Re: [Tutor] Having trouble getting mind around decimal module

2006-08-14 Thread Luke Paireepinart
Dick Moores wrote:
> I'm having trouble getting my mind around the decimal module. From 
> the tutorial () I 
> can see how to get 1/7 to, say, 32 places:
>
>  >>> from decimal import Decimal
>  >>> getcontext().prec = 32
>  >>> Decimal(1) / Decimal(7)
> Decimal("0.14285714285714285714285714285714")
>
> But I can't figure out how to compute to 32 places things like the 
> square root of 2, or the arc tangent of .41. Could someone please show me?
>
>   
I think square root calculations, and other math operations, by the 
built-in math.py package
only work on floats since they wrap math.c
So you'd have to find a pure-python implementation that supported 
Decimal objects I guess,
or write your own.
> Thanks,
>
> Dick Moores
> [EMAIL PROTECTED]
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Having trouble getting mind around decimal module

2006-08-14 Thread Alan Gauld
> >>> from decimal import Decimal
> >>> getcontext().prec = 32
> >>> Decimal(1) / Decimal(7)
> Decimal("0.14285714285714285714285714285714")
>
> But I can't figure out how to compute to 32 places things like the 
> square root of 2, or the arc tangent of .41. Could someone please 
> show me?

The first is easy:

>>> from decimal import getcontext
>>> getcontext().prec = 32
>>> Decimal(2).sqrt()
Decimal("1.4142135623730950488016887242097")

actan(0.41) is trickier... because you need to use the math module
>>> Decimal(str(math.atan(0.41)))
0.38909723105527838

And that limits the precision. If you were working with lower value
precision - say 16 digits - then it would be OK.

>>> getcontext().prec=12
>>> Decimal(str(math.atan(0.41)))
Decimal("0.389097231055")
>>>

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python on network problems

2006-08-14 Thread Alan Gauld
Diana,

It is almost certainly not a Python problem but related to how
you have the network set up. As Luke was trying to point out,
we  mifght be able to help out but your description of the
network setup wasn't clear.

We need more precise information about things like:
what OS you are using?
Are you using Domains/NIS/NDS etc?
Do you have shared drives, VNC, windows terminal server?
How do you define a 'lab'?
What do you mean by python being 'active'?
And what exactly happens when a failure occurs?

None of these things are standardised in anmy way.

Alan G



- Original Message - 
From: "Diana Hawksworth" <[EMAIL PROTECTED]>
To: "Tom Schinckel" <[EMAIL PROTECTED]>; 
Sent: Monday, August 14, 2006 7:55 AM
Subject: Re: [Tutor] Python on network problems


> Thanks Tom.  I installed the latest version on Friday - but today 
> the system went down again. I am inclined to think it is not a 
> Python problem at all. Just need someone who also has it installed 
> on a network to know if they have had any problems!!
> Diana
>
> - Original Message - 
> From: "Tom Schinckel" <[EMAIL PROTECTED]>
> To: <[EMAIL PROTECTED]>
> Sent: Monday, August 14, 2006 4:28 PM
> Subject: Re: [Tutor] Python on network problems
>
>
>> Diana Hawksworth wrote:
>>> Dear List,
>>>
>>> I have Python installed on 1 of 4 labs at my High School. The lab 
>>> is connected to a whole school network.  Students login through 
>>> the network - but Python is active in this lab only.
>>>
>>> Sometimes I have a student who simply cannot access Python, even 
>>> though he has been working on it for a number of months now. 
>>> Usually a change in username will solve the problem - but I would 
>>> like to know what is causing this to happen.
>>>
>>> The second problem is much more severe. Seems for the past three 
>>> weeks now, the entire system will crash.  It happens when we are 
>>> working on Python - so the assumption is that the program is to 
>>> blame. I cannot see that it is - but it certainly is upsetting 
>>> when it happens. Has anyone had a similar accurrence with Python 
>>> and networks? If so - what have you done about it.  If not - then 
>>> any clues about what could be happening so that I can get the 
>>> system administrator off my back - and get the system working 
>>> again!!
>>>
>>> Thanks for any suggestions.
>>>
>>> Diana
>>> ___
>>> Tutor maillist  -  Tutor@python.org
>>> http://mail.python.org/mailman/listinfo/tutor
>>>
>>>
>> It sounds a tad out of my depth, but when I first installed Python, 
>> IDLE crashed, all the time.
>>
>> Try the age old software fix: reinstall.
>>
>> Cheers
>>
>> Tom
>>
>
>
>
> 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] suggestions for read unread items datastructure

2006-08-14 Thread Luke Paireepinart
anil maran wrote:
> i m sure the users need to maintain their own data,
> but as a provider we need to store their information
> right, sessions and cookies work only during their
> stay in the site, after they exit, im sure they would
> like to come back to the same info, wont u
>
> so i was wondering what is the best way to maintain
> the list of read/unread items in a python
> datastructure, 
>   
It's not that we don't want to help you, it's that we don't understand 
what you want to do.
Consider this:
Are you trying to make a client-side program for this?
If so, why do you care about storing multiple user data?
Are you making a server that mirrors other RSS feeds for your users?
 
Are you making a client-side program that communicates with a single server
that has everyone's RSS feeds on it?

Why do you think you need to do things this way?
Why are you concerned about the data structure used to store this when 
there's
other things to be concerned about (RSS feed parsing, etc, etc.)
This should be one of the last things you worry about.

Also, Alan wasn't suggesting you use cookies.
He was stating that websites allow the client to maintain information 
about their own activities,
rather than the server trying to manage all the users.
He means that maybe you shouldn't be concerned about which RSS feeds 
your clients have been to
and let the clients take care of it themselves.

Sort of how my mailserver sends me all my mail, but my E-mail client 
takes care of marking
individual messages 'read/unread' and sorting it into folders.  There's 
no reason for the server
to need to know about any of this stuff.  Does your server really need 
to know about which
RSS feeds the clients have viewed?
> --- Alan Gauld <[EMAIL PROTECTED]> wrote:
>
>   
>> Caveat - I know nothing about RSS, it's one of those
>> web 
>> technologies that I just can't get excited about,
>> sorry...
>>
>> However...
>>
>> 
>>> there is a blog
>>> and it associated feed entries
>>> the blog posts
>>> when someone clicks it i need to maintain read
>>>   
>> status for it
>> 
>>> and when it is unclicked i need the unread status
>>> this needs to be maintianed for a huge number of
>>>   
>> usrs
>>
>> Whenever you need to maintain data for "a huge
>> number of users"
>> its time to question whether it's your job to
>> maintain the data. 
>> Maybe the users should each maintain their own data?
>> That's 
>> the idea behind cookies in a web browsing context -
>> does 
>> anything similar work for RSS?
>>
>> Alan G.
>>
>> 
>
>
> __
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] i18n Encoding/Decoding issues

2006-08-14 Thread Kent Johnson
Jorge De Castro wrote:
> Hi all,
>
> It seems I can't get rid of my continuous issues i18n with Python :(
>   
You're not alone :-)
> I've been through:
> http://docs.python.org/lib/module-email.Header.html
> and
> http://www.reportlab.com/i18n/python_unicode_tutorial.html
> to no avail.
>   
Try these:
http://www.joelonsoftware.com/articles/Unicode.html
http://jorendorff.com/articles/unicode/index.html
> Basically, I'm receiving and processing mail that comes with content (from 
> an utf-8 accepting form) from many locales (France, Germany, etc)
>
> def splitMessage() does what the name indicates, and send message is the 
> code below.
>
> def sendMessage(text):
> to, From, subject, body = splitMessage(text)
> msg = MIMEText(decodeChars(body), 'plain', 'UTF-8')
> msg['From'] = From
> msg['To'] = to
> msg['Subject'] = Header(decodeChars(subject), 'UTF-8')
>
> def decodeChars(str=""):
> if not str: return None
> for characterCode in _characterCodes.keys():
> str = str.replace(characterCode, _characterCodes[characterCode])
> return str
>
> Now as you have noticed, this only works, ie, I get an email sent with the 
> i18n characters displayed correctly, after I pretty much wrote my own 
> 'urldecode' map
>
> _characterCodes ={  "%80" : "�", "%82" : "�", "%83" : 
> "�", "%84" : "�", \
> "%85" : "�", "%86" : "�",   "%87" : 
> "�", "%88" : "�", \
> "%89" : "�", "%8A" : "�", "%8B" : 
> "�", "%8C" : "�", \
> "%8E" : "�", "%91" : "�", "%92" : 
> "�", "%93" : "�", \
> "%94" : "�", "%95" : "�", "%96" : 
> "�", "%97" : "�", \
> ...
>
> Which feels like an horrible kludge.
>   
This _characterCodes map replaces chars is the range 80-9F with a 
Unicode "undefined" marker, so I don't understand how using it gives you 
a correct result.
> Note that using urlilib.unquote doesn't do it -I get an error saying that it 
> is unable to . Replacing my decodeChars
>
> msg = MIMEText(urllib.unquote(body), 'plain', 'UTF-8')
>
> Returns content with i18n characters mangled.
>   
 From the selection of characters you have chosen to replace, my guess 
is that your source data is urlencoded Cp1252, not urlencoded UTF-8. So 
when you unquote it and then call it UTF-8, which is what the above code 
does, you get incorrect display. What happens if you change UTF-8 to 
Cp1252 in the call to MIMEText?
> Using unicode(body, 'latin-1').encode('utf-8') doesn't work either. Besides, 
> am I the only one to feel that if I want to encode something in UTF-8 it 
> doesn't feel intuitive to have to convert to latin-1 first and then encode?
>   
It doesn't work because the urlencoded text is ascii, not latin-1. I 
suspect that
  unicode(urllib.unquote(body), 'Cp12521).decode('UTF-8')
would give you what you want.
> Any ideas? I am dry on other option and really don't want to keep my kludge 
> (unless I absolutely have to)
>   
Post some of your actual data, it will be obvious whether it is encoded 
from Cp1252 or UTF-8.

Keep trying, it's worth it to actually understand what is going on. 
Trying to solve encoding problems when you don't understand the basic 
issues is unlikely to give a good solution.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to remove html ags

2006-08-14 Thread Kent Johnson
anil maran wrote:
> Human nature is not a machin... 
> 
>
> for example in the above stirng
>
> i want to remove 
> and 
Try one of these:
http://www.oluyede.org/blog/2006/02/13/html-stripper/
http://www.aminus.org/rbre/python/cleanhtml.py
>
> i tried
>
> str = str.replace('(.*)','')
>
> it doesnt work
because it looks for a literal "(.*)" in the string and replaces it with 
an empty string. Since "(.*)" doesn't appear, nothing is replaced.

Kent
> thanks
>
> 
> Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great 
> rates starting at 1¢/min. 
> 
>  
>
>
>  
> 
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>  
> 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] SGMLLib, fetching some weird data

2006-08-14 Thread Kent Johnson
Basil Shubin wrote:
> Hi friends,
>
> Please, examine attached script. I want fetch some data from online 
> resource and almost achieve this, but I can't fetch some weird formatted 
> data like this '45° Reverse Calf Press'. I got the following error:
>
> 45
>   Reverse Calf Press
> Reverse Calf Raise
> Seated Reverse Calf Press
> Traceback (most recent call last):
>File "net_exrx.py", line 226, in ?
>  exercisesList = LoadExercisesList(2, 4, 9)
>File "net_exrx.py", line 86, in LoadExercisesList
>  return parser.GetExercisesList()
>File "net_exrx.py", line 176, in GetExercisesList
>  self.exerList.append([self.desc[i],self.urls[i]])
> IndexError: list index out of range
>   
Apparently self.desc has more entries than self.urls. This would happen 
if handle_data() is called more than once for an  tag. If you put 
some print statements in your program you can probably figure out why 
this is happening.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Regex

2006-08-14 Thread Matt Williams
Dear All,

I know this has come up loads of times before, but I'm stuck with what 
should be a simple Regex problem. I'm trying to pull all the definitions 
  from a latex document. these are marked

\begin{defn}

\end{defn}

so I thought I'd write something like this:

filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex'

infile = open(filename,'r')

def_start = "\\begin\{defn\}"
def_end = "\end{defn}"

def_start_reg = re.compile(def_start)

l = 0
while l < 500:
 line = infile.readline()
 #print l, line
 res = re.search(def_start_reg,line)
 print l, res
 l = l+1

but it doesn't return any matches (BTW, I know there's a defn tag in 
that section). I thought it was my regex matching, but I checked it with 
an online checker, and also with a small bit of text:


def_start = "\\begin\{defn\}"

def_start_reg = re.compile(def_start)

text = """atom that is grounded. These formulae are useful not only for the
work on valuation but are also used in later chapters.

\begin{defn}
A Patient-ground formula is a formula which contains a grounding of
$Patient(x)$. The other atoms in the formula may be either ground
or non-ground.
\end{defn}
Having defined our patient ground formulae, we can now use formulae
of this form to define our patient values."""

res = re.search(def_start_reg, text)
print res



and this returns a MatchObject. I'm not sure why there should be any 
difference between the two - but I'm sure it's very simple.

Thanks for any tips,

Matt
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to un-import modules?

2006-08-14 Thread Dick Moores
Actually, my question is, after using IDLE to do some importing of 
modules and initializing of variables, how to return it to it's 
initial condition without closing and reopening it.

So, for example after I've done
 >>> import math, psyco
 >>> a = 4**23

How can I wipe those out without closing IDLE?
(I used to know how, but I've forgotten.)

Thanks,

Dick Moores
[EMAIL PROTECTED]

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Kermit Rose
 
 
From: Luke Paireepinart 
Date: 08/13/06 22:28:50 
To: Kermit Rose 
Cc: Danny Yoo; tutor@python.org 
Subject: Re: [Tutor] Global variables 
 
Kermit Rose wrote: 
> 
> 
> From: Danny Yoo 
> Date: 08/09/06 16:23:35 
> To: Kermit Rose 
> Cc: tutor@python.org 
> 
> 
> If I can figure out how to make my main function subroutine declare global

> variables 
> then I won't need to pass parameters most parameters to the other 
> subroutines, 
> 
> and will bypass the problem I'm having that sometimes the function
strongfac 
> SOMETIMES does not return the value it has in the subroutine, back to the 
> calling routine. 
> 
 
From: Luke Paireepinart 
 
are you asking a question?
 
 
Kermit Rose wrote: 
 
 
Yes.   How can I make a package of functions declare global variables for
passing information between
the functions in the package?
 
 
 
 
 
 
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to un-import modules?

2006-08-14 Thread Michael P. Reilly
On 8/14/06, Dick Moores <[EMAIL PROTECTED]> wrote:
Actually, my question is, after using IDLE to do some importing ofmodules and initializing of variables, how to return it to it'sinitial condition without closing and reopening it.So, for example after I've done
 >>> import math, psyco >>> a = 4**23How can I wipe those out without closing IDLE?(I used to know how, but I've forgotten.)Hi Dick,  Usually this entails removing from the "module registry and removing references to it in the code.  If you have a _really_ well used module (like one with config parameters imported into every module), then you'll have an additional step of removing it from every module.  Also, if you have use "from psyco import ...", then you will not be able to free up the module and the reference to the module easily (is it from that module, or imported from a third module? see "if paranoid: code below).
The function below deletes a module by name from the Python interpreter, the "paranoid" parameter is a list of variable names to remove from every other module (supposedly being deleted with the module).  Be VERY careful with the paranoid param; it could cause problems for your interpreter if your functions and classes are named the same in different modules.  One common occurrance of this is "error" for exceptions.  A lot of libraries have one "catch-all" exception called "error" in the module.  If you also named your exception "error" and decided to include that in the paranoid list... there go a lot of other exception objects.
def delete_module(modname, paranoid=None):    from sys import modules    try:    thismod = modules[modname]    except KeyError:    raise ValueError(modname)    these_symbols = dir(thismod)
    if paranoid:    try:    paranoid[:]  # sequence support    except:    raise ValueError('must supply a finite list for paranoid')    else:    these_symbols = paranoid[:]
    del modules[modname]    for mod in modules.values():    try:    delattr(mod, modname)    except AttributeError:    pass    if paranoid:    for symbol in these_symbols:
    if symbol[:2] == '__':  # ignore special symbols    continue    try:    delattr(mod, symbol)    except AttributeError:    pass
Then you should be able to use this like:delete_module('psyco')  ordelete_module('psyco', ['Psycho', 'KillerError'])  # only delete these symbols from every other module (for "from psyco import Psycho, KillerError" statements)
  -Arcege-- There's so many different worlds,So many different suns.And we have just one world,But we live in different ones.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to remove html ags

2006-08-14 Thread anil maran
how to do regular expressionsand remove waht is in and also the brackets<>Kent Johnson <[EMAIL PROTECTED]> wrote: anil maran wrote:> Human nature is not a machin... > >> for example in the above stirng>> i want to remove > and Try one of these:http://www.oluyede.org/blog/2006/02/13/html-stripper/http://www.aminus.org/rbre/python/cleanhtml.py>> i tried>> str = str.replace('(.*)','')>> it doesnt workbecause it looks for a literal "(.*)" in the string and replaces it with an empty string. Since "(.*)" doesn't appear, nothing is replaced.Kent> thanks>>
 > Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls. Great > rates starting at 1¢/min. >  >>>  > >> ___> Tutor maillist  -  Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor>  ___Tutor maillist  - 
 Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor 
		Do you Yahoo!? 
Get on board. You're invited to try the new Yahoo! Mail Beta.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Luke Paireepinart

> From: Luke Paireepinart 
>  
> are you asking a question?
>  
>  
> Kermit Rose wrote: 
>  
>  
> Yes.   How can I make a package of functions declare global variables for
> passing information between
> the functions in the package?
>  
>   
a 'package' meaning a module?
If you think you need global variables you're probably going about the 
problem the wrong way.
What are you trying to do?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to un-import modules?

2006-08-14 Thread Luke Paireepinart
Michael P. Reilly wrote:
> On 8/14/06, *Dick Moores* <[EMAIL PROTECTED] > 
> wrote:
>
> Actually, my question is, after using IDLE to do some importing of
> modules and initializing of variables, how to return it to it's
> initial condition without closing and reopening it.
>
> So, for example after I've done
> >>> import math, psyco
> >>> a = 4**23
>
> How can I wipe those out without closing IDLE?
> (I used to know how, but I've forgotten.)
>
while you're in the IDLE shell view, hit Ctrl+F6.  it restarts the 
interpreter.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to remove html ags

2006-08-14 Thread Luke Paireepinart
anil maran wrote:
> how to do regular expressions
> and remove waht is in and also the brackets
> <>
I'm not answering any more of your questions until you read 
http://www.catb.org/~esr/faqs/smart-questions.html
The information you want you could find in any regexp tutorial.
If you have a problem learning regular expressions and you need 
clarification about something, ask us.
This list is here to help you learn and understand the Python language, 
not to generate code for you.
:-).
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to remove html ags

2006-08-14 Thread anil maran
hi lukei tried to do this for 2 weeks using the regexpsi couldnt find itand hence i was asking you guysthanksanilLuke Paireepinart <[EMAIL PROTECTED]> wrote: anil maran wrote:> how to do regular expressions> and remove waht is in and also the brackets> <> 
		Talk is cheap. Use Yahoo! Messenger to make PC-to-Phone calls.  Great rates starting at 1¢/min.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to remove html ags

2006-08-14 Thread John Fouhy
On 15/08/06, anil maran <[EMAIL PROTECTED]> wrote:
> hi luke
> i tried to do this for 2 weeks using the regexps
> i couldnt find it
> and hence i was asking you guys
> thanks
> anil

What have you tried?  What problems were you having?

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Regex

2006-08-14 Thread Alan Gauld
> so I thought I'd write something like this:
> 
> filename = '/home/acl_home/PhD/CurrentPhD/extensions1_14.8.6.tex'
> 
> infile = open(filename,'r')
> 
> def_start = "\\begin\{defn\}"
> def_end = "\end{defn}"
> 
> def_start_reg = re.compile(def_start)
> 
> l = 0
> while l < 500:
> line = infile.readline()
> #print l, line
> res = re.search(def_start_reg,line)
> print l, res
> l = l+1

Use a for loop instead of the while loop.
And use the methods of the compiled regex object:

for n,line in enumerate(open(filename)):
res = def_start_reg.search(line)
print n,res

Does that work?

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to un-import modules?

2006-08-14 Thread Alan Gauld
>> Actually, my question is, after using IDLE to do some importing of
>> modules and initializing of variables, how to return it to it's
>> initial condition without closing and reopening it.

Doesn't Shell->Restart shell do this?

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Alan Gauld
>> If I can figure out how to make my main function subroutine declare 
>> global
>> variables then I won't need to pass parameters most parameters to 
>> the other
>> subroutines,

That may be true but you will make your code much less reusable
and much more error propne in the process. There are good reasons
why global variables are considered evil...

>> and will bypass the problem I'm having that sometimes the function
> strongfac SOMETIMES does not return the value it has in the 
> subroutine,
> back to the calling routine.

I'm not sure how you work that out. If the function uis getting bad 
data
it will still return it regardless of whether you use golobals or 
return values.

> Yes.   How can I make a package of functions declare global 
> variables for
> passing information between the functions in the package?

just use the global keyword:

###
x,y = 42,27

def f():
   global x,y
   x = 66
   y = 42
   print x+y

print x,y
f()
print x,y


But its very bad practice and

##
x,y = 42,27
def f(x,y):
x = 66
y = 42
print x+y
return x,y

print x,y
x,y = f(x,y)
print x,y
##

is much better.

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Kermit Rose
 
From: Luke Paireepinart 
Date: 08/14/06 17:17:13 
To: Kermit Rose 
Cc: Danny Yoo; tutor@python.org 
Subject: Re: [Tutor] Global variables 
 
 
> From: Luke Paireepinart 
> 
> are you asking a question? 
> 
> 
> Kermit Rose wrote: 
> 
> 
> Yes. How can I make a package of functions declare global variables for 
> passing information between 
> the functions in the package? 
> 
> 
a 'package' meaning a module? 
 

 
Yes.  I mean a module.
 
 
>
 
If you think you need global variables you're probably going about the 
problem the wrong way. 
What are you trying to do? 
 
*
 
In my module I have several functions which work together to factor integers

 
One function, called testrange is the  main calling routine.
 
It generates Tables and and passes their values to the main factoring
subroutine, named 
fermat.
 
Fermat calls a routine named strongfac.
 
There seems to be some type of bug in Python because
 
I observe that 
strongfac, depending on the number being factored,
will sometimes return  0 instead of the  factors it found.
 
I believe that if I can get my main function, testrange,
to declare a global variable to hold the caculated factor list,
then I can bypass the apparent bug in Python that actualizes only
for  a few particular  numbers to be factored.
 
Also, if I can get testrange to create global variables, then I can shorten
the parameter list of many of the
functions in the module.
 
 
Kermit   <  [EMAIL PROTECTED]  >
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Kermit Rose
 
 
From: Alan Gauld 
Date: 08/14/06 18:42:41 
To: Kermit Rose; Luke Paireepinart 
Cc: tutor@python.org; Danny Yoo 
Subject: Re: [Tutor] Global variables 
 
 
That may be true but you will make your code much less reusable 
and much more error propne in the process. There are good reasons 
why global variables are considered evil... 
 
 
*
 
I know that global variable usage can be abused.
 
But in fact I use the same variable names  in the subroutine parameter list
as in the calling routine for every function in the module.
 
So I believe that in this case global variables would be useful and not
likely to
increase errors due to confusion of global and local variables.
 
I would never have a local variable with the same name as the global
variable.
 
But in this case, it's only because of an apparent bug in Python that want
to 
bypass that I'm considering the use of global variables.
 
 
My routine strongfac calculates a value for fac in the subroutine, and the
calling routine picks up a different vaalue.
 
An illustration.
 
In strong fac:
 
fac = [1,2,3]
print fac
return fac
 
in fermat:
 
fac = strongfac(z)
print fac
 
prints [0,0,0]
 
And most of the time it does not misbehave like this.
 
It is only occasionally, and consistently with certain numbers to be
factored.
 
 
Kermit   <  [EMAIL PROTECTED] >
 
 
 
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread John Fouhy
On 15/08/06, Kermit Rose <[EMAIL PROTECTED]> wrote:
> My routine strongfac calculates a value for fac in the subroutine, and the
> calling routine picks up a different vaalue.
>
> An illustration.
>
> In strong fac:
>
> fac = [1,2,3]
> print fac
> return fac
>
> in fermat:
>
> fac = strongfac(z)
> print fac
>
> prints [0,0,0]
>
> And most of the time it does not misbehave like this.

Can you post actual code to illustrate the problem?  Don't post your
entire module; just show us the functions involved, the input that
causes the problem, and what output you expect to get.

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Luke Paireepinart
Kermit Rose wrote:
>  
>  
> From: Alan Gauld 
> Date: 08/14/06 18:42:41 
> To: Kermit Rose; Luke Paireepinart 
> Cc: tutor@python.org; Danny Yoo 
> Subject: Re: [Tutor] Global variables 
>  
>  
> That may be true but you will make your code much less reusable 
> and much more error propne in the process. There are good reasons 
> why global variables are considered evil... 
>  
>  
> *
>  
> I know that global variable usage can be abused.
>  
> But in fact I use the same variable names  in the subroutine parameter list
> as in the calling routine for every function in the module.
>  
> So I believe that in this case global variables would be useful and not
> likely to
> increase errors due to confusion of global and local variables.
>  
> I would never have a local variable with the same name as the global
> variable.
>  
>   
It sounds like you should make a Factoring class and have whichever
variables are similar for all functions be variables specific to the 
class instance
(I forgot the word for this)

Something like:

#
Class Factoring(object):
def __init__(self):
   self.var1 = ['a','b','c']
   self.var2 = 5
   self.var3 = (0)

def method1(self):
   print self.var1,self.var2
def method2(self):
   print self.var2,self.var3

fac = Factoring()
fac.method1()
fac.method2()

#-
the output would be
['a','b','c']5
5(0)

Thus you prevent global namespace pollution.
> But in this case, it's only because of an apparent bug in Python that want
> to 
> bypass that I'm considering the use of global variables.
>   
You probably shouldn't claim there's a bug in Python unless you're sure 
(I.E. have a snippet of code
that reproduces the bug that you'll share with us)
>  
>  
> My routine strongfac calculates a value for fac in the subroutine, and the
> calling routine picks up a different vaalue.
>   
do you think you could use more conventional terminology like 'function' 
and such?
I don't understand what you mean by the subroutine of the routine.
def routine():
def subroutine():
   print 'hi'
subroutine()

Is that what you mean?
or by 'subroutine' do you mean 'loop inside of function'?

By your terminology, if there's a routine that calls strongfac, doesn't 
that mean
strongfac is a subroutine?  which would mean that the value for fac is 
calculated in the subroutine of the subroutine of the calling routine?

>  
> An illustration.
>  
> In strong fac:
>  
> fac = [1,2,3]
> print fac
> return fac
>  
> in fermat:
>  
> fac = strongfac(z)
> print fac
>  
> prints [0,0,0]
>   
what is 'z'?  a random parameter?
can you give us a cut-down version of your code that just reproduces this
erratic behavior you're having a problem with?

>  
> And most of the time it does not misbehave like this.
>   
if random.randint(0,5) < 3:
malfunction()
>  
> It is only occasionally, and consistently with certain numbers to be
> factored.
>   
so with certain numbers it always occurs, with other numbers it 
sometimes occurs?
>  
>  
> Kermit   <  [EMAIL PROTECTED] >
>  
>   
Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Global variables

2006-08-14 Thread Bob Gailer
A while back you attached factor34.py. Is that the program you are 
having trouble with?
And you said it misbehaves "consistently with certain numbers to be 
factored."
What are these numbers?

-- 
Bob Gailer
510-978-4454

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python on network problems

2006-08-14 Thread Diana Hawksworth
Sorry Alan.  Replied to Luke - but didn't include that to the tutor list as a 
whole!

We are running Windows XP.  The students log in to a network server that allows 
them access to their user accounts as well as various group folders.  We have 4 
rooms full of computers - but Python is installed on each workstation in this 
room only ie, it is "active" in this room only. It is not on the network and no 
other computer rooms have access to it. The students in this room save their 
Python files to a networked "user" account - as they do with all their other 
files.

Two failures have occurred.

The first has been intermittent and to individual students only at rare times.  
A student will attempt to start IDLE - and nothing will happen.  Sometimes, 
changing that student's log in user name will solve the problem, and he then 
has access to Python again. 

The 2nd is more pervasive, and that is, whenever I have the class working with 
Python - the entire school network becomes inoperable, and the system 
administrator needs to reboot it again. Because we have been working on Python 
each time this has happened, Python is being blamed for the system failure. 
Inoperable - no one is able to open any files in any program, save any work 
they have been working on, open files - or even log in if they haven't already. 
The whole system is " frozen", from the office to every other computer in the 
school. 

Now I am inclined to think it is not a Python problem at all.  Python is 
locally and individually installed on computers in this room only.  It has no 
network access at all  - apart from files being saved in networked user 
accounts.

What I would like to know is if anyone else has had a similar problem - and it 
has been proven that Python is the cause?  If so - how was the problem solved?  

Be grateful for any advice - and hope I have made the situation clearer now.

Diana

> Alan Gauld <[EMAIL PROTECTED]> wrote:
> 
> Diana,
> 
> It is almost certainly not a Python problem but related to how
> you have the network set up. As Luke was trying to point out,
> we  mifght be able to help out but your description of the
> network setup wasn't clear.
> 
> We need more precise information about things like:
> what OS you are using?
> Are you using Domains/NIS/NDS etc?
> Do you have shared drives, VNC, windows terminal server?
> How do you define a 'lab'?
> What do you mean by python being 'active'?
> And what exactly happens when a failure occurs?
> 
> None of these things are standardised in anmy way.
> 
> Alan G
> 
> 
> 
> - Original Message - 
> From: "Diana Hawksworth" <[EMAIL PROTECTED]>
> To: "Tom Schinckel" <[EMAIL PROTECTED]>; 
> Sent: Monday, August 14, 2006 7:55 AM
> Subject: Re: [Tutor] Python on network problems
> 
> 
> > Thanks Tom.  I installed the latest version on Friday - but today 
> > the system went down again. I am inclined to think it is not a 
> > Python problem at all. Just need someone who also has it installed 
> > on a network to know if they have had any problems!!
> > Diana
> >
> > - Original Message - 
> > From: "Tom Schinckel" <[EMAIL PROTECTED]>
> > To: <[EMAIL PROTECTED]>
> > Sent: Monday, August 14, 2006 4:28 PM
> > Subject: Re: [Tutor] Python on network problems
> >
> >
> >> Diana Hawksworth wrote:
> >>> Dear List,
> >>>
> >>> I have Python installed on 1 of 4 labs at my High School. The lab 
> >>> is connected to a whole school network.  Students login through 
> >>> the network - but Python is active in this lab only.
> >>>
> >>> Sometimes I have a student who simply cannot access Python, even 
> >>> though he has been working on it for a number of months now. 
> >>> Usually a change in username will solve the problem - but I would 
> >>> like to know what is causing this to happen.
> >>>
> >>> The second problem is much more severe. Seems for the past three 
> >>> weeks now, the entire system will crash.  It happens when we are 
> >>> working on Python - so the assumption is that the program is to 
> >>> blame. I cannot see that it is - but it certainly is upsetting 
> >>> when it happens. Has anyone had a similar accurrence with Python 
> >>> and networks? If so - what have you done about it.  If not - then 
> >>> any clues about what could be happening so that I can get the 
> >>> system administrator off my back - and get the system working 
> >>> again!!
> >>>
> >>> Thanks for any suggestions.
> >>>
> >>> Diana
> >>> ___
> >>> Tutor maillist  -  Tutor@python.org
> >>> http://mail.python.org/mailman/listinfo/tutor
> >>>
> >>>
> >> It sounds a tad out of my depth, but when I first installed Python, 
> >> IDLE crashed, all the time.
> >>
> >> Try the age old software fix: reinstall.
> >>
> >> Cheers
> >>
> >> Tom
> >>
> >
> >
> >
> >
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] What does import really do?

2006-08-14 Thread jim stockford

For example,
import os
import sys

My take is that one uses the import keyword in a
program.
The Python interpreter reads the program and
generates machine code.
The import keyword directs the Python interpreter
to find some library (which is not necessarily named,
certainly not necessarily named in the import
statement), get some portion of machine code from
the library, bind that machine code in current
program's process space, and integrate the names
of the imported machine code with the program's
namespace (probably keeping the namespace of
the imported code as a separate name domain).

I'm just guessing, of course. Can anyone explain
what is really going on under the hood? I'll be
grateful for a description of the behavior.

newbie

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] processing multi entry logs

2006-08-14 Thread Reed L. O'Brien
I have a log file. Essentially the file has 2 important entries for each process id. One when the process starts with an id and a another piece of data. the second is when the process finishes, with the result also with the process id. I need to get data from both to make a sensible representation of the data. The file can be very large, in excess of 400MB. And the process id entries can be any random distance apart.I am hoping for input regarding the best way to do it.I can't think of an efficient way to store the data from the first entry. Keep processing line by line and check against the partially recorded ids?Maintain seperate lists and merge them at the end?Ideas and input appreciated?___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does import really do?

2006-08-14 Thread Luke Paireepinart
jim stockford wrote:
Hi Jim.
> For example,
> import os
> import sys
>
> My take is that one uses the import keyword in a
> program.
> The Python interpreter reads the program and
> generates machine code.
> The import keyword directs the Python interpreter
> to find some library (which is not necessarily named,
> certainly not necessarily named in the import
> statement), get some portion of machine code from
> the library, bind that machine code in current
> program's process space, and integrate the names
> of the imported machine code with the program's
> namespace (probably keeping the namespace of
> the imported code as a separate name domain).
>   
I don't know when code is converted to machine code, but here's how I think
import works.
you say 'find some library ... not necessarily named in the import 
statement.'
I don't know what you mean by this.
If the user says 'import os'
first python checks for
'os.pyc' in the current working directory.
if it doesn't find this, it looks if 'os.py' is there.
If not, then it checks the PYTHONPATH (I believe)
for 'os.pyc' and 'os.py' files.

When the user says 'import x' the name of the
actual filename will be x.pyc or x.py
for example:

# config.py in C:/exprog
a = 'hi'
b = 'hello'
#

# main.py in C:/exprog
import config
print config.a
print config.b
#

when I run main.py for the first time, it looks for
'config.pyc' because of the 'import config' line.
It doesn't find it, so it compiles 'config.py' into 'config.pyc'
and then imports it.  Note that it's not in the global namespace
unless I say 'from config import *'
instead, you have to reference values stored in the 'config' module
using the 'config. ' syntax.

if I were to delete config.py and config.pyc, it would look in
C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc'
because that's where my python is installed.

At least that's how I think import works :)
> I'm just guessing, of course. Can anyone explain
> what is really going on under the hood? I'll be
> grateful for a description of the behavior.
>
> newbie
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] processing multi entry logs

2006-08-14 Thread Luke Paireepinart
Reed L. O'Brien wrote:
> I have a log file. Essentially the file has 2 important entries for 
> each process id. One when the process starts with an id and a another 
> piece of data. the second is when the process finishes, with the 
> result also with the process id. I need to get data from both to make 
> a sensible representation of the data. The file can be very large, in 
> excess of 400MB. And the process id entries can be any random distance 
> apart.
>
Are you in control of the format of the log file?  Is it possible that, 
in the future, you could instead log everything in an SQL table or 
something of the sort
to make it easier to get at the data you want?
I understand that now you have a log that you need to parse, but if 
every time you need something from the log you have to parse 400MB of text
it might take a little longer than you'd like.

> I am hoping for input regarding the best way to do it.
>
> I can't think of an efficient way to store the data from the first entry. 
>
> Keep processing line by line and check against the partially recorded ids?
>
>
> Maintain seperate lists and merge them at the end?

You could do something like (in semi-python)
tasks = {}
for item in logfile.readlines():
if item is start_data:
   tasks[process_id] = [start_data-process_id]
elif item is end_data:
   tasks[process_id].append(end_data-process_id)

This should work because you said the process_id is common to both the 
startdata and enddata.
The only problem is determining if the entry is start or end data.

Now you have a dictionary where the keywords are the processids and the 
data is
a two-element list.
Does that do what you need?
HTH,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What does import really do?

2006-08-14 Thread jim stockford

many thanks.
wrt import and what's named, in the case of
the PIL library, the import statement can be
import Image # not import PIL
my presumption is that the PIL whatever-it-is
contains a set of whatever-they-are, one of
which is named Image.
I like to use proper terminology, by way of
explaining my avoidance above. Might help
to know I very much liked working in assembler
and infer possible assembler correspondences
when I wonder about code behavior.
Your rundown of search order is helpful.
more thanks.
jim


On Aug 14, 2006, at 7:52 PM, Luke Paireepinart wrote:

> jim stockford wrote:
> Hi Jim.
>> For example,
>> import os
>> import sys
>>
>> My take is that one uses the import keyword in a
>> program.
>> The Python interpreter reads the program and
>> generates machine code.
>> The import keyword directs the Python interpreter
>> to find some library (which is not necessarily named,
>> certainly not necessarily named in the import
>> statement), get some portion of machine code from
>> the library, bind that machine code in current
>> program's process space, and integrate the names
>> of the imported machine code with the program's
>> namespace (probably keeping the namespace of
>> the imported code as a separate name domain).
>>
> I don't know when code is converted to machine code, but here's how I 
> think
> import works.
> you say 'find some library ... not necessarily named in the import 
> statement.'
> I don't know what you mean by this.
> If the user says 'import os'
> first python checks for
> 'os.pyc' in the current working directory.
> if it doesn't find this, it looks if 'os.py' is there.
> If not, then it checks the PYTHONPATH (I believe)
> for 'os.pyc' and 'os.py' files.
>
> When the user says 'import x' the name of the
> actual filename will be x.pyc or x.py
> for example:
>
> # config.py in C:/exprog
> a = 'hi'
> b = 'hello'
> #
>
> # main.py in C:/exprog
> import config
> print config.a
> print config.b
> #
>
> when I run main.py for the first time, it looks for
> 'config.pyc' because of the 'import config' line.
> It doesn't find it, so it compiles 'config.py' into 'config.pyc'
> and then imports it.  Note that it's not in the global namespace
> unless I say 'from config import *'
> instead, you have to reference values stored in the 'config' module
> using the 'config. ' syntax.
>
> if I were to delete config.py and config.pyc, it would look in
> C:/python24/Lib/site-packages/ for a 'config.py' and 'config.pyc'
> because that's where my python is installed.
>
> At least that's how I think import works :)
>> I'm just guessing, of course. Can anyone explain
>> what is really going on under the hood? I'll be
>> grateful for a description of the behavior.
>>
>> newbie
>>
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] more rps

2006-08-14 Thread Christopher Spears
Here is the latest version of my Rock, Paper, Scissors
game:

#!/usr/bin/python

import random
random.seed()

class Human:
def __init__(self):
self.points = 0
self.choice = " "

def plays(self):
fromUser = raw_input("Pick (R)ock, (P)aper, or
(S)cissors! ")
translate = {'r':'rock', 's':'scissors',
'p':'paper'} 
try:
self.choice = translate[fromUser.lower()]
except KeyError:
print 'Invalid Response'

class Computer:
def __init__(self):
self.points = 0
self.choice = " "

def plays(self):
comp_choice = random.randint(0,2)
if comp_choice == 0:
self.choice = 'rock'
elif comp_choice == 1:
self.choice = 'paper'
else:
self.choice = 'scissors'

def compare_objects(human, computer):
print "Human picked ", human.choice
print "Computer picked", computer.choice
results = { 'rock' : {'rock' : 'draw', 'paper': 0,
'scissors': 1},
'paper' : {'rock' : 1, 'paper': 'draw', 'scissors':
0},
'scissors' : {'rock' : 0, 'paper' : 1, 'scissors' :
'draw'}
}

outcome = results[human.choice][computer.choice]
if outcome == 0:
print "Computer Wins!"
computer.points = computer.points + 1
elif outcome == 1:
print "Human Wins!"
human.points = human.points + 1
else:
print "Draw!"


if __name__ == "__main__":
print "Welcome to Rock, Paper, Scissors!"
final_points = raw_input("Play to how many points? ")
human = Human()
computer = Computer()
while (human.points < final_points or computer.points
< final_points):
human.plays()
computer.plays()
compare_objects(human, computer)
print "Score:\tHuman: ",human.points,"\tComputer:
",computer.points
print "Game Over!"


I actually figured out how to build the 2x2 matrix. 
I'm quite proud of this.  Like all of my good ideas,
the answer came to me in the shower. :-)

Unfortunately, my while loop doesn't seem to be
working.  I've played around with it with no success. 
Hints, anyone?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor