Re: [Tutor] Livewires Help
The official tutor only covers core Python, not even Tkinter. But I believe there is a separate LiveWires tutor somewhere, although I've never used LiveWires personally. In fact, although I've seen it mentioned here several times I confess I don't even know what LiveWires is! I probably should investigate at some point... Alan G. - Original Message - From: <[EMAIL PROTECTED]> To: Sent: Tuesday, March 22, 2005 10:49 PM Subject: [Tutor] Livewires Help > Does python tutor cover livewires w.s help? > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] .readlines() condensing multiple lines
> Unless I'm mistaken .readlines() is supposed to return a list, where > each index is a line from the file that was handed to it. Well I'm > finding that it's putting more than one line of my file into a single > list entry, and separating them with \r. \r is the carriage return marker which is used as the end of line character on some OS. So Python sees \r as the end of the line regardless of how your system displays the file on screen. Typically what happens is you view the file in an application that autrowraps long lines so it looks like multiple lines on screen but in fact it is one long line in the file. In that case Python will only see the single long line. > Surely there's a way to have a > one to one correlation between len(list) and the lines in the file the > list was derived from...? Should just work. If its not the situation described above give us some more detail and maybe a cut down example of the file content where we can see the effect? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] primes - sieve of odds
C Smith schrieb: Hi Gregor, I had done the same thing. I also noted that assigning (or inserting) an element into a list is faster than creating a new list: l.insert(0,2) is faster than l = [2]+l. ### def sieve (maximum): if maximum < 2: return [] limit = int(maximum**0.5) nums = range(1,maximum+1,2) nums[0] = None for p in nums: if p: if p > limit: break nums[(p*p)//2::p] = [False]*(1+(maximum//p- p)//2) nums[0] = 2 return filter(None, nums) ### /c Well done! Now it would be fine to have an *equally fast* infinite prime number generator. Has anybody any suggestions? Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] What does Python gain by having immutable types?
> After showing him to change it to this > s1 = s1.replace("is a", "is a short") > He then asked > Why is it that the sort operation modfies the original list variable? > > l1=[3,44,1,22] > l1.sort() > l1 > [1, 3, 22, 44] > > I don't know, but I think it has something to do with strings being > immutable, whiles lists are mutable. It's related but personally I think the sort() thing is probably more to do with saving memory and performance since a list can be very big and returning a sorted copy could be expensive. OTOH it does add a big inconsistency in the language and is a common gotcha for beginners > So, other than the non-informative answer " because that's how the > language was written" are there any other reasons how Python benefits > from immutable types? Quite often the only answer is "just because". Some features are the way they are because that's Guido's pesonal preference. Others may disagree with him but it's his language and he gets to pick what he thinks is best - the benign dictator syndrome. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Livewires
If you have any questions on Livewires (do you mean the Scripture Union pygame wrapper ?). We will try to help.Send instant messages to your online friends http://uk.messenger.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] blocking user access
Hi! I need help on blocking user access to a message box - for example, the program could provide an answer to an input. At the moment, the user has access to - and can type into - that "answer" space. How do I prevent that from happening please? Diana - a very newbie! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] blocking user access
Hi Diana, Welcome. Are you using IDLE? Could you provide a copy of your code? Regards, Liam Clarke Still a newbie, but not as much. :) On Wed, 23 Mar 2005 20:59:02 +1100, Diana Hawksworth <[EMAIL PROTECTED]> wrote: > > Hi! I need help on blocking user access to a message box - for example, the > program could provide an answer to an input. At the moment, the user has > access to - and can type into - that "answer" space. How do I prevent that > from happening please? > > Diana - a very newbie! > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] List comprehensions
Hi, Is there a way to apply multiple actions within one list comprehension? i.e. instead of a = [] for i in x: i.pop(3) g = [ int(item) for item in i] a.append(g) Is there any guides to this (possibly obtuse) tool? Regards, Liam Clarke PS I can see how nested list comprehensions can quickly lose readability. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] .readlines() condensing multiple lines
Liam Clarke wrote: Oh right, From his email, I got the impression he was getting a list like - [[abc\rdef\rghi\r]] We really need a clarification of what is in the original file and what results he is getting. My impression is that it is mixed line endings so the result of readlines is multiple strings some of which contain data from multiple lines, but it's really not clear from the OP. Anyway, Mike, it seems clear that your file has line endings in it which are not consistent with the default for your OS. If reading with universal newlines doesn't solve the problem, please let us know what OS you are running under and give more details about the data. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Livewires Help
Alan Gauld wrote: The official tutor only covers core Python, not even Tkinter. But I believe there is a separate LiveWires tutor somewhere, although I've never used LiveWires personally. In fact, although I've seen it mentioned here several times I confess I don't even know what LiveWires is! I probably should investigate at some point... Livewires is a set of worksheets containing problem sets and tutorial material for teaching Python. It was created for teaching young people in a summer camp setting. http://www.livewires.org.uk/python/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] blocking user access
Diana Hawksworth wrote: Hi! I need help on blocking user access to a message box - for example, the program could provide an answer to an input. At the moment, the user has access to - and can type into - that "answer" space. How do I prevent that from happening please? It sounds like you want to disable writing into a text field in your gui? Are you using Tkinter or another GUI toolkit? In Tkinter you could use a Label widget, which is never editable, or you could use a Text widget with its 'state' option set to 'DISABLED' like this: t=Text(state=DISABLED) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
Liam Clarke wrote: Hi, Is there a way to apply multiple actions within one list comprehension? i.e. instead of a = [] for i in x: i.pop(3) g = [ int(item) for item in i] a.append(g) You can nest list comps. Except for the pop, the above can be written a = [ [ int(item) for item in i] for i in x ] which is pretty readable. There is probably some way to get the pop in there too but I avoid list comps with side effects as bad style. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] List comprehensions
I'm not sure if you can or want to do this solely one list comprehension. You could make a helper function and use map: ### def helper(i): i.pop(3) return map(int, i) a = map(helper, x) ### Description of map: http://docs.python.org/lib/built-in-funcs.html I think map is a little cleaner is some cases. Not sure if its more Pythonic, I'm still trying to figure out exactly what that means. The need to pop(3) off the list makes a pure functional solution kinda hard. Thanks, Ryan -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Liam Clarke Sent: Wednesday, March 23, 2005 5:44 AM To: Tutor Tutor Subject: [Tutor] List comprehensions Hi, Is there a way to apply multiple actions within one list comprehension? i.e. instead of a = [] for i in x: i.pop(3) g = [ int(item) for item in i] a.append(g) Is there any guides to this (possibly obtuse) tool? Regards, Liam Clarke PS I can see how nested list comprehensions can quickly lose readability. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ 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] List comprehensions
Liam Clarke wrote: Is there any guides to this (possibly obtuse) tool? Think of it this way. A list comprehension generates a new list. So, you should think about list comps whenever you have old_list -> new_list style behavior. There are two advantages to list comps over map: 1) a list comp can use a predicate to filter results [ x for x in mylist if is Prime(x) ] for instance. that would be map(lambda x: x, filter(isPrime, mylist)) which is a little more dense. 2) usually there is no need for a lambda. Not that there is anything wrong with lambdas mind you (-: ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
Liam Clarke wrote: Is there any guides to this (possibly obtuse) tool? http://docs.python.org/tut/node7.html#SECTION00714 http://www.amk.ca/python/2.0/index.html#SECTION00060 Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Getting error that calendar is underfined when importing calendar module
Hi all. I am using Python 2.4 on a Slackware Linux box and am having a problem importing the calendar module into a program that I am writing. The code is simple and looks like this: import cgitb, os, sys cgitb.enable() sys.strerr = sys.stdout import cgi import time import calendar print "Content-Type: text/html\n\n" print print "\n\n" #Get date variables from datetime import datetime date = datetime.now().date() today= date.strftime("%m %Y") thisyear = date.strftime("%Y") thismonth = date.strftime("%m") #Print calendar for the current month calendar.prmonth(int(thisyear),int(thismonth)) - For some reason that I don't understand, I get an error when I use this code in a cgi way (run the file out of cgi-bin) but not when I type it from the command line. The error I get is this: /var/www/cgi-bin/calendar.py 43 calendar.prmonth(int(thisyear),int(thismonth)) calendar = , calendar.prmonth undefined, builtin int = , thisyear = '2005', thismonth = '03' AttributeError: 'module' object has no attribute 'prmonth' args = ("'module' object has no attribute 'prmonth'",) The calendar module description says there is a prmonth, and as I said, it works from the command line. Can anyone tell me what I am missing? Vicki ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting error that calendar is underfined when importing calendar module
The cgi is importing itself when you 'import calendar'. Try renaming your calendar.py to something else like calendar-cgi.py Kent Vicki Stanfield wrote: Hi all. I am using Python 2.4 on a Slackware Linux box and am having a problem importing the calendar module into a program that I am writing. The code is simple and looks like this: import cgitb, os, sys cgitb.enable() sys.strerr = sys.stdout import cgi import time import calendar print "Content-Type: text/html\n\n" print print "\n\n" #Get date variables from datetime import datetime date = datetime.now().date() today= date.strftime("%m %Y") thisyear = date.strftime("%Y") thismonth = date.strftime("%m") #Print calendar for the current month calendar.prmonth(int(thisyear),int(thismonth)) - For some reason that I don't understand, I get an error when I use this code in a cgi way (run the file out of cgi-bin) but not when I type it from the command line. The error I get is this: /var/www/cgi-bin/calendar.py 43 calendar.prmonth(int(thisyear),int(thismonth)) calendar = , calendar.prmonth undefined, builtin int = , thisyear = '2005', thismonth = '03' AttributeError: 'module' object has no attribute 'prmonth' args = ("'module' object has no attribute 'prmonth'",) The calendar module description says there is a prmonth, and as I said, it works from the command line. Can anyone tell me what I am missing? Vicki ___ 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] .readlines() condensing multiple lines
Liam, "rU" worked like a charm. My previous syntax where the lines were condensing was: fOpen = file(f, "r") fRead = fTmp.readlines() In this instance the size of fRead would not correspond to my line numbers. With fOpen = file(f, "rU") it now does. Thanks :) On Mar 22, 2005, at 7:15 PM, Liam Clarke wrote: From the docs - In addition to the standard fopen() values mode may be 'U' or 'rU'. If Python is built with universal newline support (the default) the file is opened as a text file, but lines may be terminated by any of '\n', the Unix end-of-line convention, '\r', the Macintosh convention or '\r\n', the Windows convention. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support mode 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen. So, try x = file(myFile, 'rU').readlines() Or try: x = file(myFile, 'rU') for line in x: #do stuff Let us know how that goes. Regards, Liam Clarke PS Worse come to worse, you could always do - x = file(myFile, 'r').read() listX = x.split('\r') On Tue, 22 Mar 2005 17:10:43 -0800, Mike Hall <[EMAIL PROTECTED]> wrote: Unless I'm mistaken .readlines() is supposed to return a list, where each index is a line from the file that was handed to it. Well I'm finding that it's putting more than one line of my file into a single list entry, and separating them with \r. Surely there's a way to have a one to one correlation between len(list) and the lines in the file the list was derived from...? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting error that calendar is underfined when importing calendar module
> The cgi is importing itself when you 'import calendar'. Try renaming your > calendar.py to something > else like calendar-cgi.py > > Kent Thanks. I was almost there, having noticed that dir(calendar) was different when run from the script than in an interactive session. Vicki P.S. Now to parse the data. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] .readlines() condensing multiple lines
On Mar 23, 2005, at 12:53 AM, Alan Gauld wrote: Typically what happens is you view the file in an application that autrowraps long lines so it looks like multiple lines on screen but in fact it is one long line in the file. In that case Python will only see the single long line. I'm using subEthaEdit, which will autowrap long lines, but it also displays line numbers, so there's no doubt where one begins and ends :) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] .readlines() condensing multiple lines
On Mar 23, 2005, at 3:17 AM, Kent Johnson wrote: Anyway, Mike, it seems clear that your file has line endings in it which are not consistent with the default for your OS. If reading with universal newlines doesn't solve the problem, please let us know what OS you are running under and give more details about the data. Kent, reading universal did indeed solve my problem, but for the record I'm on OSX, and was reading from a standard plain text file. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] .readlines() condensing multiple lines
Mike Hall wrote: On Mar 23, 2005, at 3:17 AM, Kent Johnson wrote: Anyway, Mike, it seems clear that your file has line endings in it which are not consistent with the default for your OS. If reading with universal newlines doesn't solve the problem, please let us know what OS you are running under and give more details about the data. Kent, reading universal did indeed solve my problem, but for the record I'm on OSX, and was reading from a standard plain text file. OK good. OSX uses line feed (\n) for the line separator. It sounds like your text file has mixed line endings. Mac OS 9 uses carriage return (\r) for line separator, maybe your file has some old data mixed in? Anyway, I'm glad you got it working! Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
Ryan Davis wrote: I think map is a little cleaner is some cases. Not sure if its more Pythonic, I'm still trying to figure out exactly what that means. map is (probably) going to be removed in Python3000 :-( So it's probably better to not get into the habit of using it. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] blocking user access
Diana Hawksworth wrote: Hi! I need help on blocking user access to a message box - for example, the program could provide an answer to an input. At the moment, the user has access to - and can type into - that "answer" space. How do I prevent that from happening please? Are you using Tkinter? You could bind '' to nothing in the entry widget. eg: self.answer = Tkinter.Entry(master) def noop(e): return 'break' self.answer.bind('', noop) --- actually, scratch that. For Tkinter, just make the widget disabled. self.answer.config(state=Tkinter.DISABLED) Just remember that it needs to be enabled when you put the answer in. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
> Is there a way to apply multiple actions within one list comprehension? Write a function? def foo(i): # do stuff to i return i [foo(i) for i in alist] Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] problems with dictionary
Hi, was wondering whether you can help? Say I got a dictionary of keys:values : And what I want to do is depending on what key (a,b,c) the person presses, I want to output the value (tom, dic, harry). So I program like this: import Tkinter D={a:"tom", b:"dick", c:"harry"} text.bind('', self.Conv) def Conv(self,event): if D.has_key(event.keysym): str="The name is"+str self.text.insert(END,str) return 'break' (If I had to do each one (i.e. without the dictionary) I would do as follows: def Conv(self,event): if event.keysym==a: str="tom" self.text(END, str) return 'break' ) There is clearly a mistake in the first function, only thing is I cannot spot it and thus the thing does not work. Any ideas? Igor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] List comprehensions
Geez, that's pretty bad. I've got to stop playing with code when I'm tired. Thanks all. On Wed, 23 Mar 2005 20:24:32 -, Alan Gauld <[EMAIL PROTECTED]> wrote: > > Is there a way to apply multiple actions within one list > comprehension? > > Write a function? > > def foo(i): ># do stuff to i >return i > > [foo(i) for i in alist] > > Alan G. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with dictionary
On Wed, 23 Mar 2005 20:49:11 -, Igor Riabtchuk <[EMAIL PROTECTED]> wrote: > > Hi, > was wondering whether you can help? > > Say I got a dictionary of keys:values : > > And what I want to do is depending on what key (a,b,c) the person presses, I > want to output the value (tom, dic, harry). > > So I program like this: > > import Tkinter > > > D={a:"tom", b:"dick", c:"harry"} > > > text.bind('', self.Conv) > > def Conv(self,event): > if D.has_key(event.keysym): > str="The name is"+str > self.text.insert(END,str) > return 'break' > In line 3 of the Conv function, you write "str="The name is" + str . However, str has yet to be defined, from what I can tell. Thus, Python should throw a NameError. Unforutnately, you haven't included the exception that Python gives you with this email, so I can't really help you much more than that. To get a value from a dictionary D, simply do: >>> D = {1:'test', 2:'monkey', 3:'apple'} >>> D[2] 'monkey' You should read the Python Tutorial at http://docs.python.org/tut/tut.html . > (If I had to do each one (i.e. without the dictionary) I would do as > follows: > > def Conv(self,event): > if event.keysym==a: > str="tom" > self.text(END, str) > return 'break' > ) > > There is clearly a mistake in the first function, only thing is I cannot > spot it and thus the thing does not work. Send us the exception python gives you and we may be able to help you more. Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Dictionary blues...
I posted the wrong code before. The code is: from Tkinter import * D={a:"tom", b:"dick", c:"harry"} text.bind('', self.Conv) def Conv(self,event): if D.has_key(event.keysym): str=D[event.keysym] self.text.insert(END,str) return 'break' The error message says wrong syntax... What I am basically trying to do is to allow the output of dictionary values for each keyboard button pressed. Igor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary blues...
On Wed, 23 Mar 2005, Igor Riabtchuk wrote: > I posted the wrong code before. The code is: > > from Tkinter import * > > D={a:"tom", b:"dick", c:"harry"} > > text.bind('', self.Conv) > > def Conv(self,event): > if D.has_key(event.keysym): > str=D[event.keysym] > self.text.insert(END,str) > return 'break' > > The error message says wrong syntax... Hi Igor, Can you show us the exact error message? Copy and paste it, as well as the "traceback", so we can figure out why it thinks there's a problem with syntax. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with dictionary
> D={a:"tom", b:"dick", c:"harry"} You don't have quotes around the keys. > > text.bind('', self.Conv) > > def Conv(self,event): The fact that you have 'self' as a first parameter to COnv and as a second argument to bind suggests this is all part of a class definition? Is D part off the same class? If so you need: >if D.has_key(event.keysym): if self.D.has_key(event.keysym) self.text.insert(END,str) And you use self.text here but not where you call bind? It seems that this is only pseudo code. It might be easier if you send us the real code - or a fragment that shows the same problem. Also you don't say what does happen? Is there an error message in the console? Does anything get printed? Error reports are extremely helpful in diagnosing problems. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems with dictionary
On Mar 23, 2005, at 21:55, Bill Mill wrote: In line 3 of the Conv function, you write "str="The name is" + str . However, str has yet to be defined, from what I can tell. Thus, Python should throw a NameError. Unforutnately, you haven't included the exception that Python gives you with this email, so I can't really help you much more than that. Also, rename it. The str name is already used by a Python built-in (namely, the string datatype). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] primes - sieve of odds
On Wednesday, Mar 23, 2005, at 04:00 America/Chicago, [EMAIL PROTECTED] wrote: Now it would be fine to have an *equally fast* infinite prime number generator. Has anybody any suggestions? I think when you add the condition of it being an infinite generator, you are changing the rules and can't end up with something as fast. What makes the sieve so fast is that we are generating all the primes in a given range using a very simple "strike out" method. In the infinite generator scenario, you will get all the primes up to n with the sieve and can yield those back, but at some point you will have to stop and get "the next one." To get the next one you will have to pick a range in which a next prime is likely to be found. The previous primes can be used to clear out this range. What follows is an attempt based on the previous tutor-evolved sieve that extends the range in which to find the next prime by a factor of 2 over the last known prime. A similar algorithm is on ASPN (I bellieve), under Space-efficient version of sieve of Eratosthenes. D. Eppstein, May 2004 It's slower than the sieve but about twice as fast as Eppstein's up to 1,000,000. I'll leave it to someone else to see when it finally blows up :-) The output of primes was checked through 1,000,000 against Eppstein's generator without error. /c ### def esieve(): '''extended sieve generator that returns primes on each call. When the end of the existing list is reached, more primes are sought in the range that extends to twice the last known prime. The known primes are used to clear out this extended range using the Sieve of Eratosthenes.''' # get started with primes less than 100; you need at least [2, 3] primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] i=0 while 1: yield primes[i] i+=1 if i==len(primes): #extend range minn=primes[-1]+2 #this is an odd number maxx=2*minn+1 #there should be a prime in this range; +1 makes it odd sqrt=int(maxx**.5) #don't use primes bigger than this length = (maxx-minn)//2 #this is used for computing the crossing out None values nums=range(minn,maxx+1,2) #here is the range in which a primes will be found for p in primes: if p>sqrt:break j=minn%p #find out where the striking out should start if j<>0: j=(p-j) #if evens were present, this is where to start, but... if (minn+j)%2==0:j+=p #if it lands on an even, go to the next one j//=2 #and now account for the fact that evens aren't present nums[j::p]=[None]*(1+(length-j)//p) #cross out multiples of p x=filter(None,nums) #clean up the range assert len(x)>0 #there should be a prime in here, but check anyway primes.extend(x) #add these to the existing primes and continue yielding ### ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary blues...
Igor, > I posted the wrong code before. The code is: Is this the actual code you have written? If so it is so far from being working code that it suggests you need to back up a little and work at the basics of Python before trying to tackle Tkinter and GUIs. I'll assume this really is your code and make some comments... > from Tkinter import * > > D={a:"tom", b:"dick", c:"harry"} You need to put the keys in quotes too > text.bind('', self.Conv) self is only used to access the members of a class, you don't have any class so you don't need self. You also don't, at this stage, have anything called 'text' so you can't bind anything to it. You need to create a text widget which in turn it parented under a Tk object top = Tk() text = Text(top) text.bind('', Conv) But even here, Conv hasn't been defined yet so you need to move the Conv definition above those lines. > def Conv(self,event): You can remove the self fro the parameter list, its only needed if this is a method of a class. >if D.has_key(event.keysym): > str=D[event.keysym] >self.text.insert(END,str) You can remove the 'text.' thats only used if text were part of a class, which in this case it isn't. Also you probably want to indent the insert line as part of the if clause. >return 'break' And before anything works you need to 'pack' the text widget and set the event loop running: text.pack() top.mainloop() > The error message says wrong syntax... I'm sure it said a lot more than that. Please send the whole error message, the bit that tells us what exactly Python thought was wrong and where. In this case there is so much that is wrong it doesn't matter too much but in future it will be important. The more you help us the more we can help you. If the above doesn't make sense can I suggest you try building a textual version first using the dictionary and raw_input to read the keys from the console. Once you have the basics working putting it into a GUI will be much easier. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary blues...
My deepest and most sincere apologies - cooking dinner for the family and posting questions do not mix, I keep making mistakes in the code I type. Once again my apologies - here's the code as it is in my source: import sys, os, unicodedata from Tkinter import * class CRED(Frame): def __init__(self): Frame.__init__(self) self.txt=Text(self) self.txt.bind('', self.conv) self.txt.pack() self.pack() self.txt.focus() def conv(self,event): if event.keysym=='t': str='p' self.txt.insert(END,str) return 'break' app=CRED() app.mainloop() This works - i.e. when I press 't' on the keyboard, it gives me 'p'. What I want to do is, instead of coding a conversion for each letter separately using a long "if elif" sequence, to put all the conversion values into the dictionary and then a general function for each keypress that would take the values out of the dictionary. E.g. - say I have dictionary D={'p':'t','t':'z'} Instead of coding the conv function for each letter: if event.keysym=='p': str='t' elif event.keysym=='t': str='z' put all the conversion values into a dictionary and make the function use the key:value pairs from dictionary. I hope I am making sense. Igor - Original Message - From: "Alan Gauld" <[EMAIL PROTECTED]> To: "Igor Riabtchuk" <[EMAIL PROTECTED]>; Sent: Wednesday, March 23, 2005 11:17 PM Subject: Re: [Tutor] Dictionary blues... Igor, I posted the wrong code before. The code is: Is this the actual code you have written? If so it is so far from being working code that it suggests you need to back up a little and work at the basics of Python before trying to tackle Tkinter and GUIs. I'll assume this really is your code and make some comments... from Tkinter import * D={a:"tom", b:"dick", c:"harry"} You need to put the keys in quotes too text.bind('', self.Conv) self is only used to access the members of a class, you don't have any class so you don't need self. You also don't, at this stage, have anything called 'text' so you can't bind anything to it. You need to create a text widget which in turn it parented under a Tk object top = Tk() text = Text(top) text.bind('', Conv) But even here, Conv hasn't been defined yet so you need to move the Conv definition above those lines. def Conv(self,event): You can remove the self fro the parameter list, its only needed if this is a method of a class. if D.has_key(event.keysym): str=D[event.keysym] self.text.insert(END,str) You can remove the 'text.' thats only used if text were part of a class, which in this case it isn't. Also you probably want to indent the insert line as part of the if clause. return 'break' And before anything works you need to 'pack' the text widget and set the event loop running: text.pack() top.mainloop() The error message says wrong syntax... I'm sure it said a lot more than that. Please send the whole error message, the bit that tells us what exactly Python thought was wrong and where. In this case there is so much that is wrong it doesn't matter too much but in future it will be important. The more you help us the more we can help you. If the above doesn't make sense can I suggest you try building a textual version first using the dictionary and raw_input to read the keys from the console. Once you have the basics working putting it into a GUI will be much easier. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dictionary blues...
I just solved it :) thank you all for chastising me :) particularly Alan Gauld - you save me again :) I reckon I will have to put a credit for you in the code :) Igor - Original Message - From: "Igor Riabtchuk" <[EMAIL PROTECTED]> To: Sent: Wednesday, March 23, 2005 11:51 PM Subject: Re: [Tutor] Dictionary blues... My deepest and most sincere apologies - cooking dinner for the family and posting questions do not mix, I keep making mistakes in the code I type. Once again my apologies - here's the code as it is in my source: import sys, os, unicodedata from Tkinter import * class CRED(Frame): def __init__(self): Frame.__init__(self) self.txt=Text(self) self.txt.bind('', self.conv) self.txt.pack() self.pack() self.txt.focus() def conv(self,event): if event.keysym=='t': str='p' self.txt.insert(END,str) return 'break' app=CRED() app.mainloop() This works - i.e. when I press 't' on the keyboard, it gives me 'p'. What I want to do is, instead of coding a conversion for each letter separately using a long "if elif" sequence, to put all the conversion values into the dictionary and then a general function for each keypress that would take the values out of the dictionary. E.g. - say I have dictionary D={'p':'t','t':'z'} Instead of coding the conv function for each letter: if event.keysym=='p': str='t' elif event.keysym=='t': str='z' put all the conversion values into a dictionary and make the function use the key:value pairs from dictionary. I hope I am making sense. Igor - Original Message - From: "Alan Gauld" <[EMAIL PROTECTED]> To: "Igor Riabtchuk" <[EMAIL PROTECTED]>; Sent: Wednesday, March 23, 2005 11:17 PM Subject: Re: [Tutor] Dictionary blues... Igor, I posted the wrong code before. The code is: Is this the actual code you have written? If so it is so far from being working code that it suggests you need to back up a little and work at the basics of Python before trying to tackle Tkinter and GUIs. I'll assume this really is your code and make some comments... from Tkinter import * D={a:"tom", b:"dick", c:"harry"} You need to put the keys in quotes too text.bind('', self.Conv) self is only used to access the members of a class, you don't have any class so you don't need self. You also don't, at this stage, have anything called 'text' so you can't bind anything to it. You need to create a text widget which in turn it parented under a Tk object top = Tk() text = Text(top) text.bind('', Conv) But even here, Conv hasn't been defined yet so you need to move the Conv definition above those lines. def Conv(self,event): You can remove the self fro the parameter list, its only needed if this is a method of a class. if D.has_key(event.keysym): str=D[event.keysym] self.text.insert(END,str) You can remove the 'text.' thats only used if text were part of a class, which in this case it isn't. Also you probably want to indent the insert line as part of the if clause. return 'break' And before anything works you need to 'pack' the text widget and set the event loop running: text.pack() top.mainloop() The error message says wrong syntax... I'm sure it said a lot more than that. Please send the whole error message, the bit that tells us what exactly Python thought was wrong and where. In this case there is so much that is wrong it doesn't matter too much but in future it will be important. The more you help us the more we can help you. If the above doesn't make sense can I suggest you try building a textual version first using the dictionary and raw_input to read the keys from the console. Once you have the basics working putting it into a GUI will be much easier. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ 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] Passing data from html to py
Quoting Vicki Stanfield <[EMAIL PROTECTED]>: > I need something more like this: > > First Name: Vicki > Last Name: Stanfield > etc. Instead of just printing form, try this: for key in form: print '%s: %s' % (key, form[key].value) Basically, a FieldStorage object is organised as a dictionary, where the keys are the names of the HTML form elements, and the values are MiniFieldStorage objects. To get the actual form data, you look at the .value attribute. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] I need some guidance
Hi to everyone first, this is my first posting and I hope that I won't make a mess. I am 100% newbie (and when I mean newbie it is with a big N). I decided to have a go at programming and after reading different articles I decided to have a go at Python (first because it is free, secondly because apparently it is easier than other languages). The reason for me to try to learn programming is that I have been involved with computer (graphic operator) but I have decided to modify my profesionnal path (risk of future redundancy) and want to equip myself better. I have started by reading the excellent "Non-ProgrammersTutorial For Python" by Josh Cogliati. I like it a lot. My first problem is as I don't have any experience in programming I sometimes get a bit lost in the explanation (i.e. I am just learning about Defining Functions. It fascinates me, but it is taking me a long to get around it. My first question is do i need to really understand everything first time I come across or does it get easier if you kind of move along and get back to it later? Second question: As i am not, unfortunately, involved professionaly in the field of programming is there a specific technique to learn other than just read everything I put my hand on? Third question: Does anybody know if it is possible to get involved in this field in a non-lucrative kind of way in order to learn faster and of course to apply this science in a real world. I guess it's enough question for now, sorry to bore you as you probably have seen this question over time. I apologise for my English as it is not my first language and thank in advance anybody that will help me with my queries. Thanks JC ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing data from html to py
Quoting Vicki Stanfield <[EMAIL PROTECTED]>: > > for key in form: > > print '%s: %s' % (key, form[key].value) > Thanks John, > That is exactly what I was looking for. I would like to add a newline > after each line. I tried adding a \n after the second %s, but that > doesn't seem to work. But wait, it works interactively. Any idea why it might > not work in this script. > > for key in form: > print '%s: %s/n/n' % (key, form[key].value) Hi Vicki --- Two things: Firstly, a there is a difference between /n and \n :-) Secondly, remember that all whitespace (including newlines) in HTML is collapsed down to a single space. The newlines will be there, but your web browser is just ignoring them. A quick fix is something like '%s: %s' % (key, form[key].value). -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] I need some guidance
Title: RE: [Tutor] I need some guidance Welcome. And we all start as newbies (eerrr Level 1 programmers armed with a +1 Python and d4 hit points) "My first question is do i need to really understand everything first time I come across or does it get easier if you kind of move along and get back to it later?" Run through a tutorial or two and then try and program something of use to you. I started with a simple program to convert between data formats. "Second question: As i am not, unfortunately, involved professionaly in the field of programming is there a specific technique to learn other than just read everything I put my hand on?" Start writing small programs that you need for your job or future job. Do have a few in mind? "Third question: Does anybody know if it is possible to get involved in this field in a non-lucrative kind of way in order to learn faster and of course to apply this science in a real world." What area of science? Another good tutorial is http://www.freenetpages.co.uk/hp/alan.gauld/ and it's available in other languages as well. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need some guidance
> My first question is do i need to really understand everything first time I > come across or does it get easier if you kind of move along and get back to > it later? My personal experience is that anything makes more sense when you come back to it later, so yes :^) > Third question: Does anybody know if it is possible to get involved in this > field in a non-lucrative kind of way in order to learn faster and of course > to apply this science in a real world. There are programming contests from time to time, on various web sites. You can probably find loads of them on Google. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need some guidance
Quoting John Carmona <[EMAIL PROTECTED]>: > Second question: As i am not, unfortunately, involved professionaly in > the field of programming is there a specific technique to learn other than > just read everything I put my hand on? Reading is fine, but you really need to be writing code to cement your knowledge. I find it very helpful if I have a projcet of some kind to work on if I'm learning something new. Which leads on to --- > Third question: Does anybody know if it is possible to get involved in > this field in a non-lucrative kind of way in order to learn faster and of > course to apply this science in a real world. Well, look around yourself. Is there anything that you do which might benefit from some basic programming? For example, I play ultimate frisbee. So my "learn python" project was to create a CGI system for handling the ultimate leagues here in Wellington (displaying this week's games, recording scores, calculating leaderboards, etc). The code I produced is not a model for anyone on this list to look at, but it did get me into the language :-) -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing data from html to py
> > Hi Vicki --- > > Two things: > > Firstly, a there is a difference between /n and \n :-) > > Secondly, remember that all whitespace (including newlines) in HTML is > collapsed > down to a single space. > > The newlines will be there, but your web browser is just ignoring them. A > quick > fix is something like '%s: %s' % (key, form[key].value). > > -- > John. Yeah, thanks, John. That'll teach me to type instead of cutting and pasting. Thanks too for the lesson. Vicki ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need some guidance
On Thu, 24 Mar 2005 00:30:22 +, John Carmona <[EMAIL PROTECTED]> wrote: > Hi to everyone first, this is my first posting and I hope that I won't make > a mess. > > I am 100% newbie (and when I mean newbie it is with a big N). > > I decided to have a go at programming and after reading different articles I > decided to have a go at Python (first because it is free, secondly because > apparently it is easier than other languages). The reason for me to try to > learn programming is that I have been involved with computer (graphic > operator) but I have decided to modify my profesionnal path (risk of future > redundancy) and want to equip myself better. > > I have started by reading the excellent "Non-ProgrammersTutorial For Python" > by Josh Cogliati. I like it a lot. My first problem is as I don't have any > experience in programming I sometimes get a bit lost in the explanation > (i.e. I am just learning about Defining Functions. It fascinates me, but it > is taking me a long to get around it. > > My first question is do i need to really understand everything first time I > come across or does it get easier if you kind of move along and get back to > it later? No. I find it's good to have an familarity with the basic concepts, and then when you hit a particular problem, try certain approaches you've heard about. BTW I heartily recommend Alan Gauld's tutorial - http://www.freenetpages.co.uk/hp/alan.gauld/ I used that and IDLE to learn. > Second question: As i am not, unfortunately, involved professionaly in the > field of programming is there a specific technique to learn other than just > read everything I put my hand on? Try stuff out. Use IDLE, or any other Python interactive interpreter to try stuff as you go. > Third question: Does anybody know if it is possible to get involved in this > field in a non-lucrative kind of way in order to learn faster and of course > to apply this science in a real world. I would say find a project that appeals to you. The first ever Python code I wrote was a programme to calculate the best crop to plant for Harvest Moon, a very old SNES farming game! Since then I've written a programme that downloads certain email attachments from an IMAP server, parses them and generates a CSV file with the results, and I'm currently working on a small database for my own use. During each of these, I've learnt as I've gone, and as I've faced new problems, I've tried new approaches. And, I've usually been pointed in the right direction by people on this list. It's actually quite funny I was looking over my email programme code, and I could exactly identify precisely the point where I figured out how to use dictionaries instead of lists. > I apologise for my English as it is not my first language and thank in > advance anybody that will help me with my queries. > Your English is a lot better than my anything else. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Passing data from html to py
I am trying to understand how to pass data back and forth from a form to a python script. I mostly have it working now, but I am unsure about how to find out which variables are being passed from the html. I can see them in the form.list, but I need to iterate over them and print a label for each. Currently the data gets printed out like this: [MiniFieldStorage('fname', 'Vicki'), MiniFieldStorage('lname', 'Stanfield'), MiniFieldStorage('addr', '123 Street'), MiniFieldStorage('pwd', 'sdkfsadf'), MiniFieldStorage('prod[]', 'Cases'), MiniFieldStorage('email', 'on'), MiniFieldStorage('buyDays', '10')] I need something more like this: First Name: Vicki Last Name: Stanfield etc. The code I have so far is this: #! /usr/bin/python import cgitb, os, sys cgitb.enable() sys.strerr = sys.stdout import cgi print "Content-Type: text/html\n\n" print print "\n\n" form = cgi.FieldStorage() if ( os.environ['REQUEST_METHOD'] == 'POST' ): if form.list != []: print form.list else: print "No POST data." elif ( os.environ['REQUEST_METHOD'] == 'GET' ): if form.list != []: print form.list else: print "No GET data." print "\n\n" --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing data from html to py
I have one last question on this particular script. I am using the following line to print out the post data: for key in form: print "%s: %s" % (key, form[key].value) It works fine except for when the key is to a list object made by the following select statement: Motherboards Processors Cases Power Supplies Memory Hard Drives Peripherals AttributeError: 'list' object has no attribute 'value' args = ("'list' object has no attribute 'value'",) How does one traverse a list object to get the selected data? Thanks for any help. Vicki ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need some guidance
My two bits... Use the python interpreter a lot! Run through the examples in the tutorial, see the output piece by piece, then make small variations and see the output. For example, when the tutorial passes one variable to a function, change the variable and see the output. Then see if you can get two variables to work like you expect. Second, when you get an output you don't expect, try and figure out why. If you can't, then utilize this great tutor list to help... I unfortunately discovered it later than necessary and ended up on using my imagination to get things to work. Third, your English is much better than what I see everyday at my English dominant high school. I've heard that English is a hard second language, so don't critisize yourself... Jacob ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] xmlrpc server
Hi, I've been exploring xmlrpc implementations, and am somewhat confused as to what I should use. I've spent the most time poking at Twisted, which took me a while to figure out the basics of, and have spent a moment or two exploring py-xmlrpc as well as SimpleXMLRPCServer in the standard library. My observations are that: Twisted fully loaded with xmlrpc, database access using adbapi, and virtual hosts to proxy behind apache runs at almost 20mb of memory. This seems a lot, but Twisted also offers a great deal more such as web-templating with Nevow, if necessary. py-xmlrpc uses a scant 4mb of memory, does only one thing, and does it well, serve xmlrpc requests. It appears significantly faster than Twisted. SimpleXMLRPCServer, as a CGI solution, appears acceptable, given that it be run from FastCGI or mod_python to give it that extra boost. What would you suggest? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing data from html to py
Vicki Stanfield wrote: I have one last question on this particular script. I am using the following line to print out the post data: for key in form: print "%s: %s" % (key, form[key].value) The difficulty is that sometimes you have a single value and sometimes you have a list. If you use form.getlist(key) you will always get a list and you can process it like this: for key in form: datalist = form.getlist(key) # always returns a list value = ', '.join(datalist) # turn the list into a string of comma-separated values print "%s: %s" % (key, value) Kent It works fine except for when the key is to a list object made by the following select statement: Motherboards Processors Cases Power Supplies Memory Hard Drives Peripherals AttributeError: 'list' object has no attribute 'value' args = ("'list' object has no attribute 'value'",) How does one traverse a list object to get the selected data? Thanks for any help. Vicki ___ 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] primes - sieve of odds
Now it would be fine to have an *equally fast* infinite prime number generator. Has anybody any suggestions? [cut] What follows is an attempt based on the previous tutor-evolved sieve that extends the range in which to find the next prime by a factor of 2 over the last known prime. A similar algorithm is on ASPN (I bellieve), under Space-efficient version of sieve of Eratosthenes. D. Eppstein, May 2004 Oh, please...ignore what I suggested and look at Eppstein's code. It's a thing of beauty and just keeps chugging out primes well past what the inefficient version that I suggested could do with the same memory. It's a "tortoise and hare" race as the memory gets chewed up by the esieve approach. The ASPN version of Eppstein's program is an older one than the one at the following site: http://www.ics.uci.edu/~eppstein/PADS/Eratosthenes.py Take a look! /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor