From missive at hotmail.com Tue Mar 1 00:36:40 2005 From: missive at hotmail.com (Lee Harr) Date: Tue Mar 1 00:37:06 2005 Subject: [Tutor] (no subject) Message-ID: <BAY2-F10D59BFC4FBF9FD1C63815B1580@phx.gbl> >I attempting to control xfmedia, >http://spuriousinterrupt.org/projects/xfmedia/ , via it's remote from >python and I can not get a connection. > >s = socket.fromfd('/tmp/xfmedia_remote.1001.0', socket.AF_UNIX, >socket.SOCK_STREAM) > >i get this error > ></xfmedia_remote.1001.0', socket.AF_UNIX, socket.SOCK_STREAM) >Traceback (most recent call last): > File "<stdin>", line 1, in ? > >f = open('/tmp/xfmedia_remote.1001.0') >Traceback (most recent call last): > File "<stdin>", line 1, in ? >IOError: [Errno 6] No such device or address: >'/tmp/xfmedia_remote.1001.0' > >yet ls shows the file exists, xfmedia is working fine. > I have not done this before, but I think you need to create a _new_ socket for your end, and then connect to the other socket. Does that make more sense? _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From python.programming at gmail.com Tue Mar 1 01:35:08 2005 From: python.programming at gmail.com (Kevin) Date: Tue Mar 1 01:35:12 2005 Subject: [Tutor] printing out a box of O's Message-ID: <d082fff8050228163535b5b240@mail.gmail.com> I just started getting in to python and for taking a look at the for loop. I want to print out a box of O's 10o chars long by 10 lines long this is what I came up with. Is there a better way to do this: j = 'O' for i in j*10: print i * 100 Thanks Kevin From cyresse at gmail.com Tue Mar 1 01:45:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 1 01:45:36 2005 Subject: [Tutor] printing out a box of O's In-Reply-To: <d082fff8050228163535b5b240@mail.gmail.com> References: <d082fff8050228163535b5b240@mail.gmail.com> Message-ID: <f2ff2d0502281645feb0d11@mail.gmail.com> for y in range(10): for x in range(10): print "O", print '\n' Or - for y in range(10): print "O"*10 On Mon, 28 Feb 2005 18:35:08 -0600, Kevin <python.programming@gmail.com> wrote: > I just started getting in to python and for taking a look at the for > loop. I want to print out a box > of O's 10o chars long by 10 lines long this is what I came up with. Is > there a better way to do > this: > > j = 'O' > for i in j*10: > print i * 100 > > Thanks > > Kevin > _______________________________________________ > 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. From dyoo at hkn.eecs.berkeley.edu Tue Mar 1 02:33:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 1 02:33:38 2005 Subject: [Tutor] Python and a web image map In-Reply-To: <f2ff2d05022813277188e4d4@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0502281728190.22677-100000@hkn.eecs.berkeley.edu> > Save the above as an HTM and click, it should give you the x,y co-ords > for the browser window excluding scrolbars etc. It is possible to do this with Python, since a server-side HTML ISMAP will send its coordinates off as part of the request. There are some notes here: http://www.algonet.se/~ug/html+pycgi/img.html The coordinates we get back are in terms of the pixels of the image, so translating to a latitidue/longitude system will probably take some more work. Best of wishes! From billk at fastmail.fm Tue Mar 1 04:06:44 2005 From: billk at fastmail.fm (Bill Kranec) Date: Tue Mar 1 04:06:46 2005 Subject: [Tutor] Criticism / Suggestions Message-ID: <4223DC44.6010506@fastmail.fm> Hello, So I think that I've 'completed' my first real Python program, and I would appreciate any constructive criticism you all could offer. The program deals with a question that my Dad asked me awhile ago, which was "If twelve people want to divide into teams of two and play (golf) against each other, can a series of rounds be constructed such that each player is teammates with each other player only once, and play against each other as opponents no more then 3 times" ( that last bit might or might not be 'optimal'. My program: 1. Defines a round as a list, for example [1,2,3,4,5,6,7,8,9,10,11,12], meaning player 1 & player 2 vs. player 3 & player 4, etc. I have generated all such possible rounds ( I think ). 2. Defines a tournament iterator object, which uses two functions, checkTeammates and checkOpponents, to build a tournament satisfying the above criteria. Like I mentioned before, this is my first fairly complex program, and is also my first real use of things like exceptions, objects, and list comprehensions. Basically I would like to know weather or not I used these structures properly, weather or not my syntax is good, and if there are any places with potential for improvement. ( This version is somewhat slow, but is much faster than previous versions that I have written. ) I've tried to have as many comments as possible to help readability. Code aside, my algorithm may or may not be the best. Feel free to suggest improvements. The code is located at http://rafb.net/paste/results/lrd5DG32.html. Thanks for any thoughts! Bill From amonroe at columbus.rr.com Tue Mar 1 04:33:38 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 1 04:34:22 2005 Subject: [Tutor] How to read unicode strings from a binary file and display them as plain ascii? Message-ID: <12255145785.20050228223338@columbus.rr.com> I started writing a program to parse the headers of truetype fonts to examine their family info. But I can't manage to print out the strings without the zero bytes in between each character (they display as a black block labeled 'NUL' in Scite's output pane) I tried: stuff = f.read(nlength) stuff = unicode(stuff, 'utf-8') print type(stuff), 'stuff', stuff.encode() This prints: <type 'unicode'> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] Apparently I'm missing something simple, but I don't know what. Alan From javier at ruere.com.ar Tue Mar 1 05:40:19 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue Mar 1 05:37:46 2005 Subject: [Tutor] Re: Edonkey Automatic Search Program?! In-Reply-To: <BAY22-F3413B8AC3564F145C86CA6C8580@phx.gbl> References: <BAY22-F3413B8AC3564F145C86CA6C8580@phx.gbl> Message-ID: <d00r9g$qoe$1@sea.gmane.org> . , wrote: > Hi, > > I just want to know whether this program can be programmed by python or > not. > > p2p program like edonkey is very very complicated (I think so..) > > but, is searching program for edonkey complicated too? > > Should the search program be connected to edonkey? (I think so..) > > > The Edonkey Automatic Search Program should be like... > > i input some words and the prgram automatically download files > > which are related to words by days, hours. > > > I'm looking forward to see your replys... P2P complicated? Please! Check http://www.freedom-to-tinker.com/tinyp2p.html out. ;) Javier From javier at ruere.com.ar Tue Mar 1 05:51:18 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue Mar 1 05:48:56 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <12255145785.20050228223338@columbus.rr.com> References: <12255145785.20050228223338@columbus.rr.com> Message-ID: <d00ru9$rsv$1@sea.gmane.org> R. Alan Monroe wrote: > I started writing a program to parse the headers of truetype fonts to > examine their family info. But I can't manage to print out the strings > without the zero bytes in between each character (they display as a > black block labeled 'NUL' in Scite's output pane) > > I tried: > stuff = f.read(nlength) > stuff = unicode(stuff, 'utf-8') If there are embeded 0's in the string, it won't be utf8, it could be utf16 or 32. Try: unicode(stuff, 'utf-16') or stuff.decode('utf-16') > print type(stuff), 'stuff', stuff.encode() > This prints: > > <type 'unicode'> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] I don't understand what you tried to accomplish here. > Apparently I'm missing something simple, but I don't know what. Try the other encodings. It probably is utf-16. Javier From alan.gauld at freenet.co.uk Tue Mar 1 08:35:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 1 08:35:09 2005 Subject: [Tutor] Python and a web image map References: <E338ADD616B66043824B9ABF5CA6EF2332C541@lanexc107p.fnmoc.navy.mil> Message-ID: <01a201c51e31$2f0366b0$a6388651@xp> > I have been doing Python for a bit now but I am trying to make a clickable > map of the world on a web page that gives me the latitude and longitude of a > location selected. I have done little with HTML beyond forms and have done > no Java script. Is this a problem Python can solve or is this a HTML / Java > script issue. Personally I'd go with JavaScript on this one. It has a built-in knowledge of the web browser interface and document which makes extracting the mouse location etc much easier. Its possible in Python but IMHO is easier in JavaScript on the client. Alan G. From alan.gauld at freenet.co.uk Tue Mar 1 08:40:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 1 08:40:40 2005 Subject: [Tutor] printing out a box of O's References: <d082fff8050228163535b5b240@mail.gmail.com> Message-ID: <01b101c51e31$f57d7d80$a6388651@xp> ----- Original Message ----- From: "Kevin" <python.programming@gmail.com> To: <tutor@python.org> Sent: Tuesday, March 01, 2005 12:35 AM Subject: [Tutor] printing out a box of O's > there a better way to do > this: > > j = 'O' > for i in j*10: > print i * 100 Its not bad, but the for loop could be 'simplified' to: for i in range(10): print j*100 its not any shorter and probably doesn't run much faster but its a lot more readable because its the conventional Python idiom for coding fixed length loops. Alan G. From kabads at gmail.com Tue Mar 1 10:22:06 2005 From: kabads at gmail.com (Adam Cripps) Date: Tue Mar 1 10:22:10 2005 Subject: [Tutor] Saving Entry fields in Tkinter Message-ID: <c7ff3855050301012223c241eb@mail.gmail.com> I'm writing an application which has rows of Entry fields (created in a loop - see previous thread; and thanks guys!). All the content of the Entry fields are accessed through self.contentlist[i].get() Now I'm trying to save the content of those fields in a friendly format. I've used pickle in the past, but experienced problems with pickling Tkinter widgets. I'm saving using this method :- for i in self.contentlist: saving = i.get() + "\n" f.write(saving) f.close() which creates a text file with each entry field separated with a "\n". What would be a good way to open this file and re-populate the entry fields with the content? I'm not sure how to parse the text according to the \n separator. Am I going down the right path here? TIA Adam -- http://www.monkeez.org PGP key: 0x7111B833 From amonroe at columbus.rr.com Tue Mar 1 12:39:22 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 1 12:40:06 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <d00ru9$rsv$1@sea.gmane.org> References: <12255145785.20050228223338@columbus.rr.com> <d00ru9$rsv$1@sea.gmane.org> Message-ID: <8584290042.20050301063922@columbus.rr.com> > R. Alan Monroe wrote: >> I started writing a program to parse the headers of truetype fonts to >> examine their family info. But I can't manage to print out the strings >> without the zero bytes in between each character (they display as a >> black block labeled 'NUL' in Scite's output pane) >> >> I tried: >> stuff = f.read(nlength) >> stuff = unicode(stuff, 'utf-8') > If there are embeded 0's in the string, it won't be utf8, it could be > utf16 or 32. > Try: > unicode(stuff, 'utf-16') > or > stuff.decode('utf-16') >> print type(stuff), 'stuff', stuff.encode() >> This prints: >> >> <type 'unicode'> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] > I don't understand what you tried to accomplish here. That's evidence of what I failed to accomplish. My expected results was to print the word "Copyright" and whatever other strings are present in the font, with no intervening NUL characters. > Try the other encodings. It probably is utf-16. Aha, after some trial and error I see that I'm running into an endian problem. It's "\x00C" in the file, which needs to be swapped to "C\x00". I cheated temporarily by just adding 1 to the file pointer :^) Alan -------------- next part -------------- #~ 11/30/1998 03:45 PM 38,308 FUTURAB.TTF #~ 11/30/1998 03:45 PM 38,772 FUTURABI.TTF #~ 12/10/1998 06:24 PM 32,968 FUTURAK.TTF #~ 12/30/1998 05:15 AM 36,992 FUTURAL.TTF #~ 12/15/1998 11:39 PM 37,712 FUTURALI.TTF #~ 01/05/1999 03:59 AM 38,860 FUTURAXK.TTF #~ The OpenType font with the Offset Table. If the font file contains only one font, the Offset Table will begin at byte 0 of the file. If the font file is a TrueType collection, the beginning point of the Offset Table for each font is indicated in the TTCHeader. #~ Offset Table Type Name Description #~ Fixed sfnt version 0x00010000 for version 1.0. #~ USHORT numTables Number of tables. #~ USHORT searchRange (Maximum power of 2 <= numTables) x 16. #~ USHORT entrySelector Log2(maximum power of 2 <= numTables). #~ USHORT rangeShift NumTables x 16-searchRange. import struct def grabushort(): global f data = f.read(2) return int(struct.unpack('>H',data)[0]) def grabulong(): global f data = f.read(4) return int(struct.unpack('>L',data)[0]) f=open('c:/windows/fonts/futurak.ttf', 'rb') version=f.read(4) numtables = grabushort() print numtables f.read(6) #skip searchrange, entryselector, rangeshift #~ Table Directory Type Name Description #~ ULONG tag 4 -byte identifier. #~ ULONG checkSum CheckSum for this table. #~ ULONG offset Offset from beginning of TrueType font file. #~ ULONG length Length of this table. #for x in range(numtables): for x in range(numtables): tag=f.read(4) checksum =grabulong() offset = grabulong() tlength = grabulong() print 'tag', tag, 'offset', offset, 'tlength', tlength if tag=='name': nameoffset = offset namelength = tlength print 'nameoffset', nameoffset, 'namelength', namelength #The Naming Table is organized as follows: #~ Type Name Description #~ USHORT format Format selector (=0). #~ USHORT count Number of name records. #~ USHORT stringOffset Offset to start of string storage (from start of table). #~ NameRecord nameRecord[count] The name records where count is the number of records. #~ (Variable) Storage for the actual string data. #~ Each NameRecord looks like this: #~ Type Name Description #~ USHORT platformID Platform ID. #~ USHORT encodingID Platform-specific encoding ID. #~ USHORT languageID Language ID. #~ USHORT nameID Name ID. #~ USHORT length String length (in bytes). #~ USHORT offset String offset from start of storage area (in bytes). print f.seek(nameoffset) format = grabushort() count = grabushort() stringoffset = grabushort() print 'format', format, 'count', count, 'stringoffset', stringoffset for x in range(count): platformid = grabushort() encodingid = grabushort() languageid = grabushort() nameid = grabushort() nlength = grabushort() noffset = grabushort() print 'platformid', platformid, 'encodingid', encodingid, 'languageid', languageid, 'nameid', nameid, 'nlength', nlength, 'noffset', noffset if platformid==3:# microsoft bookmark = f.tell() print 'bookmark', bookmark f.seek(nameoffset+stringoffset+noffset+1) stuff = f.read(nlength) #stuff = unicode(stuff, 'utf-16') stuff = stuff.decode( 'utf-16') print type(stuff), 'stuff', stuff f.seek(bookmark) f.close() From kent37 at tds.net Tue Mar 1 12:50:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 1 12:50:06 2005 Subject: [Tutor] How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <12255145785.20050228223338@columbus.rr.com> References: <12255145785.20050228223338@columbus.rr.com> Message-ID: <422456E9.5030707@tds.net> R. Alan Monroe wrote: > I started writing a program to parse the headers of truetype fonts to > examine their family info. But I can't manage to print out the strings > without the zero bytes in between each character (they display as a > black block labeled 'NUL' in Scite's output pane) > > I tried: > stuff = f.read(nlength) > stuff = unicode(stuff, 'utf-8') I think you need 'utf-16be', not 'utf-8'. See this page if you don't know the difference: http://www.joelonsoftware.com/articles/Unicode.html Kent > print type(stuff), 'stuff', stuff.encode() > > This prints: > > <type 'unicode'> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] > > Apparently I'm missing something simple, but I don't know what. > > Alan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ewald.ertl at hartter.com Tue Mar 1 12:52:57 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 1 12:53:02 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: <c7ff3855050301012223c241eb@mail.gmail.com> References: <c7ff3855050301012223c241eb@mail.gmail.com> Message-ID: <20050301125257.00004683@sunray2.hartter.com> Hi! Perhaps this could help you: fileContent=open( "my/file/to/read", "r").readlines() for line in fileContent: print line.strip() # remove leading and trailing whitspace's incl. \n In the loop you could perhaps populate the entry-widgets. HTH Ewald on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps <kabads@gmail.com> wrote : --------------------------------------------------------------------------------------------- Adam Cripps > I'm writing an application which has rows of Entry fields (created in Adam Cripps > a loop - see previous thread; and thanks guys!). All the content of Adam Cripps > the Entry fields are accessed through self.contentlist[i].get() Adam Cripps > Adam Cripps > Now I'm trying to save the content of those fields in a friendly Adam Cripps > format. I've used pickle in the past, but experienced problems with Adam Cripps > pickling Tkinter widgets. Adam Cripps > Adam Cripps > I'm saving using this method :- Adam Cripps > Adam Cripps > for i in self.contentlist: Adam Cripps > saving = i.get() + "\n" Adam Cripps > f.write(saving) Adam Cripps > f.close() Adam Cripps > Adam Cripps > which creates a text file with each entry field separated with a "\n". Adam Cripps > Adam Cripps > What would be a good way to open this file and re-populate the entry Adam Cripps > fields with the content? I'm not sure how to parse the text according Adam Cripps > to the \n separator. Adam Cripps > Adam Cripps > Am I going down the right path here? Adam Cripps > Adam Cripps > TIA Adam Cripps > Adam ------------------- end ---------------------- -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl@trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl@hartter.com From amonroe at columbus.rr.com Tue Mar 1 12:59:04 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 1 12:59:46 2005 Subject: [Tutor] How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <422456E9.5030707@tds.net> References: <12255145785.20050228223338@columbus.rr.com> <422456E9.5030707@tds.net> Message-ID: <17885472022.20050301065904@columbus.rr.com> > R. Alan Monroe wrote: >> I started writing a program to parse the headers of truetype fonts to >> examine their family info. But I can't manage to print out the strings >> without the zero bytes in between each character (they display as a >> black block labeled 'NUL' in Scite's output pane) >> >> I tried: >> stuff = f.read(nlength) >> stuff = unicode(stuff, 'utf-8') > I think you need 'utf-16be', not 'utf-8'. See this page if you don't know the difference: Outstanding! Batteries included, indeed. Alan From kent37 at tds.net Tue Mar 1 14:46:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 1 14:46:33 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <4223DC44.6010506@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> Message-ID: <42247232.1080409@tds.net> Bill Kranec wrote: > Hello, > > So I think that I've 'completed' my first real Python program, and I > would appreciate any constructive criticism you all could offer. The > program deals with a question that my Dad asked me awhile ago, which was > "If twelve people want to divide into teams of two and play (golf) > against each other, can a series of rounds be constructed such that each > player is teammates with each other player only once, do you mean, 'each player is teammates with each other player exactly once', or, 'each player is teammates with each other player at most once'? Is there a certain number of rounds that must be played? Comments in no particular order - Why do you have the initialization code in a comment? Wouldn't it be helpful to put that in a function or maybe Tournament.__init__()? - I have a hard time figuring out how this is supposed to work. Maybe some comments about the algorithm you are using would help? I have no idea what self.key is doing. - What is the argument to Tournament.__init__() for? - checkTeammates() and checkOpponents() should probably be part of Tournament unless they are useful elsewhere. - You might want to use sets to represent your teams and lists of teams. Sets have a built-in intersect method that should be faster than your hand coded one. In Python 2.4 you could create pairings as pairings = [set(number1, number2) for number1 in range(1,13) for number2 in range(1,13) if number1 < number2] or you could eliminate the conditional by tweaking the ranges: pairings = [(number1, number2) for number1 in range(1,12) for number2 in range(number1+1,13)] - This code repeats twice, maybe it should be in a method with a name that explains what it does: self.rounds = [ roundlist[ entry ] for entry in args ] self.flattened = [ entry for list in self.rounds for entry in list ] - The above code depends on roundlist which is not even defined anywhere in the module (just shown in the comment). This suggests again that the init code from the comment should be part of Tournament, and roundlist should be an attribute of Tournament. For a class to depend on some external variable is bad design and will break if the client code is in a different module from the class code (roundlist will be in a different namespace than Tournament). - Tournament.next() doesn't return a value, it prints it directly. It should return self.key or str( self.key ) - Your loop for key in tment: key relies on the interactive shell to print out key, it won't print anything if run from a program. for key in tment: print key would be better. OK, enough for now, I hope this is helpful and doesn't come across as too critical :-) Kent From MLists at romulo.de Tue Mar 1 15:15:08 2005 From: MLists at romulo.de (Rainer Mansfeld) Date: Tue Mar 1 15:15:14 2005 Subject: [Tutor] printing out a box of O's In-Reply-To: <d082fff8050228163535b5b240@mail.gmail.com> References: <d082fff8050228163535b5b240@mail.gmail.com> Message-ID: <422478EC.4090403@romulo.de> Kevin schrieb: > I just started getting in to python and for taking a look at the for > loop. I want to print out a box > of O's 10o chars long by 10 lines long this is what I came up with. Is > there a better way to do > this: > > j = 'O' > for i in j*10: > print i * 100 > > Thanks > > Kevin Hi Kevin, I don't know, if this is better, but at least it's shorter: >>> print ('O' * 100 + '\n') * 10 Rainer From mark.kels at gmail.com Tue Mar 1 15:51:54 2005 From: mark.kels at gmail.com (Mark Kels) Date: Tue Mar 1 15:51:58 2005 Subject: [Tutor] How to use threads ? Message-ID: <c225925305030106517884079b@mail.gmail.com> Can anyone give me a very simple example on thread programming ? I looked at some tutorials but they don't really make sense... Thanks in advance -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From AKolinski at nriindustries.com Tue Mar 1 16:04:07 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Tue Mar 1 16:03:15 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42247232.1080409@tds.net> Message-ID: <OF33F36BB4.30095073-ON85256FB7.00519C21-85256FB7.0052BF4E@NRIINDUSTRIES.COM> On my way to write my own scripts from scratch I'm still assembling bits and pieces from everywhere in the Python universe to create little programs that help me automate updating my website: - to invoke a players' ranking program, - to convert text files to php formats, - ... I would like to go even further and employ Tkinter to: - open and run a C and/or Python code (including arguments where necessary), - name and safe generated html/php files. The only thing I found is the following line of code: filemenu.add_command(label="Open...", command=askopenfile) - which obviously does not do the job. Therefore, what would be the right command within Tkinter to do what I need? _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski office 416.652.4256 cell. 416.838.7667 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050301/cd746564/attachment.html From AKolinski at nriindustries.com Tue Mar 1 16:15:18 2005 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Tue Mar 1 16:14:20 2005 Subject: [Tutor] to employ Tkinter Message-ID: <OF8A59A636.481C3A28-ON85256FB7.00538840-85256FB7.0053C55E@NRIINDUSTRIES.COM> My apologies for leaving Subject entry unchanged :-). _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski ----- Forwarded by Andrzej Kolinski/NRI on 01/03/2005 10:12 AM ----- Andrzej Kolinski <AKolinski@nriindustries.com> Sent by: tutor-bounces@python.org 01/03/2005 10:04 AM To Python Tutor <tutor@python.org>, tutor-bounces@python.org cc Subject Re: [Tutor] Criticism / Suggestions On my way to write my own scripts from scratch I'm still assembling bits and pieces from everywhere in the Python universe to create little programs that help me automate updating my website: - to invoke a players' ranking program, - to convert text files to php formats, - ... I would like to go even further and employ Tkinter to: - open and run a C and/or Python code (including arguments where necessary), - name and safe generated html/php files. The only thing I found is the following line of code: filemenu.add_command(label="Open...", command=askopenfile) - which obviously does not do the job. Therefore, what would be the right command within Tkinter to do what I need? _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050301/bd4df00f/attachment.html From kabads at gmail.com Tue Mar 1 16:31:10 2005 From: kabads at gmail.com (Adam Cripps) Date: Tue Mar 1 16:33:06 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: <c7ff3855050301073018ed97dc@mail.gmail.com> References: <c7ff3855050301012223c241eb@mail.gmail.com> <20050301125257.00004683@sunray2.hartter.com> <c7ff3855050301073018ed97dc@mail.gmail.com> Message-ID: <c7ff38550503010731425e7ea7@mail.gmail.com> On Tue, 1 Mar 2005 15:30:02 +0000, Adam Cripps <kabads@gmail.com> wrote: > On Tue, 1 Mar 2005 12:52:57 +0100, Ewald Ertl <ewald.ertl@hartter.com> wrote: > > Hi! > > > > Perhaps this could help you: > > > > fileContent=open( "my/file/to/read", "r").readlines() > > > > for line in fileContent: > > print line.strip() # remove leading and trailing whitspace's incl. \n > > > > In the loop you could perhaps populate the entry-widgets. > > > > HTH > > > > Ewald > > > > on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps <kabads@gmail.com> wrote : > <snip> > Thanks Ewald - this is what I have so far, with a far from perfect result: File=open( FileName, "r") readlines = File.readlines() intcount = 0 newcontent =[] for line in readlines: print line.strip() # remove leading and trailing whitspace's incl. \n self.contentlist[intcount].set(repr(line.strip)) intcount = intcount + 1 But all the entry fields are filled with these and not the text: <built-in method strip of str object at 0x009983B0> I'm not sure what else to do here... any ideas? Thanks Adam -- http://www.monkeez.org PGP key: 0x7111B833 From kabads at gmail.com Tue Mar 1 16:45:50 2005 From: kabads at gmail.com (Adam Cripps) Date: Tue Mar 1 16:47:52 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: <c7ff38550503010731425e7ea7@mail.gmail.com> References: <c7ff3855050301012223c241eb@mail.gmail.com> <20050301125257.00004683@sunray2.hartter.com> <c7ff3855050301073018ed97dc@mail.gmail.com> <c7ff38550503010731425e7ea7@mail.gmail.com> Message-ID: <c7ff3855050301074518afa972@mail.gmail.com> On Tue, 1 Mar 2005 15:31:10 +0000, Adam Cripps <kabads@gmail.com> wrote: > On Tue, 1 Mar 2005 15:30:02 +0000, Adam Cripps <kabads@gmail.com> wrote: > > On Tue, 1 Mar 2005 12:52:57 +0100, Ewald Ertl <ewald.ertl@hartter.com> wrote: > > > Hi! > > > > > > Perhaps this could help you: > > > > > > fileContent=open( "my/file/to/read", "r").readlines() > > > > > > for line in fileContent: > > > print line.strip() # remove leading and trailing whitspace's incl. \n > > > > > > In the loop you could perhaps populate the entry-widgets. > > > > > > HTH > > > > > > Ewald > > > > > > on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps <kabads@gmail.com> wrote : > > <snip> > > > Thanks Ewald - this is what I have so far, with a far from perfect result: > File=open( FileName, "r") > readlines = File.readlines() > intcount = 0 > newcontent =[] > for line in readlines: > print line.strip() # remove leading and trailing whitspace's incl. \n > self.contentlist[intcount].set(repr(line.strip)) > intcount = intcount + 1 > > But all the entry fields are filled with these and not the text: > > <built-in method strip of str object at 0x009983B0> > > I'm not sure what else to do here... > > any ideas? I think I got the jist of it - readlines is a list, which holds all the text, and so I also iterate over readlines and push that content in thus: self.contentlist[intcount].set(readlines[intcount]) Adam -- http://www.monkeez.org PGP key: 0x7111B833 From ewald.ertl at hartter.com Tue Mar 1 17:40:26 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 1 17:40:30 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: <c7ff3855050301074518afa972@mail.gmail.com> References: <c7ff3855050301012223c241eb@mail.gmail.com> <20050301125257.00004683@sunray2.hartter.com> <c7ff3855050301073018ed97dc@mail.gmail.com> <c7ff38550503010731425e7ea7@mail.gmail.com> <c7ff3855050301074518afa972@mail.gmail.com> Message-ID: <20050301174026.0000134d@sunray2.hartter.com> Hi on Tue, 1 Mar 2005 15:31:10 +0000 Adam Cripps <kabads@gmail.com> wrote : --------------------------------------------------------------------------------------------- Adam Cripps > > Adam Cripps > Thanks Ewald - this is what I have so far, with a far from perfect result: Adam Cripps > File=open( FileName, "r") Adam Cripps > readlines = File.readlines() Adam Cripps > intcount = 0 Adam Cripps > newcontent =[] Adam Cripps > for line in readlines: Adam Cripps > print line.strip() # remove leading and trailing whitspace's incl. \n Adam Cripps > self.contentlist[intcount].set(repr(line.strip)) I think, here's the call missing self.contentlist[intcount].set(repr(line.strip())) ^^ That should be the reason, why you get the reference to the method of the string and not the content. If your printing line.strip without the paranthesis you get the reference of the method. This reference can be assigned to a variable to call it later. Adam Cripps > intcount = intcount + 1 Adam Cripps > Adam Cripps > But all the entry fields are filled with these and not the text: Adam Cripps > Adam Cripps > <built-in method strip of str object at 0x009983B0> Adam Cripps > Adam Cripps > I'm not sure what else to do here... Adam Cripps > Adam Cripps > any ideas? Adam Cripps > Adam Cripps > Thanks Adam Cripps > Adam Adam Cripps > -- Adam Cripps > http://www.monkeez.org Adam Cripps > PGP key: 0x7111B833 Adam Cripps > _______________________________________________ Adam Cripps > Tutor maillist - Tutor@python.org Adam Cripps > http://mail.python.org/mailman/listinfo/tutor Adam Cripps > ------------------- end ---------------------- From jon.papageorgiou at wachovia.com Tue Mar 1 19:29:07 2005 From: jon.papageorgiou at wachovia.com (jon.papageorgiou@wachovia.com) Date: Tue Mar 1 19:25:10 2005 Subject: [Tutor] Check if user exist in domain Message-ID: <OF178EAFCA.9B263892-ON85256FB6.0064B006-85256FB7.0064C468@ftu.firstunion.com> I need to check if a user is in a domain from a computer that is not in a domain. Currently, we are running an NT domain, but will be moving to ActiveDirectory2003 in the next few months. I thought if I could get user information for the user I could verify that the user account existed: #CODE STARTS HERE ###################################################### import win32net import win32netcon domain = "domain" login = "userid" try: #get the server for the domain -- it has to be a primary dc server = str(win32net.NetGetDCName("",domain)) print server #info returns a dictionary of information info = win32net.NetUserGetInfo(server, login, 1) print info#['full_name'] except win32net.error: print "Error: " + login + " not found in " + domain + "." #CODE ENDS HERE ###################################################### The problem is that the following code only works when one is logged in locally with a UserID and password that is the SAME as a UserID and password on the Domain. Example: Domain : Berlin Stand-alone <<- Different User : Frank Frank <<- Same Password: frank'spassword frank'spassword <<- Same So I then attempted to authenticate with alternate credentials. The following code did not work.It blew up on line 20. #CODE STARTS HERE ###################################################### import sys import win32api import win32net import win32netcon import win32security import win32con domain = "berlin" login = "hans" userwithrights = "frank" userwithrightspassword = "frank'spassword" #code blows up on next line hUser = win32security.LogonUser( userwithrights, domain, userwithrightspassword, win32con.LOGON32_LOGON_INTERACTIVE, win32con.LOGON32_PROVIDER_DEFAULT ) win32security.ImpersonateLoggedOnUser(hUser) print win32api.GetUserName() # Should display "frank" #code to be run with alternate credentials try: #get the server for the domain -- it has to be a primary dc server = str(win32net.NetGetDCName("",domain)) print server #info returns a dictionary of information info = win32net.NetUserGetInfo(server, login, 1) print info#['full_name'] except win32net.error: print "Error: " + login + " not found in " + domain + "." win32security.RevertToSelf() hUser.Close() #CODE ENDS HERE ###################################################### The output I receive is as follows: Traceback (most recent call last): File "C:\Documents and Settings\Administrator\Desktop\python-components\getuser2.py", line 20, in ? win32con.LOGON32_PROVIDER_DEFAULT pywintypes.error: (1326, 'LogonUser', 'Logon failure: unknown user name or bad password.') The account being checked and the account that I am impersonating are both domain admins and the password I am using is correct. Can anybody point me in the right direction as to what I am missing? Jon Papageorgiou From klappnase at freenet.de Tue Mar 1 20:52:44 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue Mar 1 20:49:47 2005 Subject: [Tutor] Saving Entry fields in Tkinter In-Reply-To: <20050301125257.00004683@sunray2.hartter.com> References: <c7ff3855050301012223c241eb@mail.gmail.com> <20050301125257.00004683@sunray2.hartter.com> Message-ID: <20050301205244.2a9648a3.klappnase@freenet.de> On Tue, 1 Mar 2005 12:52:57 +0100 Ewald Ertl <ewald.ertl@hartter.com> wrote: > Hi! > > Perhaps this could help you: > > fileContent=open( "my/file/to/read", "r").readlines() > > for line in fileContent: > print line.strip() # remove leading and trailing whitspace's incl. \n > > > In the loop you could perhaps populate the entry-widgets. > > HTH > > Ewald Or use the fileinput module: var_list = [] for line in fileinput.input(filename): var = Tkinter.StringVar() var.set(line) var_list.append(var) Best regards Michael > > on Tue, 1 Mar 2005 09:22:06 +0000 Adam Cripps <kabads@gmail.com> wrote : > --------------------------------------------------------------------------------------------- > > Adam Cripps > I'm writing an application which has rows of Entry fields (created in > Adam Cripps > a loop - see previous thread; and thanks guys!). All the content of > Adam Cripps > the Entry fields are accessed through self.contentlist[i].get() > Adam Cripps > > Adam Cripps > Now I'm trying to save the content of those fields in a friendly > Adam Cripps > format. I've used pickle in the past, but experienced problems with > Adam Cripps > pickling Tkinter widgets. > Adam Cripps > > Adam Cripps > I'm saving using this method :- > Adam Cripps > > Adam Cripps > for i in self.contentlist: > Adam Cripps > saving = i.get() + "\n" > Adam Cripps > f.write(saving) > Adam Cripps > f.close() > Adam Cripps > > Adam Cripps > which creates a text file with each entry field separated with a "\n". > Adam Cripps > > Adam Cripps > What would be a good way to open this file and re-populate the entry > Adam Cripps > fields with the content? I'm not sure how to parse the text according > Adam Cripps > to the \n separator. > Adam Cripps > > Adam Cripps > Am I going down the right path here? > Adam Cripps > > Adam Cripps > TIA > Adam Cripps > Adam > > > ------------------- end ---------------------- > > > -- > Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 > trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 > Wiener Stra?e 41 mailto:ewald.ertl@trinomic.com > A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl@hartter.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jfouhy at paradise.net.nz Tue Mar 1 21:03:14 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Tue Mar 1 21:03:55 2005 Subject: [Tutor] to employ Tkinter In-Reply-To: <OF8A59A636.481C3A28-ON85256FB7.00538840-85256FB7.0053C55E@NRIINDUSTRIES.COM> References: <OF8A59A636.481C3A28-ON85256FB7.00538840-85256FB7.0053C55E@NRIINDUSTRIES.COM> Message-ID: <4224CA82.5030601@paradise.net.nz> Andrzej Kolinski wrote: > I would like to go even further and employ Tkinter to: > - open and run a C and/or Python code (including arguments where > necessary), > - name and save generated html/php files. > > The only thing I found is the following line of code: > filemenu.add_command(label="Open...", command=askopenfile) > - which obviously does not do the job. Tkinter is a GUI framework ... Basically, with Tkinter, you attach the code you want to run to GUI events. eg: from Tkinter import * import tkMessageBox import tkFileDialog import os # This will hold the entry widgets, for later reference. entries = {} tk = Tk() Label(tk, text='Program:').grid(row=0, column=0) entries['program'] = Entry(tk) entries['program'].grid(row=0, column=1) Label(tk, text='Arg 1:').grid(row=1, column=0) entries['arg1'] = Entry(tk) entries['arg1'].grid(row=1, column=1) Label(tk, text='Arg 2:').grid(row=2, column=0) entries['arg2'] = Entry(tk) entries['arg2'].grid(row=2, column=1) Label(tk, text='Arg 3:').grid(row=3, column=0) entries['arg3'] = Entry(tk) entries['arg3'].grid(row=3, column=1) # Build a 'Browse' button for the program field. def browseProg(self): prog = tkFileDialog.askopenfilename() if prog: entries['program'].delete(0, END) entries['program'].insert(END, prog) Button(tk, text='Browse', command=browseProg).grid(row=0, column=2) # Callback to run the program specified. def runProgram(): prog = entries['program'].get() arg1 = entries['arg1'].get() arg2 = entries['arg2'].get() arg3 = entries['arg3'].get() if not os.path.exists(prog): tkMessageBox.showerror('Error', '%s: File not found!' % prog) return args = filter(None, [arg1, arg2, arg3]) os.system(' '.join([prog] + args)) Button(tk, text='Run', command=runProgram).grid() tk.mainloop() --------------------------------------------------------- It should go without saying that there are security concerns when you are allowing users to run arbitrary programs! -- John. From shitizb at yahoo.com Tue Mar 1 21:25:56 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Mar 1 21:26:01 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c225925305030106517884079b@mail.gmail.com> Message-ID: <20050301202557.2424.qmail@web53803.mail.yahoo.com> --- Mark Kels <mark.kels@gmail.com> wrote: > Can anyone give me a very simple example on thread > programming ? > I looked at some tutorials but they don't really > make sense... > > > Thanks in advance > -- > 1. The day Microsoft makes something that doesn't > suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about > it's friends. > 3. Documentation is like sex: when it is good, it is > very, very good. > And when it is bad, it is better than nothing. - > Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Tue Mar 1 22:15:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 1 22:15:47 2005 Subject: [Tutor] Criticism / Suggestions References: <OF33F36BB4.30095073-ON85256FB7.00519C21-85256FB7.0052BF4E@NRIINDUSTRIES.COM> Message-ID: <004301c51ea3$ca474ca0$07b78851@xp> > programs that help me automate updating my website: > - to invoke a players' ranking program, > - to convert text files to php formats, > - ... > > I would like to go even further and employ Tkinter to: If you want to put Tkinter on your web site then you probably will be dissapointed. If you want to use a Tkinter GUI to create HTML/PHP content then thats OK. > - open and run a C and/or Python code (including arguments where > necessary), > - name and safe generated html/php files. > > The only thing I found is the following line of code: > filemenu.add_command(label="Open...", command=askopenfile) If thats all you found you were probably looking in the wrong place. There is a Tkinter section on the Python website with links to Tkinter tutorials. Or you can try my ultra basic level intro to GUI programming with Tkinter. I think you need a Frame containing an Entry widget for the command(or a drop down list or menu) and another Entry for the filename, which could be populated via the standard dialogs. Finally you need a button to execute the command and that will call the commands module or os.popen or somesuch mechanism to do the work. Have a look at the Tkinter tuitorials. If you don;t understand them try doing a command line version first, making sure to separate the function that does the work from the code that gets user input and displays output. See how you get on... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From nick at javacat.f2s.com Tue Mar 1 23:08:00 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:06:42 2005 Subject: [Tutor] reading from stdin Message-ID: <1109714880.10412.5.camel@fuzzbox.local> Hi folks, I've been pondering how to get python to read from a pipe outside of itself, sort of. For example I tried a simple python prog to do a grep, eg # ps -e | myprog.py cron would give this output 3778 ? 00:00:00 crond same as # ps -e | grep cron The way I did this was to use sys.stdin.readlines() to get the output from the pipe. Here is the program: [code] import sys, glob args = sys.stdin.readlines() # found on the net pat = sys.argv[1] for i in args: if (i.find(pat) != -1): print i, [/code] My question is am I getting the output from the pipe in the correct way ? The way Im doing it works (so far) but should I be doing it another way ? Many thanks Nick . From shaleh at speakeasy.net Tue Mar 1 23:14:39 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 1 23:15:54 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <4224E94F.7070403@speakeasy.net> Nick Lunt wrote: > The way I did this was to use sys.stdin.readlines() to get the output > from the pipe. > > Here is the program: > > [code] > import sys, glob > args = sys.stdin.readlines() # found on the net > pat = sys.argv[1] > for i in args: > if (i.find(pat) != -1): > print i, > [/code] > > My question is am I getting the output from the pipe in the correct > way ? The way Im doing it works (so far) but should I be doing it > another way ? > unless you want the output for some other reason, a more idiomatic way is: for line in sys.stdin.readlines(): # handle the line I tend to use xreadlines() which does not read the entire input at once. For stdin this make sense, you have no idea how much data will be piped in. From maxnoel_fr at yahoo.fr Tue Mar 1 23:20:14 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 1 23:20:18 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> On Mar 1, 2005, at 22:08, Nick Lunt wrote: > The way I did this was to use sys.stdin.readlines() to get the output > from the pipe. > > Here is the program: > > [code] > import sys, glob > args = sys.stdin.readlines() # found on the net > pat = sys.argv[1] > for i in args: > if (i.find(pat) != -1): > print i, > [/code] > > My question is am I getting the output from the pipe in the correct > way ? The way Im doing it works (so far) but should I be doing it > another way ? I don't think you are. You're using readlines(), which means your program won't execute until ps terminates. UNIX philosophy is to have programs start acting as soon as possible -- in that case, as soon as the first line is available. You should be reading sys.stdin as an iterator (same thing you'd do for a file): import sys for line in sys.stdin: # do stuff with that line of input -- 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?" From nick at javacat.f2s.com Tue Mar 1 23:23:12 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:21:55 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224E94F.7070403@speakeasy.net> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> Message-ID: <1109715792.10412.11.camel@fuzzbox.local> On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > unless you want the output for some other reason, a more idiomatic way > is: > > for line in sys.stdin.readlines(): > # handle the line > > I tend to use xreadlines() which does not read the entire input at once. > For stdin this make sense, you have no idea how much data will be > piped in. Thanks Sean, I agree with you on both accounts there. Cheers Nick . From srini_iyyer_bio at yahoo.com Tue Mar 1 23:21:58 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Tue Mar 1 23:22:01 2005 Subject: [Tutor] Tab delim file In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <20050301222158.42380.qmail@web53503.mail.yahoo.com> Hello: I have a nasty file where I have 165 column and 140K lines. For every 12 columns, a new dataset is written. 0-12 - File A's data is there 13-24 - File B's data is there. My task is to write data in each 12 columns to a file. I have a rough idea, but when I try I am unable to proceed further. f1 = open('my_file.txt','r') aml = f1.read().split('\n') fLine = aml[0] k = len(fLine)/12 # k = 162/12 #So I want to jump k blocks and get the text. for line in aml: cols = line.split('\t') while i > 13: ...... I am lost from here... Every 4 line(row) contains the file name on which I have to write the file. can any one plese help, i am really stuck in a problem. thanks srini __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jfouhy at paradise.net.nz Tue Mar 1 23:22:54 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 1 23:22:59 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224E94F.7070403@speakeasy.net> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> Message-ID: <1109715774.4224eb3e7dc38@www.paradise.net.nz> Quoting Sean Perry <shaleh@speakeasy.net>: > for line in sys.stdin.readlines(): > # handle the line > > I tend to use xreadlines() which does not read the entire input at once. xreadlines() these days just does 'return self', I believe. File objects are their own iterators; you can just do: for line in sys.stdin: # do stuff -- John. From nick at javacat.f2s.com Tue Mar 1 23:26:29 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:25:10 2005 Subject: [Tutor] reading from stdin In-Reply-To: <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> Message-ID: <1109715989.10412.14.camel@fuzzbox.local> On Tue, 2005-03-01 at 22:20 +0000, Max Noel wrote: > I don't think you are. You're using readlines(), which means your > program won't execute until ps terminates. > UNIX philosophy is to have programs start acting as soon as possible > -- in that case, as soon as the first line is available. You should be > reading sys.stdin as an iterator (same thing you'd do for a file): > > import sys > for line in sys.stdin: > # do stuff with that line of input Aha, that makes sense. Thanks very much. Nick . From nick at javacat.f2s.com Tue Mar 1 23:28:02 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Mar 1 23:26:45 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109715774.4224eb3e7dc38@www.paradise.net.nz> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> <1109715774.4224eb3e7dc38@www.paradise.net.nz> Message-ID: <1109716082.10412.17.camel@fuzzbox.local> On Wed, 2005-03-02 at 11:22 +1300, jfouhy@paradise.net.nz wrote: > Quoting Sean Perry <shaleh@speakeasy.net>: > > > for line in sys.stdin.readlines(): > > # handle the line > > > > I tend to use xreadlines() which does not read the entire input at once. > > xreadlines() these days just does 'return self', I believe. File objects are > their own iterators; you can just do: > > for line in sys.stdin: > # do stuff > Same as Max Noel said, must be a good idea ;) Thankyou Nick . From jfouhy at paradise.net.nz Tue Mar 1 23:28:37 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 1 23:28:41 2005 Subject: [Tutor] reading from stdin In-Reply-To: <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> Message-ID: <1109716117.4224ec95cedec@www.paradise.net.nz> Quoting Max Noel <maxnoel_fr@yahoo.fr>: > UNIX philosophy is to have programs start acting as soon as possible > -- in that case, as soon as the first line is available. You should be > reading sys.stdin as an iterator (same thing you'd do for a file): > > import sys > for line in sys.stdin: > # do stuff with that line of input Is this sufficient? I tried to write a test program to get that behaviour.. ----- produce.py ----- #!/usr/bin/python import time for i in xrange(10): time.sleep(1) print i ----- read.py ----- #!/usr/bin/python import sys for line in sys.stdin: print line.strip() -------------------- If I do: $ ./produce.py | ./read.py I get nothing for ten seconds, then I get the numbers 0 through 9, one per line. What am I missing? -- John. From shaleh at speakeasy.net Wed Mar 2 00:01:53 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 2 00:03:11 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109716117.4224ec95cedec@www.paradise.net.nz> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> <1109716117.4224ec95cedec@www.paradise.net.nz> Message-ID: <4224F461.6070307@speakeasy.net> jfouhy@paradise.net.nz wrote: > If I do: > > $ ./produce.py | ./read.py > > I get nothing for ten seconds, then I get the numbers 0 through 9, one per line. > > What am I missing? > From the python man page: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. From peterm at ccs.neu.edu Wed Mar 2 00:15:19 2005 From: peterm at ccs.neu.edu (Peter Markowsky) Date: Wed Mar 2 00:15:32 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224F461.6070307@speakeasy.net> References: <1109714880.10412.5.camel@fuzzbox.local> <9ae3338b76a4759aaf26e592986c6fc5@yahoo.fr> <1109716117.4224ec95cedec@www.paradise.net.nz> <4224F461.6070307@speakeasy.net> Message-ID: <0e6638a7b01ece43210021cdcdf32345@ccs.neu.edu> Hi, On Mar 1, 2005, at 6:01 PM, Sean Perry wrote: > jfouhy@paradise.net.nz wrote: >> If I do: >> $ ./produce.py | ./read.py >> I get nothing for ten seconds, then I get the numbers 0 through 9, >> one per line. >> What am I missing? > > From the python man page: > -u > Force stdin, stdout and stderr to be totally unbuffered. On > systems where it matters, also put stdin, stdout and stderr in binary > mode. Note that there is internal buffering in xreadlines(), > readlines() and file-object iterators ("for line in sys.stdin") which > is not influenced by this option. To work around this, you will want > to use "sys.stdin.readline()" inside a "while 1:" loop. > What exactly is the "right" way to put sys.stdin in unbuffered mode? in another program I've tried to accomplish that by doing something like this import os import fcntl <...> stdinfd = sys.stdin.fileno() fcntl.fcntl(stdinfd, fcntl.F_SETFL, os.O_NONBLOCK) ... and then calling later data = sys.stdin.read(numbytes) is this correct? -Pete From james.sweeney at ieee.org Wed Mar 2 00:22:08 2005 From: james.sweeney at ieee.org (James O. Sweeney) Date: Wed Mar 2 00:17:35 2005 Subject: [Tutor] Setting up a database Message-ID: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> Hello, I have an assignment that entails entering cash transactions as records. The significant record fields are a date/time stamp, the amount, and whether the transaction is a deposit or withdrawal. My question is about setting up the database file. In Python there is a dictionary function but it looks as if only one value can be assigned to the key (I intend to make the key the timestamp). The file has to be searchable so that reports can be pulled regarding amount, date range, etc. - the usual things one would do with a database. I can't figure if I can make a query on a multi-field record in Python without engaging a dependency such a storing the record in a mySQL database and querying it from Python. I'm having real burnout with this and would appreciate a point in the right direction. Much Thanks, James -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050301/4c47f2b1/attachment.htm From hugonz-lists at h-lab.net Wed Mar 2 00:35:55 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Mar 2 00:35:57 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109714880.10412.5.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> Message-ID: <4224FC5B.9040204@h-lab.net> Everypne else has answered pretty muh about this. I just want to add that if you want to read noncanonically (less thana line ending in "\n" you'll have to do it char by char =( AFAIK, there's no way to redefine a separator por readlines() (other than \n..) Hugo Nick Lunt wrote: > Hi folks, > > I've been pondering how to get python to read from a pipe outside of > itself, sort of. > > For example I tried a simple python prog to do a grep, eg > > # ps -e | myprog.py cron > > would give this output > > 3778 ? 00:00:00 crond > > same as > # ps -e | grep cron > > The way I did this was to use sys.stdin.readlines() to get the output > from the pipe. > > Here is the program: > > [code] > import sys, glob > args = sys.stdin.readlines() # found on the net > pat = sys.argv[1] > for i in args: > if (i.find(pat) != -1): > print i, > [/code] > > My question is am I getting the output from the pipe in the correct > way ? The way Im doing it works (so far) but should I be doing it > another way ? > > Many thanks > Nick . > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Mar 2 01:27:19 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 2 01:27:24 2005 Subject: [Tutor] Tab delim file In-Reply-To: <20050301222158.42380.qmail@web53503.mail.yahoo.com> References: <1109714880.10412.5.camel@fuzzbox.local> <20050301222158.42380.qmail@web53503.mail.yahoo.com> Message-ID: <f2ff2d0503011627541ed395@mail.gmail.com> Hi Srinivas, You want to use the csv module, it's designed for this kind of stuff. http://docs.python.org/lib/module-csv.html So, I think for your thing you'd want = import csv f1 = open('my_file.txt','r') reader = csv.reader(f1) reader.delimiter = '\t' fileA = [] fileB = [] for row in reader: toA = [] toB = [] for i in range(len(row)): if i <= 12: toA.append(row[i]) else: toB.append(row[i]) fileA.append(toA) fileB.append(toB) You may want to play with this, I'm not sure if I set the reader's delimiter right. But \t is tab. Good luck, Liam Clarke On Tue, 1 Mar 2005 14:21:58 -0800 (PST), Srinivas Iyyer <srini_iyyer_bio@yahoo.com> wrote: > Hello: > > I have a nasty file where I have 165 column and 140K > lines. > > For every 12 columns, a new dataset is written. > > 0-12 - File A's data is there > 13-24 - File B's data is there. > > My task is to write data in each 12 columns to a file. > > I have a rough idea, but when I try I am unable to > proceed further. > > f1 = open('my_file.txt','r') > aml = f1.read().split('\n') > > fLine = aml[0] > > k = len(fLine)/12 # k = 162/12 > > #So I want to jump k blocks and get the text. > > for line in aml: > cols = line.split('\t') > while i > 13: > ...... > I am lost from here... > > Every 4 line(row) contains the file name on which I > have to write the file. > > can any one plese help, i am really stuck in a > problem. > > thanks > srini > > > __________________________________________________ > 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 > -- '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. From dyoo at hkn.eecs.berkeley.edu Wed Mar 2 01:35:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 2 01:40:28 2005 Subject: [Tutor] Setting up a database In-Reply-To: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> Message-ID: <Pine.LNX.4.44.0503011613400.29049-100000@hkn.eecs.berkeley.edu> On Tue, 1 Mar 2005, James O. Sweeney wrote: > I have an assignment that entails entering cash transactions as records. Hi James, Just to make it clear: we are prohibited from doing homework questions. Since it's an assignment, we'll try to stay clear of direct solutions. > My question is about setting up the database file. In Python there is a > dictionary function but it looks as if only one value can be assigned to > the key (I intend to make the key the timestamp). A dictionary can be used to associate a single key with multiple values. If we let each value be a list, then we can do a 'key' to 'records' mapping: ### >>> d = {} >>> def addTally(name): ... d.setdefault(name[0], []).append(name) ... >>> addTally('john') >>> addTally('brian') >>> addTally('jane') >>> addTally('alice') >>> addTally('bob') >>> d {'a': ['alice'], 'j': ['john', 'jane'], 'b': ['brian', 'bob']} ### Here, we can see that the key 'john' can be associated with multiple values. The body above: ###### d.setdefault(name[0], []).append(name) ###### is shorthand for: ###### if name not in d: d[name[0]] = [] d[name[0]].append(name) ###### > The file has to be searchable so that reports can be pulled regarding > amount, date range, etc. - the usual things one would do with a > database. The direct solution would be to use a database here. > I can't figure if I can make a query on a multi-field record in Python You can. Conceptually, if you can make a query into a predicate, then you can always do a linear scan: ### Pseudocode def doQuerySearch(): resultSet = [] for record in allRecordsInDatabase: if satisfiesQuery(record): resultSet.append(record) return resultSet ### And satisfiesQuery() can do whatever it needs to do to see if the record is a good one or not. The problem here is one of efficiency: this is a linear scan. For small databases, this is fine. For larger ones, it might not be so good. Databases use indices and other optimization strategies to avoid a linear scan across the entire database. Dictionaries are one tool at our disposal that allow us to avoid linear scans. If we use several dictionaries, then we might even be able to do quick lookup on different fields. But a lot of the work behind databases involves figuring out which field constraint will cut down on the number of candidates most effectively, and that's hard work. That's why, if you can, you probably should use a real database. Best of wishes to you. From cyresse at gmail.com Wed Mar 2 01:40:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 2 01:40:34 2005 Subject: [Tutor] Setting up a database In-Reply-To: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> References: <0ICP00KVS4P83TO1@vms040.mailsrvcs.net> Message-ID: <f2ff2d05030116407afda086@mail.gmail.com> While we generally don't get too specific with assignments and/or homework - For a traditional database, you'd have to go the mySQL route. A dictionary is good, but for only one discreet key. That said, you could do it with objects like this - dictOfTransactionObjects = {} class CashTransaction: def __init__(self, amount, depOrWith): self.amount=float(amount) self.transactionType = depOrWith #...do various things which get the various values dateStamp, amount, transType dictOfTransactionObjects[dateStamp] = CashTransaction(amount, transType) So, now your dictionary will be {'01/05/2004-22:00:00' : <instance of CashTransaction>} And you could search either by the dictionary key which is acting like a primary key, (the timestamp) or like this - isWith = [] for (key, item) in dictOfTransactionObjects.items(): if item.transactionType == 'Withdrawal': isWith.append(key) And isWith becomes a list of primary keys of withdrawals. That said, I would use SQL queries instead, it's a lot more straightforward, you'll end up reinventing several wheels this way. Regards, Liam Clarke On Tue, 01 Mar 2005 18:22:08 -0500, James O. Sweeney <james.sweeney@ieee.org> wrote: > > > > Hello, > > I have an assignment that entails entering cash transactions as records. The > significant record fields are a date/time stamp, the amount, and whether the > transaction is a deposit or withdrawal. My question is about setting up the > database file. In Python there is a dictionary function but it looks as if > only one value can be assigned to the key (I intend to make the key the > timestamp). The file has to be searchable so that reports can be pulled > regarding amount, date range, etc. ? the usual things one would do with a > database. I can't figure if I can make a query on a multi-field record in > Python without engaging a dependency such a storing the record in a mySQL > database and querying it from Python. I'm having real burnout with this and > would appreciate a point in the right direction. > > Much Thanks, > > James > _______________________________________________ > 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. From dyoo at hkn.eecs.berkeley.edu Wed Mar 2 01:37:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 2 01:42:28 2005 Subject: [Tutor] Setting up a database In-Reply-To: <Pine.LNX.4.44.0503011613400.29049-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503011636130.29049-100000@hkn.eecs.berkeley.edu> > ### > >>> d = {} > >>> def addTally(name): > ... d.setdefault(name[0], []).append(name) > ... > >>> addTally('john') > >>> addTally('brian') > >>> addTally('jane') > >>> addTally('alice') > >>> addTally('bob') > >>> d > {'a': ['alice'], 'j': ['john', 'jane'], 'b': ['brian', 'bob']} > ### > > > Here, we can see that the key 'john' can be associated with multiple > values. Hi James, Quick typo correction. I meant to write: """Here, we can see that the key 'j' can be associated with multiple values.""" My apologies! From missive at hotmail.com Wed Mar 2 02:26:20 2005 From: missive at hotmail.com (Lee Harr) Date: Wed Mar 2 02:27:04 2005 Subject: [Tutor] Re: open a socket from a named file on linux Message-ID: <BAY2-F21CCDE87BF7E1CE19B3FCFB15A0@phx.gbl> Sorry. I sent this yesterday but forgot the subject. Hope this helps point you in the right direction ... >I attempting to control xfmedia, >http://spuriousinterrupt.org/projects/xfmedia/ , via it's remote from >python and I can not get a connection. > >s = socket.fromfd('/tmp/xfmedia_remote.1001.0', socket.AF_UNIX, >socket.SOCK_STREAM) > >i get this error > ></xfmedia_remote.1001.0', socket.AF_UNIX, socket.SOCK_STREAM) >Traceback (most recent call last): > File "<stdin>", line 1, in ? > >f = open('/tmp/xfmedia_remote.1001.0') >Traceback (most recent call last): > File "<stdin>", line 1, in ? >IOError: [Errno 6] No such device or address: >'/tmp/xfmedia_remote.1001.0' > >yet ls shows the file exists, xfmedia is working fine. > I have not done this before, but I think you need to create a _new_ socket for your end, and then connect to the other socket. Does that make more sense? _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From david at graniteweb.com Wed Mar 2 06:13:35 2005 From: david at graniteweb.com (David Rock) Date: Wed Mar 2 06:17:31 2005 Subject: [Tutor] reading from stdin In-Reply-To: <1109715792.10412.11.camel@fuzzbox.local> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> <1109715792.10412.11.camel@fuzzbox.local> Message-ID: <20050302051335.GB1056@wdfs.graniteweb.com> * Nick Lunt <nick@javacat.f2s.com> [2005-03-01 22:23]: > On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > > > > unless you want the output for some other reason, a more idiomatic way > > is: > > > > for line in sys.stdin.readlines(): > > # handle the line > > > > I tend to use xreadlines() which does not read the entire input at once. > > For stdin this make sense, you have no idea how much data will be > > piped in. > > Thanks Sean, I agree with you on both accounts there. For another approach to this, I like to use the fileinput module. In the case of the original example of mimicing grep, it allows you to easily handle both a list of files passed to the command or use it as a pipe. The default action if there are no files given is to use stdin. http://www.python.org/doc/2.4/lib/module-fileinput.html -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050301/66fafd35/attachment.pgp From billk at fastmail.fm Wed Mar 2 07:17:28 2005 From: billk at fastmail.fm (Bill Kranec) Date: Wed Mar 2 07:17:29 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42247232.1080409@tds.net> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> Message-ID: <42255A78.6040909@fastmail.fm> Hi Kent, First off, thank you so much for the suggestions! They have helped clarify some of the concepts I've been struggling with lately ( mostly object - related ones ). I have been teaching myself Python in my spare time for the last few months, and have no previous programming experience, so any feedback I get really helps me improve as a programmer. I have implemented some of the changes you talked about, and posted an updated version of my program here: http://rafb.net/paste/results/SicsjJ23.html I hope this new version is a bit better, and that my answers to your questions help you understand what I'm doing. > do you mean, 'each player is teammates with each other player exactly > once', or, 'each player is teammates with each other player at most > once'? Is there a certain number of rounds that must be played? Each player is teammates with each other player exactly once. > - Why do you have the initialization code in a comment? Wouldn't it be > helpful to put that in a function or maybe Tournament.__init__()? The initialization code is commented because I don't run it every time the script runs ( it takes awhile to run ). I usually load the list from a file, this is reflected in my updated code. > - I have a hard time figuring out how this is supposed to work. Maybe > some comments about the algorithm you are using would help? I have no > idea what self.key is doing. My algorithm works something like this: Fact: roundlist partitions into 11 slices of length 113400, and self.key keeps track of which round in each of those slices I am currently using. Starting with the first tournament ( Tournament(0) ), I do the following: 1. Construct the tournament. 2. Test to see if two players are on the same team twice ( checkTeammates ) 3. Test to see if two players match up against each other too often (checkOpponents ) 4a. If everything is ok, I'll append another round from the next slice. 4b. If not, I'll try the next round in the most recent slice. If none of the rounds in the slice work, I'll move back and try the next round in the previous slice, etc. 5. Whenever I manage to build an 11 round tournament, I'm done. It's an attempt at a recursive algorithm, and I'm not sure how well it is implemented. > - What is the argument to Tournament.__init__() for? The argument lets you specify a starting tournament, to avoid having to start the search from the beginning, you can instead pick up from some point where you last left off. Example: Tournament(0,113460) gives a two round tournament using elements 0, 113460 from roundlist. > - The above code depends on roundlist which is not even defined > anywhere in the module (just shown in the comment). This suggests > again that the init code from the comment should be part of > Tournament, and roundlist should be an attribute of Tournament. For a > class to depend on some external variable is bad design and will break > if the client code is in a different module from the class code > (roundlist will be in a different namespace than Tournament). I have always been uneasy about this, but I wanted to be able to define multiple tournament objects off of the same roundlist, to avoid generating the list every time a new object is created. I think what I really want to do is have a separate Round class, from which Tournament inherits the list of rounds. I have started to implement something like this in my most recent version, but haven't finished it yet. ( I need to understand class inheritance better. ) > - Tournament.next() doesn't return a value, it prints it directly. It > should return self.key or str( self.key ) Does the next() call in an iterator object need to return a value, and if so, why? ( My reasoning was that next() only needs to increment the iterator. ) Thanks again for any additional suggestions! Bill From jeffshannon at gmail.com Wed Mar 2 08:44:43 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Mar 2 08:44:47 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42255A78.6040909@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> <42255A78.6040909@fastmail.fm> Message-ID: <5d0204a1050301234415bcccd4@mail.gmail.com> On Wed, 02 Mar 2005 01:17:28 -0500, Bill Kranec <billk@fastmail.fm> wrote: > [...] I wanted to be able to define > multiple tournament objects off of the same roundlist, to avoid > generating the list every time a new object is created. I think what I > really want to do is have a separate Round class, from which Tournament > inherits the list of rounds. I have started to implement something like > this in my most recent version, but haven't finished it yet. ( I need > to understand class inheritance better. ) This sounds like a good idea, but inheritance is probably not the right way to solve it. Every Tournament contains a list of Rounds, but it's probably not accurate to say that a Tournament is a type of Round. (Inheritance works best when it describes an "is-a" relationship, not a "has-a" relationship.) It's probably better to have Tournament and Round be independent classes, but have Tournament instances hold a list of Rounds (which may be passed in during initialization, or may be added later). This is called "composition", and is just as important (or perhaps more important) of an idea as inheritance, even though inheritance gets all the press. ;) Jeff Shannon From nick at javacat.f2s.com Wed Mar 2 08:59:33 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Mar 2 08:58:14 2005 Subject: [Tutor] reading from stdin In-Reply-To: <20050302051335.GB1056@wdfs.graniteweb.com> References: <1109714880.10412.5.camel@fuzzbox.local> <4224E94F.7070403@speakeasy.net> <1109715792.10412.11.camel@fuzzbox.local> <20050302051335.GB1056@wdfs.graniteweb.com> Message-ID: <1109750373.5012.0.camel@fuzzbox.local> Thanks to everyone who helped me with this. It's certainly given me something to think about :) Cheers Nick . On Tue, 2005-03-01 at 23:13 -0600, David Rock wrote: > * Nick Lunt <nick@javacat.f2s.com> [2005-03-01 22:23]: > > On Tue, 2005-03-01 at 14:14 -0800, Sean Perry wrote: > > > > > > > > unless you want the output for some other reason, a more idiomatic way > > > is: > > > > > > for line in sys.stdin.readlines(): > > > # handle the line > > > > > > I tend to use xreadlines() which does not read the entire input at once. > > > For stdin this make sense, you have no idea how much data will be > > > piped in. > > > > Thanks Sean, I agree with you on both accounts there. > > For another approach to this, I like to use the fileinput module. In the > case of the original example of mimicing grep, it allows you to easily > handle both a list of files passed to the command or use it as a pipe. > The default action if there are no files given is to use stdin. > > http://www.python.org/doc/2.4/lib/module-fileinput.html > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Wed Mar 2 09:19:51 2005 From: nick at javacat.f2s.com (Nick Lunt) Date: Wed Mar 2 09:18:34 2005 Subject: [Tutor] reading from stdin In-Reply-To: <4224FC5B.9040204@h-lab.net> References: <1109714880.10412.5.camel@fuzzbox.local> <4224FC5B.9040204@h-lab.net> Message-ID: <1109751591.5278.0.camel@fuzzbox.local> Hi Hugo, many thanks for pointing that out. It all helps :) Thanks again, Nick . On Tue, 2005-03-01 at 17:35 -0600, Hugo Gonz?lez Monteverde wrote: > Everypne else has answered pretty muh about this. I just want to add > that if you want to read noncanonically (less thana line ending in "\n" > you'll have to do it char by char =( AFAIK, there's no way to redefine a > separator por readlines() (other than \n..) > > Hugo > > Nick Lunt wrote: > > Hi folks, > > > > I've been pondering how to get python to read from a pipe outside of > > itself, sort of. > > > > For example I tried a simple python prog to do a grep, eg > > > > # ps -e | myprog.py cron > > > > would give this output > > > > 3778 ? 00:00:00 crond > > > > same as > > # ps -e | grep cron > > > > The way I did this was to use sys.stdin.readlines() to get the output > > from the pipe. > > > > Here is the program: > > > > [code] > > import sys, glob > > args = sys.stdin.readlines() # found on the net > > pat = sys.argv[1] > > for i in args: > > if (i.find(pat) != -1): > > print i, > > [/code] > > > > My question is am I getting the output from the pipe in the correct > > way ? The way Im doing it works (so far) but should I be doing it > > another way ? > > > > Many thanks > > Nick . > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > From carroll at tjc.com Wed Mar 2 10:02:22 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Mar 2 10:02:31 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c225925305030106517884079b@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503020009480.28107-100000@violet.rahul.net> On Tue, 1 Mar 2005, Mark Kels wrote: > Can anyone give me a very simple example on thread programming ? I don't think a simple example is possible, given that threads are inherently for slightly more complex processing than you ordinarily do. That being said, here's an example. This is a made-up process. It shows both queuing and an arbitrary number of threads. First, the imports: ########################### import random, os, time, sys import threading, Queue ########################### No, I'll define a class for the "work" to be performed. Basically, each work unit just specifies how much time the system is supposed to wait, in second; pretend that it's doing some amount of work that takes some number of seconds to be performed: ########################### class workunit(object): """ Sample object to be put on a queue similating work to be done. variables: counter: a serial number just for identification purposes. waittime: the time in second it uses up. Done: a flag used for a special-purpose end-of-queue sentinel, in which case waittime is ignored. """ counter = 1 def __init__(self, waittime=0, Done=False): self.counter = workunit.counter self.waittime = waittime self.Done = Done workunit.counter += 1 ########################### This will be called in one of two ways: w = workunit(waittime=20) # to indicate wait for 20 seconds; or w = workunit(Done=True) # to add a "dummy" work unit to the queue so # everyone know the queue is empty and finished. Okay, imagine a queue (or just a list) full of work units like the above. Here's a plain old sequential NON-THREAD way of processing this: ########################### def ProcessQueue(work_queue): """ Method to process an element from the queue (Non-Threaded implementation). All it does is loop, doing the following: pull an element from the queue (break out if it's a "Done" marker) print a starting message; wait for the specified amount of time; print an ending message """ while True: queue_entry = work_queue.get() if queue_entry.Done: break print "%s starting on workunit %d, %d secs" % \ (time.asctime(), queue_entry.counter, queue_entry.waittime) time.sleep(queue_entry.waittime) print "%s ending for workunit %d" % \ (time.asctime(), queue_entry.counter) ############################ Okay, understand that, first See what it's doing? It's just popping things off the work_queue, printing a message, waiting for the indicated amount of time in the work unit, and printing another message; then starting over. Now, let's try the same approach with threads. Firrst, the class declaration: ############################# class ThreadProcessQueue(threading.Thread): """ This is a Threaded equivalent to ProcessQueue(). """ ############################# Now, here's the ThreadProcessQueue.__init__: ############################# def __init__(self, threadname, work_queue, **kwds): self.tname = threadname self.work_queue = work_queue threading.Thread.__init__(self, **kwds) print "%s Thread %s started" % (time.asctime(), self.tname) ############################# The parameters here are an arbitrary name for the thread, and the queue it will process. All __init__ does is print a message that the thread started. Here's the guts of it, the ThreadProcessQueue.__run__ method. NOte how similar it is to the non-Threaded version: ############################# def run(self): while True: queue_entry = work_queue.get() if queue_entry.Done: break print "%s Thread %s starting on workunit %d, %d secs" % \ (time.asctime(), self.tname, queue_entry.counter, queue_entry.waittime) time.sleep(queue_entry.waittime) print "%s Thread %s ending for workunit %d" % \ (time.asctime(), self.tname, queue_entry.counter) print "%s %s thead ending." % (time.asctime(), self.tname) self.work_queue.put(queue_entry) ############################# The only real difference is that the messages produced include an identifier so you can see which thread is generating which message; and also there's that self.work_queue.put(queue_entry) at the end. I'll discuss that at the end of this message. Now, here's the main program that uses these. First some setup: ############################ print "MAIN: %s starting..." % (time.asctime()) work_queue = Queue.Queue() NumWorkUnits=8 NumThreads=3 WaitTimes = [3,6,9,12,1,5,5,1] lenWaitTimes = len(WaitTimes) # WaitTimes is just a list of some arbitrary times representing work # A particular WorkUnit will wait for one of these times. ThreadList=[] ########################### Queue is s specialized type of FIFO list, which is made to be shared among concurrently running threads. We use that instead of a plain list. NumWorkUnits and NumThreads are just constants, for the number of work units that we'll put in the queue, and the number of threads that will read from them. WaitTimes is just an arbitrary list of numbers that we'll randomly select from later. Every work unit will get a random one of these, which indicates how long it should take to be processed (e.g., 1 for a 1-second workunit, 12 for a 12-second workunit, etc. ThreadList is a list that will contain all the threads. Let's get those threads going: ################################# # make up a list of threads (not started yet) for i in range(1,NumThreads+1): ThreadName = "T%03d" % i ThreadList.append(ThreadProcessQueue(ThreadName, work_queue)) ################################# Okay, this has created three threads (NumThreads = 3), with names T001, T002 and T003. Each has been passed the work_queue (which is still empty), and all three threads have been added to the ThreadList. The threads all exist at this point, but have not yet been started. That's next: ############################### # start the Threads for t in ThreadList: t.start() print "%s MAIN: all threads started" % (time.asctime()) ############################### This just starts the threads. The __run__ method in each thread starts running. The problem is, with the work queue empty, they'll just sit there. So, let's start putting stuff into the work queue: ############################### # Start putting things on the queue for i in range(NumWorkUnits): random_wait = WaitTimes[int(random.uniform(0,len(WaitTimes)))] w = workunit(random_wait) work_queue.put(w) ############################### This just selects a random amount of time to wait from the WaitTimes list, creates a work unit specifying that amount of time, and puts the workunit on the queue. At this point, the threads should start waking up; they were all sitting on a queue.get for an empty queue. NOw that they can start pulling things off of it, they will. I also want to put an end-of-queue element here: ############################### # Put a shutdown indicator work_queue.put(workunit(Done=True)) ############################### That's it! Just for grins, we can add a "final" shutdown message: ############################ print "%s MAIN: all done." % (time.asctime()) ############################ But you'll see that doesn't work very well. Here's what I see as output on one run: Wed Mar 02 00:40:05 2005 MAIN starting... Wed Mar 02 00:40:05 2005 Thread T001 started Wed Mar 02 00:40:05 2005 Thread T002 started Wed Mar 02 00:40:05 2005 Thread T003 started Wed Mar 02 00:40:05 2005 MAIN: all threads started Wed Mar 02 00:40:05 2005 Thread T001 starting on workunit 1, 5 secs Wed Mar 02 00:40:05 2005 Thread T002 starting on workunit 2, 12 secs Wed Mar 02 00:40:05 2005 Thread T003 starting on workunit 3, 9 secs Wed Mar 02 00:40:05 2005 MAIN: all done. Wed Mar 02 00:40:10 2005 Thread T001 ending for workunit 1 Wed Mar 02 00:40:10 2005 Thread T001 starting on workunit 4, 6 secs Wed Mar 02 00:40:14 2005 Thread T003 ending for workunit 3 Wed Mar 02 00:40:14 2005 Thread T003 starting on workunit 5, 12 secs Wed Mar 02 00:40:16 2005 Thread T001 ending for workunit 4 Wed Mar 02 00:40:16 2005 Thread T001 starting on workunit 6, 12 secs Wed Mar 02 00:40:17 2005 Thread T002 ending for workunit 2 Wed Mar 02 00:40:17 2005 Thread T002 starting on workunit 7, 1 secs Wed Mar 02 00:40:18 2005 Thread T002 ending for workunit 7 Wed Mar 02 00:40:18 2005 Thread T002 starting on workunit 8, 1 secs Wed Mar 02 00:40:19 2005 Thread T002 ending for workunit 8 Wed Mar 02 00:40:19 2005 T002 thead ending. Wed Mar 02 00:40:26 2005 Thread T003 ending for workunit 5 Wed Mar 02 00:40:26 2005 T003 thead ending. Wed Mar 02 00:40:28 2005 Thread T001 ending for workunit 6 Wed Mar 02 00:40:28 2005 T001 thead ending. >From the queue's point of view, here is how the work got parcelled out among threads: Work units: 1: 5 sec (T001) 2: 12 sec (T002) 3: 9 sec (T003) 4: 6 sec (T001) 5: 12 sec (T003) 6: 12 sec (T001) 7: 1 sec (T002) 8: 1 sec (T002) Here's a graphical view of what the threads were doing: T001: 11111444444666666666666 T002: 22222222222278 T003: 333333333555555555555 You can see that T002 ended first, followed by T003 and then T001 (which matches the timestamps). Okay, a couple oddities. First, that self.work_queue.put(queue_entry) line. This is so that when the first thread to see the Done marker sees it, it puts it back on the queue before it exits. That way, each of the other threads sees it, puts it back on for the next and exits. (I could have instead written this just to exeit when the queue was empty, but there are some ugly issues with that, too, for example, if the thing that loads up the queue pauses, the queue empties and all the threads quit, and then the queue loader adds more, with the threads already gone.) The other oddity: Note that the MAIN "final message" issued long before the threads were done. I wanted this example to nicely wait for all the threads to end before putting out that message, but couldn't figure out how to do that. For those familiar with threads: calls to t.isAlive() returned True long after the thread referred to had finished up and put out its final shitdown message. Anyway, I hope this helps as a bit of a tutorial. From linux236r4 at hotpop.com Wed Mar 2 11:48:19 2005 From: linux236r4 at hotpop.com (dm) Date: Wed Mar 2 11:48:26 2005 Subject: [Tutor] open a socket from a named file on linux In-Reply-To: <1109546297.14526.9.camel@bioblue> References: <1109546297.14526.9.camel@bioblue> Message-ID: <1109760499.14594.1.camel@bioblue> On Sun, 2005-02-27 at 17:18 -0600, dm wrote: > Hello, I am trying to open a socket connection to a named file on my > computer and can not seem to get it working. Any help or advice would > be great. solution use what are called unix domain sockets, in python they are accessed like this <code> s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) s.connect('/tmp/xfmedia_remote.1001.0') </code> now s is a normal socket object. From kent37 at tds.net Wed Mar 2 13:23:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 2 13:23:06 2005 Subject: [Tutor] Re: Help- Simple recursive function to build a list In-Reply-To: <4225455D.6030808@elemental-systems.com> References: <mailman.3222.1109731598.22381.python-list@python.org> <42252a53_2@newspeer2.tds.net> <4225455D.6030808@elemental-systems.com> Message-ID: <4225B024.2000605@tds.net> actuary77 wrote: > Kent Johnson wrote: >> >>> def rec(n,alist=[]): >> ... _nl=alist[:] >> ... print n,_nl >> ... if n == 0: >> ... print n,_nl >> ... return _nl >> ... else: >> ... _nl=_nl+[n] >> ... return rec(n-1,_nl) >> ... >> >>> _nl = rec(4) >> 4 [] >> 3 [4] >> 2 [4, 3] >> 1 [4, 3, 2] >> 0 [4, 3, 2, 1] >> 0 [4, 3, 2, 1] >> >>> print _nl >> [4, 3, 2, 1] >> >> Kent > > Kent, thank you for the answer. > > I just don't understand why. > > I only have one return at the point at the test of the end of the > recursion, n == 0. You have to return a result from each level of recursion. You have rec(4) <- this returns nothing to its caller rec(3, [4]) <- this returns nothing to its caller rec(2, [4,3]) <- this returns nothing to its caller rec(1, [4,3,2]) <- this returns nothing to its caller rec(0, [4,3,2,1]) <- this returns [4,3,2,1] to the call above By adding the missing 'return', you make all the intermediate invocations return the final result up the chain to their caller. This version shows what is happening: >>> def rec(n,alist=[]): ... _nl=alist[:] ... if n == 0: ... print n,_nl ... return _nl ... else: ... _nl=_nl+[n] ... print 'calling rec(', n-1, _nl, ')' ... val = rec(n-1,_nl) ... print 'rec(', n-1, _nl, ') returned', val ... return val ... >>> rec(4) calling rec( 3 [4] ) calling rec( 2 [4, 3] ) calling rec( 1 [4, 3, 2] ) calling rec( 0 [4, 3, 2, 1] ) 0 [4, 3, 2, 1] rec( 0 [4, 3, 2, 1] ) returned [4, 3, 2, 1] rec( 1 [4, 3, 2] ) returned [4, 3, 2, 1] rec( 2 [4, 3] ) returned [4, 3, 2, 1] rec( 3 [4] ) returned [4, 3, 2, 1] [4, 3, 2, 1] Kent PS Please send followups to the Tutor list so all may benefit from the discussion. > > I see from the output that the list is being built, up to the point of > the one and only return, > > if n == 0: > print n,_nl # 0 [4, 3, 2, 1] > return _nl # None, Why doesn't this return _nl = [4, 3, 2, 1]? > > I can see that the list is being built without the second return. > And even at the point where the end of the recursion is tested, n == 0, > the value to be returned, _nl is equal to the desired result? > The second return is never used! > The list being built is passed as an argument. > > Scope? > > Why is the second return required? > > Most confused ;( > > From shitizb at yahoo.com Wed Mar 2 18:03:43 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 2 18:03:47 2005 Subject: [Tutor] Re: Online Programming Contest (Python solutions accepted) In-Reply-To: <1109765080.931561.250290@g14g2000cwa.googlegroups.com> Message-ID: <20050302170343.60015.qmail@web53802.mail.yahoo.com> Hi, some questions need to be addressed. First, is execution time a factor, bcos admittedly python sols r much slowere than c/c++. second, wats the exact conf of python installed on machines checking our sols. i.e. which modules r allowed n which r not. shitiz --- Sridhar <sridharinfinity@gmail.com> wrote: > Hi, > > We, the students of CEG, Anna University [1] are > organizing an online > programming contest as part of aBaCus [2] 2005. The > contest itself > will start on 6th March 2005 at 1:00 pm IST [3] and > will end after 5 > hours. You have to solve the problems posted at the > start of the > contest. Teams ranking high will be awarded the > prizes. > > As a special note, inspite of C,C++ and Java we also > allow Python [4] > this time. So we hope a lot of Pythonistas also > could attend the > contest for fun. :-) > > For more details about the contest, visit the > contest page > > -- http://203.197.138.181/OPC -- > > [1] http://en.wikipedia.org/wiki/Anna_University > [2] http://www.annauniv.edu/abacus/ > [3] Indian Standard Time (IST) is the time zone for > India. It is 5 > hours and 30 minutes ahead of GMT/UTC. > [4] http://www.python.org > > -- > Sridhar Ratna - http://srid.bsdnerds.org > > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From s.varun at gmail.com Wed Mar 2 19:20:42 2005 From: s.varun at gmail.com (Varun Soundararajan) Date: Wed Mar 2 19:20:46 2005 Subject: [Tutor] Re: Python Online Programming Contest In-Reply-To: <32b5ee76050224114510c9cd5e@mail.gmail.com> References: <32b5ee76050224114510c9cd5e@mail.gmail.com> Message-ID: <32b5ee760503021020557ea67a@mail.gmail.com> Hi, The results of OPC (online programming contest) is out. The statistics of python usage is available at http://www.samhita.info/opc/status.php. Regards, -OPC Team From mark.kels at gmail.com Wed Mar 2 20:35:56 2005 From: mark.kels at gmail.com (Mark Kels) Date: Wed Mar 2 20:36:00 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <20050301202537.62490.qmail@web53804.mail.yahoo.com> References: <c225925305030106517884079b@mail.gmail.com> <20050301202537.62490.qmail@web53804.mail.yahoo.com> Message-ID: <c2259253050302113555cab32f@mail.gmail.com> On Tue, 1 Mar 2005 12:25:37 -0800 (PST), Shitiz Bansal <shitizb@yahoo.com> wrote: > > Here is a simple program > > class abc(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > self.x=1 etc. etc..... > self.cont_flag=1 > def run(self): > while self.cont_flag: > print self.x > (you can set the self.cont_falg to zero > whenever you wish to end the loop(and > hence > the thread., either > here, or even from outside the thread. > of course, it isnt necessary that your > thread is a loop, it can be a finite > function.) > Thanks alot !! I think I got it ths time. The only problem is that when I try to do it my thread doesnt closes. When does a thread closes ? Thanks again. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From gwyn.evans at gmail.com Wed Mar 2 21:34:18 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Wed Mar 2 21:34:22 2005 Subject: [Tutor] Threaded persistance? Message-ID: <c0312f5d050302123433eb084e@mail.gmail.com> Hi, New to Python, but with Java background I'm interested in comments/suggestions for something I'm trying... I've got a series of events (basically a dictionary of a few key:value pairs) which I'd like to forward onto a web service. That should be no problem, but I'm investigating what I can do when the web service is down for a bit. What I'm considering is to persist the event and trigger a seperate thread to retry the forwarding. What I'm wondering about is if there's a storage method that allows 1 thread writing to the storage while the other thread reads and then deletes from the storage... I had a look at using ZODB but hit problems when trying to have two connections to the same FileStorage DB, but a second look at things suggested that dbm might well do what I need, if I ensure only one thread at a time can access it. /Gwyn From kent37 at tds.net Wed Mar 2 21:53:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 2 21:53:15 2005 Subject: [Tutor] Threaded persistance? In-Reply-To: <c0312f5d050302123433eb084e@mail.gmail.com> References: <c0312f5d050302123433eb084e@mail.gmail.com> Message-ID: <422627BD.6020304@tds.net> Gwyn Evans wrote: > Hi, > New to Python, but with Java background I'm interested in > comments/suggestions for something I'm trying... > > I've got a series of events (basically a dictionary of a few > key:value pairs) which I'd like to forward onto a web service. That > should be no problem, but I'm investigating what I can do when the web > service is down for a bit. > What I'm considering is to persist the event and trigger a seperate > thread to retry the forwarding. What I'm wondering about is if > there's a storage method that allows 1 thread writing to the storage > while the other thread reads and then deletes from the storage... Do you need to allow for the sending thread to be restarted as well? In other words, does the queue have to be persistent? If not, you could use Queue.Queue which is intended for this kind of inter-thread communication. Kent From nixonron at yahoo.com Wed Mar 2 21:54:04 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Wed Mar 2 21:54:07 2005 Subject: [Tutor] Better Search and replace method Message-ID: <20050302205404.33444.qmail@web20326.mail.yahoo.com> I'm trying to figure out a better solution to do multiple search and replaces in a text file without having to type: import re s = open('filename') re.sub('vaule1','value2',s) re.sub('vaule3','value4',s) etc I've tried putting all the vaules in a list and doing the replace, but came up short. Any suggestions? Thanks in advance Ron __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From gwyn.evans at gmail.com Wed Mar 2 21:59:35 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Wed Mar 2 21:59:44 2005 Subject: [Tutor] Threaded persistance? In-Reply-To: <422627BD.6020304@tds.net> References: <c0312f5d050302123433eb084e@mail.gmail.com> <422627BD.6020304@tds.net> Message-ID: <c0312f5d050302125964554ea3@mail.gmail.com> On Wed, 02 Mar 2005 15:53:17 -0500, Kent Johnson <kent37@tds.net> wrote: > Gwyn Evans wrote: > > Hi, > > New to Python, but with Java background I'm interested in > > comments/suggestions for something I'm trying... > > > > I've got a series of events (basically a dictionary of a few > > key:value pairs) which I'd like to forward onto a web service. That > > should be no problem, but I'm investigating what I can do when the web > > service is down for a bit. > > What I'm considering is to persist the event and trigger a seperate > > thread to retry the forwarding. What I'm wondering about is if > > there's a storage method that allows 1 thread writing to the storage > > while the other thread reads and then deletes from the storage... > > Do you need to allow for the sending thread to be restarted as well? In other words, does the queue > have to be persistent? If not, you could use Queue.Queue which is intended for this kind of > inter-thread communication. Ideally, yes, although the main issue I was concerned about with Queue.Queue was that I didn't want to be be limited by memory size... I guess the final fallback would be going straight to a full-blown DB with a connection from each thread, but I'm not sure if it's a bit over the top... /Gwyn From gwyn.evans at gmail.com Wed Mar 2 22:15:50 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Wed Mar 2 22:15:53 2005 Subject: [Tutor] Re: Threaded persistance? In-Reply-To: <c0312f5d050302123433eb084e@mail.gmail.com> References: <c0312f5d050302123433eb084e@mail.gmail.com> Message-ID: <c0312f5d05030213156fca657b@mail.gmail.com> On Wed, 2 Mar 2005 20:34:18 +0000, Gwyn Evans <gwyn.evans@gmail.com> wrote: > I had a look at using ZODB but hit problems when trying to have two > connections to the same FileStorage DB, but a second look at things > suggested that dbm might well do what I need, if I ensure only one > thread at a time can access it. When I found I had the same sort of issue with dbm I had a closer look and realised that my test code was tidying up too quickly and closing the DB before the test had actually finished, so it looks as if ZODB's still in the picture! /Gwyn From carroll at tjc.com Wed Mar 2 22:48:51 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Mar 2 22:48:54 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c2259253050302113555cab32f@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503021346290.4283-100000@green.rahul.net> On Wed, 2 Mar 2005, Mark Kels wrote: > The only problem is that when I try to do it my thread doesnt closes. > When does a thread closes ? You got me. That's what I meant when I wrote "calls to t.isAlive() returned True long after the thread referred to had finished up and put out its final [shutdown] message." I don't know what it would take to have a t.isAlive() call ever come back as False. I may experiment a bit. That tutorial and program was put together on the fly late last night, and I didn't have the opportunity to look into that issue. From alan.gauld at freenet.co.uk Wed Mar 2 23:19:45 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 2 23:19:48 2005 Subject: [Tutor] Better Search and replace method References: <20050302205404.33444.qmail@web20326.mail.yahoo.com> Message-ID: <004601c51f75$f12b7940$1cd28751@xp> > I'm trying to figure out a better solution to do > multiple search and replaces in a text file without > having to type: > import re > s = open('filename') s = open(...).read() # I assume? > re.sub('vaule1','value2',s) > re.sub('vaule3','value4',s) > I've tried putting all the vaules in a list and doing > the replace, but came up short. Any suggestions? Without seeing what you tried or what the results were I can only guess... But did you try storing the values as a list of tuples, or as a dictionary? values = [ (vaule1, value2), (vaule3,value4),...] for target,replace in values: re.sub(target,replace,s) OR values = { 'vaule1' : 'value2', 'vaule3' : 'value4', .....} for target in values.keys(): re,sub(target,values[target],s) Finally do you need re? Or could the simple string methods work? They'd be slightly faster... Alan G. From kent37 at tds.net Wed Mar 2 23:44:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 2 23:44:06 2005 Subject: [Tutor] Better Search and replace method In-Reply-To: <20050302205404.33444.qmail@web20326.mail.yahoo.com> References: <20050302205404.33444.qmail@web20326.mail.yahoo.com> Message-ID: <422641B1.1040709@tds.net> Ron Nixon wrote: > I'm trying to figure out a better solution to do > multiple search and replaces in a text file without > having to type: > import re > s = open('filename') > re.sub('vaule1','value2',s) > re.sub('vaule3','value4',s) > etc > > I've tried putting all the vaules in a list and doing > the replace, but came up short. Any suggestions? See this recipe which uses the ability of re.sub() to take a callable as the substitution parameter to do what you want. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 Kent From shitizb at yahoo.com Wed Mar 2 23:48:11 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 2 23:48:16 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c2259253050302113555cab32f@mail.gmail.com> Message-ID: <20050302224811.80682.qmail@web53804.mail.yahoo.com> The thread finishes when: 1.The run method finishes. 2.In case of the loop- you may - >>> import threading >>> class abc(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.cont_flag=1 def run(self): while self.cont_flag: pass >>> abcd=abc() >>> abcd <abc(Thread-1, initial)> >>> abcd.start() >>> abcd <abc(Thread-1, started)> >>> abcd.cont_flag=0 >>> abcd <abc(Thread-1, stopped)> Also, you may >>> del abcd >>> abcd Traceback (most recent call last): File "<pyshell#29>", line 1, in -toplevel- abcd NameError: name 'abcd' is not defined I am not very sure about the CPU usage of a stopped thread.Perhaps someone from the group can enlighten us. Hope this makes it clear. Cheers, Shitiz --- Mark Kels <mark.kels@gmail.com> wrote: > On Tue, 1 Mar 2005 12:25:37 -0800 (PST), Shitiz > Bansal > <shitizb@yahoo.com> wrote: > > > > Here is a simple program > > > > class abc(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > self.x=1 etc. etc..... > > self.cont_flag=1 > > def run(self): > > while self.cont_flag: > > print self.x > > (you can set the self.cont_falg to zero > > whenever you wish to end the loop(and > > hence > > the thread., either > > here, or even from outside the thread. > > of course, it isnt necessary that your > > thread is a loop, it can be a finite > > function.) > > > Thanks alot !! > I think I got it ths time. > The only problem is that when I try to do it my > thread doesnt closes. > When does a thread closes ? > > Thanks again. > > -- > 1. The day Microsoft makes something that doesn't > suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about > it's friends. > 3. Documentation is like sex: when it is good, it is > very, very good. > And when it is bad, it is better than nothing. - > Dick Brandon > __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From tegmine at gmail.com Thu Mar 3 00:59:58 2005 From: tegmine at gmail.com (Luis N) Date: Thu Mar 3 01:00:02 2005 Subject: [Tutor] slow html generation code Message-ID: <77bfa81a05030215596064b8fd@mail.gmail.com> This code seems a little slow, is there anything in particular that jumps out as being not quite right. The idea is that a file is opened that contains path names to other files, that are appended and outputed into a directory of choice. I plan to move this off the filesystem into a database when the concept is worked out, maybe that will help. #!/usr/local/bin/python import sys import os from string import Template from textile import textile def main(files): if len(files) < 1: print 'Feed me with XHTML, String Templates, and Textile' else: path = os.path.expanduser('~/') publish = os.path.join(path, 'publish') pages = os.path.join(publish, 'pages') write = os.path.join(path, 'public_html/write') try: for i in files: page = os.path.join(write, i) f = open(os.path.join(pages, i), 'r') tmp = "" for line in f.readlines(): line = line.rstrip() structure = open(os.path.join(publish, line)) clean = structure.read() tmp = tmp + clean.rstrip() txt = textile(tmp) + '</body></html>' t = Template(txt) s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) output = open(page, 'w') output.write('') output.write(s) except: pass if __name__ == '__main__': main(sys.argv[1:]) From shaleh at speakeasy.net Thu Mar 3 01:12:45 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Mar 3 01:14:03 2005 Subject: [Tutor] slow html generation code In-Reply-To: <77bfa81a05030215596064b8fd@mail.gmail.com> References: <77bfa81a05030215596064b8fd@mail.gmail.com> Message-ID: <4226567D.1020806@speakeasy.net> Luis N wrote: > This code seems a little slow, is there anything in particular that > jumps out as being not quite right. > > The idea is that a file is opened that contains path names to other > files, that are appended and outputed into a directory of choice. > > I plan to move this off the filesystem into a database when the > concept is worked out, maybe that will help. > You are reading entire file contents into memory. Once with f.readlines() and then again with structure.read(). If these are somewhat large files that could definitely be a place for slowness. If nothing else, Python promises garbage collection to be done, but not when. So many of your files could be sitting in memory. From dyoo at hkn.eecs.berkeley.edu Thu Mar 3 01:37:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 3 01:37:43 2005 Subject: [Tutor] slow html generation code In-Reply-To: <77bfa81a05030215596064b8fd@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503021623350.17948-100000@hkn.eecs.berkeley.edu> On Wed, 2 Mar 2005, Luis N wrote: > This code seems a little slow, is there anything in particular that > jumps out as being not quite right. Hi Luis, Some comments: You have an empty 'except' exception-handling block in the code: ###### try: for i in files: page = os.path.join(write, i) ## ... code cut output.write(s) except: pass ###### Try not to do that. *grin* Having 'except: pass' is almost always a bad idea because it really makes it hard to debug problems. Make sure your exception handler does something useful: as it is, the code can disguise all sorts of bugs without giving any feedback to you. It's not clear at all what the benefit of the custom exception handler is in your code, so I'd recommend just dropping the try/except. Another thing is that the code is a big long: it might be worthwhile to break: > page = os.path.join(write, i) > f = open(os.path.join(pages, i), 'r') > tmp = "" > for line in f.readlines(): > line = line.rstrip() > structure = open(os.path.join(publish, line)) > clean = structure.read() > tmp = tmp + clean.rstrip() > txt = textile(tmp) + '</body></html>' > t = Template(txt) > s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) > output = open(page, 'w') > output.write('') > output.write(s) off into its own helper function. Let's pretend that we call this function 'writePage()': ###### def writePage(): ## FIXME: the argument list here isn't quite right yet page = os.path.join(write, i) f = open(os.path.join(pages, i), 'r') tmp = "" for line in f.readlines(): line = line.rstrip() structure = open(os.path.join(publish, line)) clean = structure.read() tmp = tmp + clean.rstrip() txt = textile(tmp) + '</body></html>' t = Template(txt) s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) output = open(page, 'w') output.write('') output.write(s) ###### This breakup isn't quite right yet, and this needs to take in some parameters. So it needs a little work. But this improves the code by allowing you to concentrate on what it means to write a single page. It also makes it easier to see a possible bug in the code: the last few lines in the 'for' loop look suspicious: ###### txt = textile(tmp) + '</body></html>' t = Template(txt) s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) output = open(page, 'w') output.write('') output.write(s) ###### It does look strange that the file is being open and rewritten over and over, for each line in the file. Are you sure you want to put that in the body of the loop? Best of wishes to you! From javier at ruere.com.ar Thu Mar 3 05:42:33 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Thu Mar 3 05:39:55 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <8584290042.20050301063922@columbus.rr.com> References: <12255145785.20050228223338@columbus.rr.com> <d00ru9$rsv$1@sea.gmane.org> <8584290042.20050301063922@columbus.rr.com> Message-ID: <d0644h$m0i$1@sea.gmane.org> R. Alan Monroe wrote: >>R. Alan Monroe wrote: >> >>>I started writing a program to parse the headers of truetype fonts to >>>examine their family info. But I can't manage to print out the strings >>>without the zero bytes in between each character (they display as a >>>black block labeled 'NUL' in Scite's output pane) >>> >>>I tried: >>> stuff = f.read(nlength) >>> stuff = unicode(stuff, 'utf-8') > > >> If there are embeded 0's in the string, it won't be utf8, it could be >>utf16 or 32. >> Try: >> unicode(stuff, 'utf-16') >>or >> stuff.decode('utf-16') > > >>> print type(stuff), 'stuff', stuff.encode() >>>This prints: >>> >>> <type 'unicode'> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] > > >> I don't understand what you tried to accomplish here. > > > That's evidence of what I failed to accomplish. My expected results > was to print the word "Copyright" and whatever other strings are > present in the font, with no intervening NUL characters. Oh but why print type(stuff) or 'stuff'? > Aha, after some trial and error I see that I'm running into an endian > problem. It's "\x00C" in the file, which needs to be swapped to > "C\x00". I cheated temporarily by just adding 1 to the file pointer > :^) Ah! Endianness! I completely overlook this issue! I have lost several hours of my life to endian problems. Glad to see (on another post) there is an encoding which handles explicitly the endianness or the encoded string. Javier From kent37 at tds.net Thu Mar 3 05:48:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 3 05:48:59 2005 Subject: [Tutor] slow html generation code In-Reply-To: <Pine.LNX.4.44.0503021623350.17948-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503021623350.17948-100000@hkn.eecs.berkeley.edu> Message-ID: <42269736.3060006@tds.net> Danny Yoo wrote: > It also makes it easier to see a possible bug in the code: the last few > lines in the 'for' loop look suspicious: > > ###### > txt = textile(tmp) + '</body></html>' > t = Template(txt) > s = t.safe_substitute(title='Web-siter: %s' % i[:-5]) > output = open(page, 'w') > output.write('') > output.write(s) > ###### > > It does look strange that the file is being open and rewritten over and > over, for each line in the file. Are you sure you want to put that in the > body of the loop? You are also passing the text through textile / Template / safe_substitute repeatedly. You probably want to accumulate all the text, process it once and write it to the file. Kent From gwyn.evans at gmail.com Thu Mar 3 12:08:59 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Thu Mar 3 12:09:46 2005 Subject: [Tutor] Re: Threaded persistance? In-Reply-To: <c0312f5d05030213156fca657b@mail.gmail.com> References: <c0312f5d050302123433eb084e@mail.gmail.com> <c0312f5d05030213156fca657b@mail.gmail.com> Message-ID: <c0312f5d050303030835102733@mail.gmail.com> On Wed, 2 Mar 2005 21:15:50 +0000, Gwyn Evans <gwyn.evans@gmail.com> wrote: > On Wed, 2 Mar 2005 20:34:18 +0000, Gwyn Evans <gwyn.evans@gmail.com> wrote: > > I had a look at using ZODB but hit problems when trying to have two > > connections to the same FileStorage DB, but a second look at things > > suggested that dbm might well do what I need, if I ensure only one > > thread at a time can access it. > > When I found I had the same sort of issue with dbm I had a closer > look and realised that my test code was tidying up too quickly and > closing the DB before the test had actually finished, so it looks as > if ZODB's still in the picture! I've put the code I've come up with at http://www.javaguy.co.uk/Python/TestCEH.html but as I'm new to Python, I'd appreciate any comments, if anyone have time to take a look. /Gwyn From kent37 at tds.net Thu Mar 3 12:50:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 3 12:50:28 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42255A78.6040909@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> <42255A78.6040909@fastmail.fm> Message-ID: <4226F9FF.4020008@tds.net> Bill Kranec wrote: > Hi Kent, >> - The above code depends on roundlist which is not even defined >> anywhere in the module (just shown in the comment). This suggests >> again that the init code from the comment should be part of >> Tournament, and roundlist should be an attribute of Tournament. For a >> class to depend on some external variable is bad design and will break >> if the client code is in a different module from the class code >> (roundlist will be in a different namespace than Tournament). > > > I have always been uneasy about this, but I wanted to be able to define > multiple tournament objects off of the same roundlist, to avoid > generating the list every time a new object is created. I think what I > really want to do is have a separate Round class, from which Tournament > inherits the list of rounds. I have started to implement something like > this in my most recent version, but haven't finished it yet. ( I need > to understand class inheritance better. ) Composition is a better solution than inheritance. You can have a separate Round class and pass an instance of Round to the constructor for Tournament. Tournament can save the instance and refer to it as needed. > >> - Tournament.next() doesn't return a value, it prints it directly. It >> should return self.key or str( self.key ) > > > Does the next() call in an iterator object need to return a value, and > if so, why? ( My reasoning was that next() only needs to increment the > iterator. ) To be an iterator it needs to return a value. This is the value that will be assigned to the loop variable. For example, this class looks like an iterator but it doesn't return any value from next(): class not_an_iterator: def __init__(self): self.i = 0 def __iter__(self): return self def next(self): if self.i < 5: print 'In next - i =', self.i self.i += 1 else: raise StopIteration If I use the class in a loop, the loop variable doesn't receive any value: for i in not_an_iterator(): print 'In loop - i =', i prints: In next - i = 0 In loop - i = None In next - i = 1 In loop - i = None In next - i = 2 In loop - i = None In next - i = 3 In loop - i = None In next - i = 4 In loop - i = None For the loop variable to get the values from next(), I have to return it: class is_an_iterator: def __init__(self): self.i = 0 def __iter__(self): return self def next(self): if self.i < 5: print 'In next - i =', self.i old_i = self.i self.i += 1 return old_i else: raise StopIteration for i in is_an_iterator(): print 'In loop - i =', i prints: In next - i = 0 In loop - i = 0 In next - i = 1 In loop - i = 1 In next - i = 2 In loop - i = 2 In next - i = 3 In loop - i = 3 In next - i = 4 In loop - i = 4 Incidentally, generator functions make it much easier to do this because they maintain state between calls automatically. I could write is_an_iterator as a generator like this: def is_a_generator(): i = 0 while i < 5: yield i i += 1 for i in is_a_generator(): print 'In loop - i =', i Kent From kent37 at tds.net Thu Mar 3 13:01:33 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 3 13:01:39 2005 Subject: [Tutor] Criticism / Suggestions In-Reply-To: <42255A78.6040909@fastmail.fm> References: <4223DC44.6010506@fastmail.fm> <42247232.1080409@tds.net> <42255A78.6040909@fastmail.fm> Message-ID: <4226FC9D.8020202@tds.net> Bill Kranec wrote: > Hi Kent, > > First off, thank you so much for the suggestions! They have helped > clarify some of the concepts I've been struggling with lately ( mostly > object - related ones ). I have been teaching myself Python in my spare > time for the last few months, and have no previous programming > experience, so any feedback I get really helps me improve as a programmer. > > I have implemented some of the changes you talked about, and posted an > updated version of my program here: > > http://rafb.net/paste/results/SicsjJ23.html > > I hope this new version is a bit better, and that my answers to your > questions help you understand what I'm doing. OK, some comments on the code. - I would make checkTeammates() and checkOpponents() return a boolean value rather than raising an exception. Then next() would have code like if self.checkTeammates( self.flattened ) and self.checkOpponents( self.flattened ): # add the round to the tournament else: # handle a bad round - You are (ab)using the iterator protocol essentially to implement a while loop. I would rename next() to something like makeTournament() and put the code in a loop like while len(self.rounds) < 11: ... You can return the final tournament if you want or just have the output from makeTournament() be the only result. - Instead of stdout.write( str( self.key ) + '\n' ) just use print self.key BTW what is magic about 113400? Kent From mark.kels at gmail.com Thu Mar 3 15:04:28 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 3 15:04:33 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <20050302224811.80682.qmail@web53804.mail.yahoo.com> References: <c2259253050302113555cab32f@mail.gmail.com> <20050302224811.80682.qmail@web53804.mail.yahoo.com> Message-ID: <c22592530503030604595c9574@mail.gmail.com> On Wed, 2 Mar 2005 14:48:11 -0800 (PST), Shitiz Bansal <shitizb@yahoo.com> wrote: > The thread finishes when: > 1.The run method finishes. > 2.In case of the loop- you may - > > >>> import threading > >>> class abc(threading.Thread): > def __init__(self): > threading.Thread.__init__(self) > self.cont_flag=1 > def run(self): > while self.cont_flag: > pass > > >>> abcd=abc() > >>> abcd > <abc(Thread-1, initial)> > >>> abcd.start() > >>> abcd > <abc(Thread-1, started)> > >>> abcd.cont_flag=0 > >>> abcd > <abc(Thread-1, stopped)> But for some reason it keeps working after its job is done in my app... Here is the class: (the app itself got some Entrys to get the input and a Button to start the go() and stop() functions) class scan(threading.Thread): def _init_(self): threading.thread._init_(self) def scanner(self): self.open_counter=0 self.flag='scan' try: host=host_e.get() start_port=int(start_port_e.get()) end_port=int(end_port_e.get()) except ValueError: tkMessageBox.showerror("Bad input","You must enter a vaild host IP and port numbers.") pass else: start.config(text="Stop",command=stop) root.update() result.insert(END,"Scanning "+str(host)+"...\n\n") root.update() while start_port<=end_port and self.flag=='scan': self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sk.settimeout(0.01) try: self.sk.connect((host,start_port)) except: pass else: result.insert(END,str(start_port)+"\n") root.update() self.open_counter=self.open_counter+1 self.sk.close() start_port=start_port+1 if self.flag=='scan': result.insert(END,"\nDone !!\nFound "+str(self.open_counter)+" opened ports") root.update() start.config(text="Scan",command=go) root.update() elif self.flag=='stop': result.insert(END,"\n Scan stopped.") start.config(text="Scan",command=go) root.update() app=scan() Here is the go() function, which starts the thread: def go(): app.start() app.scanner() And here is the stop() function that should end the thread and the scan (and for some reason it ends only the scan loop): def stop(): app.flag='stop' You got any Idea whats wrong here ?? Thanks allot. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From gwyn.evans at gmail.com Thu Mar 3 15:31:55 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Thu Mar 3 15:32:17 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c22592530503030604595c9574@mail.gmail.com> References: <c2259253050302113555cab32f@mail.gmail.com> <20050302224811.80682.qmail@web53804.mail.yahoo.com> <c22592530503030604595c9574@mail.gmail.com> Message-ID: <c0312f5d050303063153d0f816@mail.gmail.com> On Thu, 3 Mar 2005 16:04:28 +0200, Mark Kels <mark.kels@gmail.com> wrote: > On Wed, 2 Mar 2005 14:48:11 -0800 (PST), Shitiz Bansal > <shitizb@yahoo.com> wrote: > > The thread finishes when: > > 1.The run method finishes. > > 2.In case of the loop- you may - > > > > >>> import threading > > >>> class abc(threading.Thread): > > def __init__(self): > > threading.Thread.__init__(self) > > self.cont_flag=1 > > def run(self): > > while self.cont_flag: > > pass > > > > >>> abcd=abc() > > >>> abcd > > <abc(Thread-1, initial)> > > >>> abcd.start() > > >>> abcd > > <abc(Thread-1, started)> > > >>> abcd.cont_flag=0 > > >>> abcd > > <abc(Thread-1, stopped)> > > But for some reason it keeps working after its job is done in my app... > Here is the class: > (the app itself got some Entrys to get the input and a Button to start > the go() and stop() functions) > > class scan(threading.Thread): > def _init_(self): > threading.thread._init_(self) > def scanner(self): > self.open_counter=0 > self.flag='scan' > try: > host=host_e.get() > start_port=int(start_port_e.get()) > end_port=int(end_port_e.get()) > except ValueError: > tkMessageBox.showerror("Bad input","You must enter a vaild > host IP and port numbers.") > pass > else: > start.config(text="Stop",command=stop) > root.update() > result.insert(END,"Scanning "+str(host)+"...\n\n") > root.update() > while start_port<=end_port and self.flag=='scan': > self.sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM) > self.sk.settimeout(0.01) > try: > self.sk.connect((host,start_port)) > except: > pass > else: > result.insert(END,str(start_port)+"\n") > root.update() > self.open_counter=self.open_counter+1 > self.sk.close() > start_port=start_port+1 > if self.flag=='scan': > result.insert(END,"\nDone !!\nFound > "+str(self.open_counter)+" opened ports") > root.update() > start.config(text="Scan",command=go) > root.update() > elif self.flag=='stop': > result.insert(END,"\n Scan stopped.") > start.config(text="Scan",command=go) > root.update() > app=scan() > > Here is the go() function, which starts the thread: > def go(): > app.start() > app.scanner() > > And here is the stop() function that should end the thread and the > scan (and for some reason it ends only the scan loop): > def stop(): > app.flag='stop' > > You got any Idea whats wrong here ?? Hi, The one thing that stands out is that when you subclass Thread as you do, you need to override the 'run' method, which will get called as a result of you calling 'start()'. You're calling start(), but you've not got a run method, so the new thread doesn't call your code. Instead you've got your own call to 'scanner()', that is running under the main thread. Rename 'scanner()' to 'run()', remove the call to 'scanner()' and see how that looks. /Gwyn From mark.kels at gmail.com Thu Mar 3 16:53:11 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 3 16:53:15 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c0312f5d050303063153d0f816@mail.gmail.com> References: <c2259253050302113555cab32f@mail.gmail.com> <20050302224811.80682.qmail@web53804.mail.yahoo.com> <c22592530503030604595c9574@mail.gmail.com> <c0312f5d050303063153d0f816@mail.gmail.com> Message-ID: <c22592530503030753354e079f@mail.gmail.com> On Thu, 3 Mar 2005 14:31:55 +0000, Gwyn Evans <gwyn.evans@gmail.com> wrote: > Hi, > The one thing that stands out is that when you subclass Thread as > you do, you need to override the 'run' method, which will get called > as a result of you calling 'start()'. > You're calling start(), but you've not got a run method, so the new > thread doesn't call your code. Instead you've got your own call to > 'scanner()', that is running under the main thread. > > Rename 'scanner()' to 'run()', remove the call to 'scanner()' and > see how that looks. It looks the same, but with 1 line less... The thread is still working after the loop is done, so after I stop the scan I cant start another one. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From gwyn.evans at gmail.com Thu Mar 3 17:36:05 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Thu Mar 3 17:36:40 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c22592530503030753354e079f@mail.gmail.com> References: <c2259253050302113555cab32f@mail.gmail.com> <20050302224811.80682.qmail@web53804.mail.yahoo.com> <c22592530503030604595c9574@mail.gmail.com> <c0312f5d050303063153d0f816@mail.gmail.com> <c22592530503030753354e079f@mail.gmail.com> Message-ID: <c0312f5d05030308367075eec0@mail.gmail.com> On Thu, 3 Mar 2005 17:53:11 +0200, Mark Kels <mark.kels@gmail.com> wrote: > On Thu, 3 Mar 2005 14:31:55 +0000, Gwyn Evans <gwyn.evans@gmail.com> wrote: > > Hi, > > The one thing that stands out is that when you subclass Thread as > > you do, you need to override the 'run' method, which will get called > > as a result of you calling 'start()'. > > You're calling start(), but you've not got a run method, so the new > > thread doesn't call your code. Instead you've got your own call to > > 'scanner()', that is running under the main thread. > > > > Rename 'scanner()' to 'run()', remove the call to 'scanner()' and > > see how that looks. > > It looks the same, but with 1 line less... > The thread is still working after the loop is done, so after I stop > the scan I cant start another one. Hmm, at this point I'd be either firing up a debugger or adding a print/msg box to check that it's exiting run() as expected... How are you trying to start another scan? You'd have to create a new instance, you can't just call app.start() again. /Gwyn From mark.kels at gmail.com Thu Mar 3 19:02:05 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 3 19:02:10 2005 Subject: [Tutor] How to use threads ? In-Reply-To: <c0312f5d05030308367075eec0@mail.gmail.com> References: <c2259253050302113555cab32f@mail.gmail.com> <20050302224811.80682.qmail@web53804.mail.yahoo.com> <c22592530503030604595c9574@mail.gmail.com> <c0312f5d050303063153d0f816@mail.gmail.com> <c22592530503030753354e079f@mail.gmail.com> <c0312f5d05030308367075eec0@mail.gmail.com> Message-ID: <c225925305030310024eb430f2@mail.gmail.com> On Thu, 3 Mar 2005 16:36:05 +0000, Gwyn Evans <gwyn.evans@gmail.com> wrote: > How are you trying to start another scan? You'd have to create a > new instance, you can't just call app.start() again. Thanks allot !! This is exactly what I was doing wrong. Now it works :) -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From amonroe at columbus.rr.com Fri Mar 4 00:10:37 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Mar 4 00:11:21 2005 Subject: [Tutor] Re: How to read unicode strings from a binary file and display them as plain ascii? In-Reply-To: <d0644h$m0i$1@sea.gmane.org> References: <12255145785.20050228223338@columbus.rr.com> <d00ru9$rsv$1@sea.gmane.org> <8584290042.20050301063922@columbus.rr.com> <d0644h$m0i$1@sea.gmane.org> Message-ID: <152298565474.20050303181037@columbus.rr.com> >>>> print type(stuff), 'stuff', stuff.encode() >>>>This prints: >>>> >>>> <type 'unicode'> stuff [NUL]C[NUL]o[NUL]p[NUL]y[NUL]r[NUL]i[NUL]g[NUL] >> >> >>> I don't understand what you tried to accomplish here. >> >> >> That's evidence of what I failed to accomplish. My expected results >> was to print the word "Copyright" and whatever other strings are >> present in the font, with no intervening NUL characters. > Oh but why print type(stuff) To make sure it really came back as <type 'unicode'>, as opposed to <type 'str'>. > or 'stuff'? Personal tradition :^) The outcome of the project was this: Firefox would not display bold text correctly when I selected "Futura Lt BT" as my font (it would display a stretched version of the Light font, even though I also had "Futura Bold BT" in my fonts folder). After some googling, I figured out that (if I understand it right) Windows groups plain fonts and bold fonts together based on their internal family name, which turned out to be different between the two fonts. futural.ttf Font Family name : Futura Lt BT Font Subfamily name : Light futurab.ttf Font Family name : Futura Md BT Font Subfamily name : Bold So as best I can tell, the d*mb*asses that made Word Perfect Office 2002 (pre-loaded on my computer when I bought it) failed to give me the entire font family. Alan From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 07:58:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 07:58:34 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <20050226062509.47947.qmail@web51603.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0503032245380.17769-100000@hkn.eecs.berkeley.edu> [Meta note to other folks on the list: I'm sorry for letting this post through; I was rushing, and I should have been more careful when going through my moderation queue.] On Fri, 25 Feb 2005, liew choon chui wrote: > Here are two question to need some solution. Hi Lieu Choon Chui, I do not want to be rude, but, bluntly speaking, you have to do your own work. Asking us to do it for you is a bit insulting, and I hope you understand you've just made a terrible netiquette blunder. Your homework is yours to solve. Please read: http://www.catb.org/~esr/faqs/smart-questions.html If you have questions about Python, we will be happy to help you. But don't dump homework questions on us and expect a useful response. From cyresse at gmail.com Fri Mar 4 08:59:33 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Mar 4 08:59:36 2005 Subject: [Tutor] Programming challenge (C++ and Python) In-Reply-To: <20050201082017.44023.qmail@web61002.mail.yahoo.com> References: <20050201082017.44023.qmail@web61002.mail.yahoo.com> Message-ID: <f2ff2d050303235926876816@mail.gmail.com> ??? Why am I getting this one as new again? On Tue, 1 Feb 2005 00:20:17 -0800 (PST), Ali Polatel <alipolatel@yahoo.com> wrote: > Dear Python friends, > I need a favor.I play chess at a chess server with the name > ICC(www.chessclub.com). I want to write a plugin for their interface using > Python. > I don't have any idea about how to write a plugin but I found out that > the server administrator has written a Plugin Development Kit in C++ for > those who wish to write plugins for the interface.I don't know C++ so I > cannot convert this kit into python scripts.Can anyone do this for me? or > can anyone examine those scripts and tell me a way how to write those with > python?The development kit is avaliable at the site > ftp://ftp.chessclub.com/pub/icc/interface/blitzin2/plugins/ > under the name PluginDevkit.zip > Any kind of help is appreciated. > Regards, > Ali Polatel > > ________________________________ > Do you Yahoo!? > Yahoo! Search presents - Jib Jab's 'Second Term' > > > _______________________________________________ > 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. From davholla2002 at yahoo.co.uk Fri Mar 4 10:26:40 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Mar 4 10:26:43 2005 Subject: [Tutor] Make a .exe Message-ID: <20050304092641.55708.qmail@web25406.mail.ukl.yahoo.com> I have a game I wrote using python and pygame that I am trying to change into a .exe I created the script setup.py which has this code :- setup.py from distutils.core import setup import py2exe setup(console=["Gamename.py"]) In a dos prompt with all the files there I ran :- python setup.py py2exe It Completed with these errors :- The following modules appear to be missing {'AppKit', 'Foundation', 'objc'] but the game.exe was created However when I try to run it I get &nb sp; File "livewires3\games.pyc", line 585 in init_text File "livewires3\games.pyc", line 585 in init_text Fatal Python error: <pygame parachute> Segmentation Fault. Livewires3 is a modified version of a pygame wrapper. http://www.livewires.org.uk/python/ is where the original is. The book I used to learn python "python programming for the absolute beginner" has a modified version of this with some functionality added and taken away. I modified the wrapper so that has the functionality of both wrappers. Any ideas about how to fix it ? Thanks in advance David Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050304/990ecfa0/attachment.html From gwyn.evans at gmail.com Fri Mar 4 10:37:21 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Fri Mar 4 10:37:24 2005 Subject: [Tutor] Newbie question. In-Reply-To: <001601c5050c$de90dfb0$0408a8c0@Client98> References: <001601c5050c$de90dfb0$0408a8c0@Client98> Message-ID: <c0312f5d050304013766573a6a@mail.gmail.com> On Fri, 28 Jan 2005 09:42:07 +0200, Adriaan Louw <adriaan@kredcorgroup.com> wrote: > I want to learn python as quick as possible, for web programming at first, > and applications later on. Any leads? Hi, I'd start with the basic python tutorials, then have a look at something like CherryPy (http://www.cherrypy.org/) or Quixote (http://www.quixote.ca/) for the initial web stuff - there are others, too. Try & read around each a bit, e.g. web site/mailing lists, then download & give ones you fancy a try. > I have an xp windows and ms office machine. (I'm considering linux, but it's > a bit daunting?) No need to in most cases. > How do I run python scripts? Nothing happens when I double-click the > filename, in IDLE I only get the code, and not what it does. Command line is one way. Make sure your PATH (My Computer/Propeties/Advanced/Environment, or similar) has the Python folder in it then try "python <script.py>" You can also try Explorer/Tools/Folder Options/File Types/.PY to associate .py files with the python.exe file. Gwyn From gwyn.evans at gmail.com Fri Mar 4 10:43:08 2005 From: gwyn.evans at gmail.com (Gwyn Evans) Date: Fri Mar 4 10:43:11 2005 Subject: [Tutor] Proxy In-Reply-To: <20050130002329.4200.qmail@web61003.mail.yahoo.com> References: <20050130002329.4200.qmail@web61003.mail.yahoo.com> Message-ID: <c0312f5d05030401432359abba@mail.gmail.com> On Sat, 29 Jan 2005 16:23:29 -0800 (PST), Ali Polatel <alipolatel@yahoo.com> wrote: > is it possible to connect to somewhere through a proxy while using sockets > module of Python to connect? If yes can you show me some basic examples? Yes, but not auto-magically. If you want to stay at the sockets level, you'll have to handle all the proxy interaction yourself. I'd suggest instead looking at the urllib2 module, as I believe that you can use that (via a Request object?) to handle the proxy for you. /Gwyn From maxnoel_fr at yahoo.fr Fri Mar 4 11:11:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Mar 4 11:11:55 2005 Subject: [Tutor] Make a .exe In-Reply-To: <20050304092641.55708.qmail@web25406.mail.ukl.yahoo.com> References: <20050304092641.55708.qmail@web25406.mail.ukl.yahoo.com> Message-ID: <1c69aad8c67d4430e7ae3e410e42ed61@yahoo.fr> On Mar 4, 2005, at 09:26, David Holland wrote: > It Completed with these errors :- > The following modules appear to be missing {'AppKit', > 'Foundation', 'objc'] Now that's really weird. AppKit and Foundation are Mac OS X frameworks, and objc stands for Objective-C, the language in which they're written and which you're supposed to use to develop applications that use them. However, since you're on a Windows box, I have no idea why Python is trying to involve them. -- 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?" From kent37 at tds.net Fri Mar 4 12:16:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 4 12:16:43 2005 Subject: [Tutor] Newbie question. In-Reply-To: <001601c5050c$de90dfb0$0408a8c0@Client98> References: <001601c5050c$de90dfb0$0408a8c0@Client98> Message-ID: <42284398.4060402@tds.net> Adriaan Louw wrote: > I want to learn python as quick as possible, for web programming at > first, and applications later on. Any leads? There are many tutorials available, see http://www.python.org/doc/Intros.html for one list. > > I have an xp windows and ms office machine. (I'm considering linux, but > it's a bit daunting?) > > How do I run python scripts? Nothing happens when I double-click the > filename, in IDLE I only get the code, and not what it does. You can run the program in IDLE using Run / Run Module (F5). > I know that cgi-scripts must be called from html. I want to to use a > python server for testing. Which is thebest, and how? There are many options for web programming, one list is here: http://www.python.org/moin/WebProgramming In addition to CherryPy and Quixote, Snakelets is a complete web solution that is intended to be easy to learn. Twisted and Zope are perhaps the most comprehensive solutions. Kent From davholla2002 at yahoo.co.uk Fri Mar 4 13:12:02 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Mar 4 13:12:03 2005 Subject: [Tutor] make an .exe In-Reply-To: <20050304110113.E3BD81E4005@bag.python.org> Message-ID: <20050304121202.16666.qmail@web25405.mail.ukl.yahoo.com> Noel Thanks for that info, I did do a search for that but I could not find anything useful Message: 3 Date: Fri, 4 Mar 2005 10:11:51 +0000 From: Max Noel Subject: Re: [Tutor] Make a .exe To: David Holland Cc: tutor@python.org Message-ID: <1c69aad8c67d4430e7ae3e410e42ed61@yahoo.fr> Content-Type: text/plain; charset=US-ASCII; format=flowed On Mar 4, 2005, at 09:26, David Holland wrote: > It Completed with these errors :- > The following modules appear to be missing {'AppKit', > 'Foundation', 'objc'] Now that's really weird. AppKit and Foundation are Mac OS X frameworks, and objc stands for Objective-C, the language in which they're written and which you're supposed to use to develop applications that use them. However, since you're on a Windows box, I have no idea why Python is trying to involve them. -- 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 End of Tutor Digest, Vol 13, Issue 13 ************************************* Send instant messages to your online friends http://uk.messenger.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050304/282cfe49/attachment.htm From mhansen at cso.atmel.com Fri Mar 4 15:00:03 2005 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Mar 4 15:00:03 2005 Subject: [Tutor] Re: Newbie question. In-Reply-To: <20050304110113.4F10E1E4016@bag.python.org> References: <20050304110113.4F10E1E4016@bag.python.org> Message-ID: <422869E3.20702@cso.atmel.com> > Subject: > Re: [Tutor] Newbie question. > From: > Gwyn Evans <gwyn.evans@gmail.com> > Date: > Fri, 4 Mar 2005 09:37:21 +0000 > To: > tutor@python.org > > To: > tutor@python.org > > >On Fri, 28 Jan 2005 09:42:07 +0200, Adriaan Louw ><adriaan@kredcorgroup.com> wrote: > > >>I want to learn python as quick as possible, for web programming at first, >>and applications later on. Any leads? >> >> > >Hi, > I'd start with the basic python tutorials, then have a look at >something like CherryPy (http://www.cherrypy.org/) or Quixote >(http://www.quixote.ca/) for the initial web stuff - there are others, >too. Try & read around each a bit, e.g. web site/mailing lists, then >download & give ones you fancy a try. > > > I would politely disagree here. You need to walk before you can run. If you haven't done _any_ web programming before, it's probably best to do a small web app using just python's cgi module. I would think that CherryPy and Quixote are complex web tools/frameworks that I wouldn't recommend to someone new to web programming until they got their feet wet doing some basic web programming. After that, then explore more advanced web programming with CherryPy or Quixote. If you have done some basic web programming in other languages, then ignore this message. Mike From python.programming at gmail.com Fri Mar 4 16:43:46 2005 From: python.programming at gmail.com (Kevin) Date: Fri Mar 4 16:43:51 2005 Subject: [Tutor] (no subject) Message-ID: <d082fff805030407435e6ae83c@mail.gmail.com> Hello all. I have just completed my very first python program just a simple number guessing. I would like for someone to try it out if they could and let me know how I did with it and where I could have improved apon it. There are t files main.py and defs.py Thanks ############################################################################## #!/usr/bin/python #main.py ########################### from defs import * import sys ########################### choice() #Lets call the main menu up for the user #This is used to ask if you would like to keep playing# while 1: play = raw_input("What is your choice? ") #Aks use to enter a choice from the menu if play == '3': #If user picks 3 print "\nHave a nice day!\n" #Tell them to have a nice day sys.exit() #Then exit the entire thing elif play == '2': #If user picks 2 instruct() #Then lets call the instructions function elif play == '1': #If user picks 1 game() #Then lets call the game function for the user to play elif play == '': #This is used is the menu leaves the screen so the user can get it back choice() #Bring back the menu else: print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" #Let the user know that they can only pick 1, 2, 3 or just hit enter and nothing else. ########################################################################### #defs.py ######### import random import sys ####################################################### #This is not used in the game yet def yesno(question): """Asks the use a yes or no question""" answer = None while answer not in ('y','ye','yes','n','no'): answer = raw_input(question).lower() if answer not in ('y','ye','yes','n','no'): print "Please enter Y or N" return answer ######################################################## #This is the guessing game# def game(): """This is the main part of the guessing game""" tries = 5 #Set the number of tries to 5 guess = random.randrange(2)+1 #Computer picks a number from 1 to 20 while 1: try: answer = int(raw_input("What is your guess? ")) #Ask the user to guess the number if answer != guess: #Check to see if answer is not equal to guessed number tries -= 1 #if answer is wrong reduce the number of tries by 1 print "Thats not it, you only have %d tries left" %tries #Tell user not right answer if tries == 0: #Check to see if user has run out of tries print "\nYou lost this round!" #If no tries left let the user know raw_input("\n[Hit Enter to Continue]\n") #Wait for user to go back to main menu choice() #Show main menu for user break #Then break out of the loop if answer == guess: #If the answer is equal to the guessed number print "\nCongrats you just Won this round!!" #Tell the user he just one in so many tries raw_input("[Hit Enter to Continue]") #Wait for user to go back to main menu choice() #Show main menu for user break #Break out of the loop except ValueError: #Lets make sure that the user is only typeing in numbers and nothing else print "\nYou can only use numbers\n" #Let user know they can only use numbers #This is the main menu for the game def choice(): """The main menu of the game""" print """ ######################################## # # # NUMBER GUESSING GAME # # # # - Created by Kevin J # # - python.programming@gmail.com # # ------------------------------------ # # 1 - Play # # 2 - instructions # # 3 - Quit # ########################################\n""" #This is the instuctions on how to play the game that can be called from the main menu def instruct(): """Instructions on how to play the guessing game""" print"""\n HOW TO PLAY THE NUMBER GUESSING GAME ######################################################################## # To play this game all you need to do is guess a number from 1 to 20. # # You will only have 5 tries to beat the game. Once you have beat the # # game or you have used up all of your 5 tries you will be sent back # # to the main screen were you can quit or start over again. # ######################################################################## [HIT ENTER FOR MAIN MENU]\n""" From bvande at po-box.mcgill.ca Fri Mar 4 18:14:28 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Mar 4 18:16:08 2005 Subject: [Tutor] (no subject) In-Reply-To: <d082fff805030407435e6ae83c@mail.gmail.com> References: <d082fff805030407435e6ae83c@mail.gmail.com> Message-ID: <42289774.6010607@po-box.mcgill.ca> Kevin said unto the world upon 2005-03-04 10:43: > Hello all. I have just completed my very first python program just a > simple number guessing. I would like for someone to try it out if they > could and let me know how I did with it and where I could have > improved apon it. There are t files main.py and defs.py > > Thanks Hi Kevin, Though I am a learner, too, I have a few comments. They are more about style than substance. 1) A lot of your code comments get in the way of my reading and easily understanding the code. Consider: .# leading `.'s to foil google groups and other whitespace stripping readers .if play == '3': #If user picks 3 . print "\nHave a nice day!\n" #Tell them to have a nice day . sys.exit() #Then exit the entire thing I think this would be much easier to read if it were like: .if play == '3': # If user picks 3 . print "\nHave a nice day!\n" # Tell them to have a nice day . sys.exit() # Then exit the entire thing (Note that some people hate the comments along the side and would prefer them the precede the line(s) they comment on. I like the 2 column approach, but that's just one duffer's view.) But, even better would be: .if play == '3': . print "\nHave a nice day!\n" . sys.exit() Your comments are close to the canonical example of 'bad comments': count += 1 # increment count by 1 Comments like this add nothing except squiggles to read on the screen or page. They just repeat the code; so, instead of helping, they are just noise. Comments are good for tricky bits, to explain just why some non-obvious chunk of code is there, or to remind the reader (who could well be you) why some particular approach was taken. (Neatness counts ;-) 2) Whitespace is a good thing. Python needs it horizontally, but you can (and, IMHO, should) employ vertical whitespace to chunk up the code. Your code had this chunk: . if play == '3': #If user picks 3 . print "\nHave a nice day!\n" #Tell them to have a nice day . sys.exit() #Then exit the entire thing . elif play == '2': #If user picks 2 . instruct() #Then lets call the instructions function . elif play == '1': #If user picks 1 . game() #Then lets call the game function for the user to play . elif play == '': #This is used is the menu leaves the screen so the user can get it back . choice() #Bring back the menu . else: . print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Try reading that and then this: . if play == '3': . print "\nHave a nice day!\n" . sys.exit() . . elif play == '2': . instruct() . . elif play == '1': . game() . . elif play == '': # I might have put a comment here but . choice() # the else clause below explains it. . . else: . print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Which one is easier to read? :-) The separation between blocks doesn't matter too much when the blocks are short, but I still like it. Different strokes, though. But, if each block had, say 4 or 5 lines, it would be much easier for me to parse with the separation. 3) I've come to like informative dosctrings a lot. When you start using tools like pydoc on your own code, you will be glad you used them. (Plus, they cut down on the need for inline comments.) and, 4) I'd make the yesno() function do a bit more work. So, combining these two points, where you have: .def yesno(question): . """Asks the use a yes or no question""" . answer = None . while answer not in ('y','ye','yes','n','no'): . answer = raw_input(question).lower() . if answer not in ('y','ye','yes','n','no'): . print "Please enter Y or N" . return answer I have a utility function: def yes_or_no(question): . '''Asks the user the question; returns True for yes, False for no. . . question is used to prompt the user for raw_input. That input is . put in lower case and compared to the values ['y', 'yes', 'n', . 'no']. If it matches a `yes' value, True is returned; if it . matches a `no' value False is returned. If it matches none of . these values, a report of what was entered and of valid inputs . is printed and the user is reprompted until an acceptable value . is entered. . ''' . response = raw_input(question) . while True: . . lresp = response.lower() . . if lresp == 'y' or lresp == 'yes': . # adjust matching values to your tastes . return True . if lresp == 'n' or lresp == 'no': . return False . . response = raw_input(''' . You entered: %s . Valid inputs are `n', 'no', `y', and `yes' (any case). . Please try again. . %s . ''' %(response, question)) My code is a lot longer, but 1) it does a little bit more, and 2) it has a much more useful docstring. If you wanted to reuse your function elsewhere (and you will), you might have to actually look at the code to see how it works. Mine is much easier to use with help() or the web browser version of pydoc. 5) I don't see why you broke your program up the way you did. I would have everything but the yesno() in one file. The yesno I would put in something like the inpututils.py file I have where I've got other standard user input routines, too. (Examples would be code to ask for a number between n and m, any number, a file path, etc.) Anyway, I hope that helps some and that the more experienced list members will swoop in (they always do :-) to fix anything I said that is goofy. Best, Brian vdB > > ############################################################################## > > #!/usr/bin/python > #main.py > ########################### > from defs import * > import sys > ########################### > > choice() #Lets call the main menu up for the user > #This is used to ask if you would like to keep playing# > while 1: > play = raw_input("What is your choice? ") #Aks use to enter a choice > from the menu > if play == '3': #If user picks 3 > print "\nHave a nice day!\n" #Tell them to have a nice day > sys.exit() #Then exit the entire thing > elif play == '2': #If user picks 2 > instruct() #Then lets call the instructions function > elif play == '1': #If user picks 1 > game() #Then lets call the game function for the user to play > elif play == '': #This is used is the menu leaves the screen so the > user can get it back > choice() #Bring back the menu > else: > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" > #Let the user know that they can only pick 1, 2, 3 or just hit enter > and nothing else. > > ########################################################################### > #defs.py > ######### > import random > import sys > ####################################################### > #This is not used in the game yet > def yesno(question): > """Asks the use a yes or no question""" > answer = None > while answer not in ('y','ye','yes','n','no'): > answer = raw_input(question).lower() > if answer not in ('y','ye','yes','n','no'): > print "Please enter Y or N" > return answer > ######################################################## > #This is the guessing game# > def game(): > """This is the main part of the guessing game""" > tries = 5 #Set the number of tries to 5 > guess = random.randrange(2)+1 #Computer picks a number from 1 to 20 > while 1: > try: > answer = int(raw_input("What is your guess? ")) #Ask the user to > guess the number > if answer != guess: #Check to see if answer is not equal to guessed number > tries -= 1 #if answer is wrong reduce the number of tries by 1 > print "Thats not it, you only have %d tries left" %tries #Tell > user not right answer > if tries == 0: #Check to see if user has run out of tries > print "\nYou lost this round!" #If no tries left let the user know > raw_input("\n[Hit Enter to Continue]\n") #Wait for user to go > back to main menu > choice() #Show main menu for user > break #Then break out of the loop > if answer == guess: #If the answer is equal to the guessed number > print "\nCongrats you just Won this round!!" #Tell the user he > just one in so many tries > raw_input("[Hit Enter to Continue]") #Wait for user to go back to main menu > choice() #Show main menu for user > break #Break out of the loop > except ValueError: #Lets make sure that the user is only typeing in > numbers and nothing else > print "\nYou can only use numbers\n" #Let user know they can only > use numbers > > #This is the main menu for the game > def choice(): > """The main menu of the game""" > print """ > ######################################## > # # > # NUMBER GUESSING GAME # > # # > # - Created by Kevin J # > # - python.programming@gmail.com # > # ------------------------------------ # > # 1 - Play # > # 2 - instructions # > # 3 - Quit # > ########################################\n""" > > #This is the instuctions on how to play the game that can be called > from the main menu > def instruct(): > """Instructions on how to play the > guessing game""" > print"""\n > HOW TO PLAY THE NUMBER GUESSING GAME > ######################################################################## > # To play this game all you need to do is guess a number from 1 to 20. # > # You will only have 5 tries to beat the game. Once you have beat the # > # game or you have used up all of your 5 tries you will be sent back # > # to the main screen were you can quit or start over again. # > ######################################################################## > [HIT ENTER FOR MAIN MENU]\n""" > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From shitizb at yahoo.com Fri Mar 4 18:19:41 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Fri Mar 4 18:19:44 2005 Subject: [Tutor] Linked List Message-ID: <20050304171941.53337.qmail@web53806.mail.yahoo.com> Hi, Any body has any idea on how to implement a linked list in python? Ordinary python lists are not quite the same. what i need is a list i can traverse through sequentially without bothering about the indices, as another process is continuously editing this list, by inserting and deleting elements even as the list is being traversed. Shitiz __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From project5 at redrival.net Fri Mar 4 19:17:06 2005 From: project5 at redrival.net (Andrei) Date: Fri Mar 4 19:24:52 2005 Subject: [Tutor] Re: Linked List References: <20050304171941.53337.qmail@web53806.mail.yahoo.com> Message-ID: <drasq4fvhfcf$.fu6bnjqqweku.dlg@40tude.net> Shitiz Bansal wrote on Fri, 4 Mar 2005 09:19:41 -0800 (PST): > Any body has any idea on how to implement a linked > list in python? Perhaps like this: >>> class node(object): ... def __init__(self, item, next=None): ... self.item = item ... self.next = next >>> a = node('item a') >>> b = node(3) >>> c = node((3,4)) >>> d = node('last item') >>> a.next = b >>> b.next = c >>> c.next = d >>> mynode = a >>> while mynode: ... print mynode.item ... mynode = mynode.next item a 3 (3, 4) last item -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From chelan.farsight at gmail.com Fri Mar 4 19:37:58 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Fri Mar 4 19:38:54 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <Pine.LNX.4.44.0503032245380.17769-100000@hkn.eecs.berkeley.edu> References: <20050226062509.47947.qmail@web51603.mail.yahoo.com> <Pine.LNX.4.44.0503032245380.17769-100000@hkn.eecs.berkeley.edu> Message-ID: <661da26c05030410371eba7b4b@mail.gmail.com> Okay this is a real question I have and I am not trying to defend the actions of Mr. Chui. I simply wanted to make sure that I have joined the right list. Are we allowed to ask total n00b questions on this list? If not what level of understanding is presumed before someone should post a question? Again, please do not misunderstand, I have no qualms with *refusing* to do someone's homework for them. I just want to make sure that total newbies are welcome here. If not then a reccomendation for another list would be greatly appreciated. Thanks for your patience and help, chelan On Thu, 3 Mar 2005 22:58:31 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > [Meta note to other folks on the list: I'm sorry for letting this post > through; I was rushing, and I should have been more careful when going > through my moderation queue.] > > > On Fri, 25 Feb 2005, liew choon chui wrote: > > > Here are two question to need some solution. > > Hi Lieu Choon Chui, > > I do not want to be rude, but, bluntly speaking, you have to do your own > work. Asking us to do it for you is a bit insulting, and I hope you > understand you've just made a terrible netiquette blunder. Your homework > is yours to solve. > > Please read: > > http://www.catb.org/~esr/faqs/smart-questions.html > > If you have questions about Python, we will be happy to help you. But > don't dump homework questions on us and expect a useful response. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 19:45:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 19:45:58 2005 Subject: [Tutor] Programming challenge (C++ and Python) In-Reply-To: <f2ff2d050303235926876816@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503041043250.28602-100000@hkn.eecs.berkeley.edu> On Fri, 4 Mar 2005, Liam Clarke wrote: > ??? Why am I getting this one as new again? Hi Liam, This one is my fault. As a mailing list administrator, I have to go through stuff that's sitting in a moderation queue. I'd been a little derelict in my responsibility lately, and hadn't looked at the queue since January. I looked at it yesterday and started allowing some messages to come in , but I was careless enough not to notice some the questions that were already posted to this list from back in January. I apologize for this; I'll try to do a less careless job next time. From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 19:49:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 19:49:44 2005 Subject: [Tutor] Re: Linked List In-Reply-To: <drasq4fvhfcf$.fu6bnjqqweku.dlg@40tude.net> Message-ID: <Pine.LNX.4.44.0503041046430.28602-100000@hkn.eecs.berkeley.edu> On Fri, 4 Mar 2005, Andrei wrote: > Shitiz Bansal wrote on Fri, 4 Mar 2005 09:19:41 -0800 (PST): > > > Any body has any idea on how to implement a linked list in python? There's a chapter on Linked Lists in "How to Think Like a Computer Scientist": http://www.ibiblio.org/obp/thinkCSpy/chap17.htm You might also enjoy this post from a few years back: http://mail.python.org/pipermail/tutor/2002-April/014073.html From kent37 at tds.net Fri Mar 4 19:52:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 4 19:52:23 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <661da26c05030410371eba7b4b@mail.gmail.com> References: <20050226062509.47947.qmail@web51603.mail.yahoo.com> <Pine.LNX.4.44.0503032245380.17769-100000@hkn.eecs.berkeley.edu> <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: <4228AE6D.4050609@tds.net> Chelan Farsight wrote: > Okay this is a real question I have and I am not trying to defend the > actions of Mr. Chui. I simply wanted to make sure that I have joined > the right list. Are we allowed to ask total n00b questions on this > list? Yes, this list is specifically for total n00bs and other beginners (and people who like to answer beginners' questions :-) If not what level of understanding is presumed before someone > should post a question? None. A reasonable level of *effort* is appreciated. You will get better results if you try something and ask for help when you get stuck, and if you take the time to write a clear question. > Again, please do not misunderstand, I have no qualms with *refusing* > to do someone's homework for them. I just want to make sure that > total newbies are welcome here. Yes, definitely. Kent From dyoo at hkn.eecs.berkeley.edu Fri Mar 4 20:05:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 4 20:06:05 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503041049420.28602-100000@hkn.eecs.berkeley.edu> On Fri, 4 Mar 2005, Chelan Farsight wrote: > Okay this is a real question I have and I am not trying to defend the > actions of Mr. Chui. I simply wanted to make sure that I have joined > the right list. Are we allowed to ask total n00b questions on this > list? Hi Chelan, Yikes! Newcomer questions are perfectly fine. I'm sorry for the exasperated tone I used in my last message, and will try to explain myself. Let me clarify: if it's obvious that the questioner doesn't even care about the question they are asking --- if someone is just trying to get us to do homework so they can copy and paste it into some word processor --- then I get annoyed. (But I should have posted my rant off-list, so that it didn't disrupt anyone else.) If it looks like the questioner cares about the answer, and is doing other things to learn more about the subject, then that's ok. > If not what level of understanding is presumed before someone should > post a question? Any level of understanding is actually fine. Personally, it's the human intent of the questions that matters to me. Neither of Chui's questions had anything to do with Python. If there's any real requirement about questions, it's that it should at least have something to do with learning how to program in Python. > I just want to make sure that total newbies are welcome here. If not > then a reccomendation for another list would be greatly appreciated. This list is for beginners and newcomers to Python and programming. If you have any questions, please feel free to ask them. And, again, I apologize about the earlier rant; I get emotional very easily. *grin* From chelan.farsight at gmail.com Fri Mar 4 20:31:08 2005 From: chelan.farsight at gmail.com (Chelan Farsight) Date: Fri Mar 4 20:31:13 2005 Subject: [Tutor] Re: Q & A In-Reply-To: <Pine.LNX.4.44.0503041049420.28602-100000@hkn.eecs.berkeley.edu> References: <661da26c05030410371eba7b4b@mail.gmail.com> <Pine.LNX.4.44.0503041049420.28602-100000@hkn.eecs.berkeley.edu> Message-ID: <661da26c050304113158291c82@mail.gmail.com> Kent and Danny, Thanks so much for the quick and warmhearted reply. /whew Just wanted to make sure. I know there are lists specifically aimed at advanced users and wanted to watch my p's and q's. Well as I work my way through I am certain I will have questions and I am glad I have found a place to help out. Oh and rant away it can be kinda fun at times =) Thanks again, Chelan From bill at celestial.net Fri Mar 4 22:02:11 2005 From: bill at celestial.net (Bill Campbell) Date: Fri Mar 4 22:02:04 2005 Subject: [Tutor] Berkeley db incompatibility Message-ID: <20050304210211.GC96069@alexis.mi.celestial.com> I don't know that this is a tutor topic, but since I'm a python newbie, I'll try. Building python-2.4 with db-4.3.27 fails on an undefined enum, DB_LSTAT_ERR resulting in no bsddb module. It looks like the sleepycat folks decided to break backwards compatibility by dropping this out of the enum. I've tried google to find a fix, but haven't found anything yet. Is there a recommended fix for this? Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ The Constitution is a written instrument. As such, its meaning does not alter. That which it meant when it was adopted, it means now. -- SOUTH CAROLINA v. US, 199 U.S. 437, 448 (1905) From project5 at redrival.net Fri Mar 4 21:55:31 2005 From: project5 at redrival.net (Andrei) Date: Fri Mar 4 22:02:32 2005 Subject: [Tutor] Re: Re: Q & A References: <20050226062509.47947.qmail@web51603.mail.yahoo.com> <Pine.LNX.4.44.0503032245380.17769-100000@hkn.eecs.berkeley.edu> <661da26c05030410371eba7b4b@mail.gmail.com> Message-ID: <rc9k2t0wgdh9$.adib1qtykniq$.dlg@40tude.net> Chelan Farsight wrote on Fri, 4 Mar 2005 12:37:58 -0600: > actions of Mr. Chui. I simply wanted to make sure that I have joined > the right list. Are we allowed to ask total n00b questions on this > list? If not what level of understanding is presumed before someone > should post a question? The Tutor list is for beginners, which includes people who haven't programmed before. I'd say it even includes homework where the student in question has actually tried doing something and ran into a snag, but not in the case where the student just posts a "solve this homework for me". -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From kent37 at tds.net Sat Mar 5 01:50:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 01:50:59 2005 Subject: [Tutor] (no subject) In-Reply-To: <d082fff805030407435e6ae83c@mail.gmail.com> References: <d082fff805030407435e6ae83c@mail.gmail.com> Message-ID: <4229026D.10002@tds.net> Kevin wrote: > Hello all. I have just completed my very first python program just a > simple number guessing. I would like for someone to try it out if they > could and let me know how I did with it and where I could have > improved apon it. There are t files main.py and defs.py I second Brian's comments about comments and white space. The comments make it very hard to pick out the actual code. Better if you can let the code speak for itself. Kent From keridee at jayco.net Sat Mar 5 02:07:49 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Mar 5 02:07:21 2005 Subject: [Tutor] Linked List References: <20050304171941.53337.qmail@web53806.mail.yahoo.com> Message-ID: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> I'm taking a shot in the dark and answering here. Have you tried making a copy of the list, iterating over the copy, and changing the original based on the copy? Jacob > Hi, > Any body has any idea on how to implement a linked > list in python? > Ordinary python lists are not quite the same. what i > need is a list i can traverse through sequentially > without bothering about the indices, as another > process is continuously editing this list, by > inserting and deleting elements even as the list is > being traversed. > > Shitiz > > > > > __________________________________ > Celebrate Yahoo!'s 10th Birthday! > Yahoo! Netrospective: 100 Moments of the Web > http://birthday.yahoo.com/netrospective/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From ron at frenchmerchants.net Sat Mar 5 03:39:44 2005 From: ron at frenchmerchants.net (Ronnie Betzen) Date: Sat Mar 5 03:39:59 2005 Subject: [Tutor] Problem with IntVar() Message-ID: <200503042039.46191.ron@frenchmerchants.net> I've been trying to use IntVar() to update checkboxes using the Tkinter toolkit. To date I haven't been successful getting it to work. Evidently I'm missing some concept with regards to setting up my interface. I've successfully run scripts by other people using IntVar() so I know my personal system is ok. Here is some code that causes me problems with IntVar(). Can someone enlighten this total newbie (python and programming both.) as to what I'm missing here? Thanks, Ron From ron at frenchmerchants.net Sat Mar 5 03:52:02 2005 From: ron at frenchmerchants.net (Ronnie Betzen) Date: Sat Mar 5 03:52:06 2005 Subject: [Tutor] Problem with IntVar() - Oops! Here's the code. In-Reply-To: <200503042039.46191.ron@frenchmerchants.net> References: <200503042039.46191.ron@frenchmerchants.net> Message-ID: <200503042052.02275.ron@frenchmerchants.net> #! /usr/bin/env python import Tkinter class timer: def __init__(self): # initialize global variables self.ckbuttonstatus = IntVar() # set up main window self.top = Tk() self.top.geometry('355x125') self.top.title(appname) self.top.resizable(width='no', height='no') # set up menubar self.menubar = menu(self.top) self.top.config(menu = self.menubar) # set up file menu self.filemenu = Menu(self.menubar, tearoff = 0) self.filemenu.add_cascade(label="File", menu=self.filemenu) self.filemenu.add_checkbutton(label = "Click Me!", command = self.labelUpdate) self.filemenu.add_command(label = "Quit", command=self.top.quit) # set up main display area self.frame = Frame(self.top) self.frame.pack(fill=x) self.displaylabel=Label(self.frame, text=" ", font="Times 36 bold", relief="sunken") self.displaylabel.pack(side=BOTTOM, fill=X) def labelUpdate(self): self.status = self.ckbuttonstatus.get() self.labeltext = "Chekbutton status is: " + self.status self.displaylabel.config(text=labeltext) self.top.update() if __name__ == '__main__': mainApp = timer() mainloop() On Friday 04 March 2005 08:39 pm, Ronnie Betzen wrote: > I've been trying to use IntVar() to update checkboxes using the Tkinter > toolkit. To date I haven't been successful getting it to work. Evidently > I'm missing some concept with regards to setting up my interface. I've > successfully run scripts by other people using IntVar() so I know my > personal system is ok. > > Here is some code that causes me problems with IntVar(). Can someone > enlighten this total newbie (python and programming both.) as to what I'm > missing here? > > Thanks, > > Ron > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From billk at fastmail.fm Sat Mar 5 05:05:53 2005 From: billk at fastmail.fm (Bill Kranec) Date: Sat Mar 5 05:05:48 2005 Subject: [Tutor] returning table elements with Beautiful Soup Message-ID: <42293021.1030309@fastmail.fm> Hi, I'm trying to use Beautiful Soup to scrape some data out of an HTML table. I can do this using table = soup("td", {'class' : 'yfnc_tabledata1' }) table[0].string.strip() However, if I try for entry in table: entry.string.strip() I get: AttributeError: Tag instance has no attribute 'string' Clearly Python is now treating the cell as a list element, not as a Beautiful Soup class, so it cannot find the method that I want to use. But I can't seem to find a way to do what I meant to do. Is there an easy way to have Beautiful Soup return each data element in the table, preferably into a list? Any help is greatly appreciated. Bill From kent37 at tds.net Sat Mar 5 05:48:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 05:48:06 2005 Subject: [Tutor] Problem with IntVar() - Oops! Here's the code. In-Reply-To: <200503042052.02275.ron@frenchmerchants.net> References: <200503042039.46191.ron@frenchmerchants.net> <200503042052.02275.ron@frenchmerchants.net> Message-ID: <42293A01.4070507@tds.net> There seem to be quite a few problems with this code... Ronnie Betzen wrote: > #! /usr/bin/env python > import Tkinter should be from Tkinter import * > > class timer: > def __init__(self): > The next line needs to be after the line 'self.top = Tk()' so Tkinter is initialized when the variable is created. > # initialize global variables > self.ckbuttonstatus = IntVar() > > # set up main window > self.top = Tk() > self.top.geometry('355x125') appname is not defined... > self.top.title(appname) etc... I think you have bitten off too much here. Try starting with a very small, working program that has a little of what you want in it. Then add another little piece and get that working. Repeat until you get to where you want to be. Ask questions when you don't understand the next step. Here is a very simple program that links a checkbox and a label through a variable. Maybe this is a step in the right direction for you: from Tkinter import * root = Tk() var = IntVar() Label(textvariable=var).pack() c = Checkbutton(text="Click Me", variable=var) c.pack() root.mainloop() Kent > self.top.resizable(width='no', height='no') > > # set up menubar > self.menubar = menu(self.top) > self.top.config(menu = self.menubar) > > # set up file menu > self.filemenu = Menu(self.menubar, tearoff = 0) > self.filemenu.add_cascade(label="File", menu=self.filemenu) > self.filemenu.add_checkbutton(label = "Click Me!", command = > self.labelUpdate) > self.filemenu.add_command(label = "Quit", command=self.top.quit) > > # set up main display area > self.frame = Frame(self.top) > self.frame.pack(fill=x) > self.displaylabel=Label(self.frame, text=" ", font="Times 36 bold", > relief="sunken") > self.displaylabel.pack(side=BOTTOM, fill=X) > > def labelUpdate(self): > self.status = self.ckbuttonstatus.get() > self.labeltext = "Chekbutton status is: " + self.status > self.displaylabel.config(text=labeltext) > self.top.update() > > if __name__ == '__main__': > mainApp = timer() > mainloop() > > > On Friday 04 March 2005 08:39 pm, Ronnie Betzen wrote: > >>I've been trying to use IntVar() to update checkboxes using the Tkinter >>toolkit. To date I haven't been successful getting it to work. Evidently >>I'm missing some concept with regards to setting up my interface. I've >>successfully run scripts by other people using IntVar() so I know my >>personal system is ok. >> >>Here is some code that causes me problems with IntVar(). Can someone >>enlighten this total newbie (python and programming both.) as to what I'm >>missing here? >> >>Thanks, >> >>Ron >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ron at frenchmerchants.net Sat Mar 5 06:20:29 2005 From: ron at frenchmerchants.net (Ronnie Betzen) Date: Sat Mar 5 06:20:37 2005 Subject: [Tutor] Problem with IntVar() (SOLVED!) In-Reply-To: <42293A01.4070507@tds.net> References: <200503042039.46191.ron@frenchmerchants.net> <200503042052.02275.ron@frenchmerchants.net> <42293A01.4070507@tds.net> Message-ID: <200503042320.29917.ron@frenchmerchants.net> Thanks, Kent! Moving self.top=Tk() up solved the IntVar() problem. *sigh* Man, learning curves can be a royal pain.... ;-) Also, thanks for the advice about starting off with little bits at a time. Kinda seems like an obvious way to do things when you think about it. :-/ From kent37 at tds.net Sat Mar 5 06:22:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 06:22:12 2005 Subject: [Tutor] returning table elements with Beautiful Soup In-Reply-To: <42293021.1030309@fastmail.fm> References: <42293021.1030309@fastmail.fm> Message-ID: <422941FF.9070205@tds.net> Bill Kranec wrote: > Hi, > > I'm trying to use Beautiful Soup to scrape some data out of an HTML > table. I can do this using > > table = soup("td", {'class' : 'yfnc_tabledata1' }) > table[0].string.strip() OK, table is a list of Tags, the first one has a 'string' attribute. > > However, if I try > > for entry in table: > entry.string.strip() > > I get: AttributeError: Tag instance has no attribute 'string' Because not every Tag in table has a 'string' attribute, only the ones that have a single string child somewhere. Try this and you will see better what is going on: import urllib2 from BeautifulSoup import BeautifulSoup data = urllib2.urlopen('http://finance.yahoo.com/q?s=IBM').read() soup = BeautifulSoup(data) table = soup("td", {'class' : 'yfnc_tabledata1' }) for entry in table: print entry try: print entry.string except AttributeError: print 'No string' ## prints <td class="yfnc_tabledata1"><big><b>92.37</b></big></td> 92.37 <td class="yfnc_tabledata1">Mar 4</td> Mar 4 <td class="yfnc_tabledata1"><img width="10" height="14" border="0" src="http://us.i1.yimg.com/us.yimg.com/i/us/fi/03rd/down_r.gif" alt="Down" /> <b style="color:#cc0000;">0.04 (0.04%)</b></td> No string ...etc Notice the third element has two string children - ' ' and '0.04 (0.04%)'. You will have to do a little more work if you want the text from that one. > Is there an easy way to have Beautiful Soup return each data element in > the table, preferably into a list? allStrings = [entry.string for entry in table if hasattr(entry, 'string')] print allStrings ## prints ['92.37', 'Mar 4', '92.41', '92.94', 'N/A', 'N/A', '107.33', '92.36 - 93.18', '81.90 - 99.10', '4,754,000', '4,619,454', '150.81B', '18.65', '4.95', '0.72 (0.78%)', '15.02', '1.57', '10-Mar-05', ' 8-Feb-05', '5.62', '1.04', '2.1', '1.64'] Kent From osagie at gmail.com Sat Mar 5 06:25:18 2005 From: osagie at gmail.com (Anderson) Date: Sat Mar 5 06:25:21 2005 Subject: [Tutor] Cataloging Web Page Information Message-ID: <56defa170503042125689d98dc@mail.gmail.com> Hello, I currently have access to a webpage that has information that I'd like to put into a CSV (comma seperated value) spreadsheet. Its frontend is a form; you fill the form out by entering some text and selecting the appropriate option from a drop down menu, and then you press the submit form button. The webpage subsequently displays links to every entry it can find and when you click on the link you get the full info of that entry. I want to automate the whole process with a python script. I figured out that the csv module(s) would be best for storing the received information but what module should I use to access the website, fill out the form, enter each resulting link and retrieve the information? Thanks for your time, Anderson From kent37 at tds.net Sat Mar 5 06:50:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 06:50:40 2005 Subject: [Tutor] Cataloging Web Page Information In-Reply-To: <56defa170503042125689d98dc@mail.gmail.com> References: <56defa170503042125689d98dc@mail.gmail.com> Message-ID: <422948AA.4000707@tds.net> Anderson wrote: > Hello, > > I currently have access to a webpage that has information that I'd > like to put into a CSV (comma seperated value) spreadsheet. Its > frontend is a form; you fill the form out by entering some text and > selecting the appropriate option from a drop down menu, and then you > press the submit form button. You may be able just to send the same data as the form without having to actually read the form from the web site. If the form uses GET, you can see the data it sends in the URL bar of the browser after you submit the form. If the form uses POST, you will have to look at the actual form to see how the data is formatted. Alternatively you can use ClientForm to fill out the actual form and submit it. http://wwwsearch.sourceforge.net/ClientForm/ > > The webpage subsequently displays links to every entry it can find and > when you click on the link you get the full info of that entry. BeautifulSoup can help you pull the links out of the reply. http://www.crummy.com/software/BeautifulSoup/ urllib2 (in the standard library) can retrieve the final web page, if you need to parse it use BeautifulSoup again. Kent > > I want to automate the whole process with a python script. I figured > out that the csv module(s) would be best for storing the received > information but what module should I use to access the website, fill > out the form, enter each resulting link and retrieve the information? > > Thanks for your time, > Anderson > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Sat Mar 5 15:01:48 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Mar 5 15:01:29 2005 Subject: [Tutor] (no subject) References: <d082fff805030407435e6ae83c@mail.gmail.com> Message-ID: <000901c5218b$e8e3c860$735428cf@JSLAPTOP> I want to third the whitespace and comments. Also, looking at your code I notice that each of your > while 1: > play = raw_input("What is your choice? ") #Aks use to enter a choice > from the menu > if play == '3': #If user picks 3 > print "\nHave a nice day!\n" #Tell them to have a nice day > sys.exit() #Then exit the entire thing > elif play == '2': #If user picks 2 > instruct() #Then lets call the instructions function > elif play == '1': #If user picks 1 > game() #Then lets call the game function for the user to play > elif play == '': #This is used is the menu leaves the screen so the > user can get it back > choice() #Bring back the menu > else: > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" results from the choice are basically functions and functions are objects, so.... (I got this idea from Danny and Kent - I like it...) def exit(): print "\nHave a nice day!\n" # You might want to make this a raw_input so the sys.exit() # user can catch it before the screen disappears... def altexit(): # Alternative exit raw_input("\nHave a nice day!\nPress enter to exit.") # This stops the exit just long enough for the user to press enter and leave sys.exit() def instruct(): ## Whatever instruct is, goes here def game(): ## The game function is here def choice(): ## The choice definition is here ## Now the fun part ## ## We define a dictionary options that stores the strings that the user would input as keys. The values ## are the functions that we just defined options = {"3":altexit, # Notice no parenthesis--we don't want to call the functions when putting them in the dicionary! "2":instruct, "1":game, "":choice} while 1: play = raw_input("What is your choice? ") if play in options.keys(): ## This makes sure that the user input is one of our options options[play]() ## Call the function that is the value of the key that is the choice the user made else: ## Say that the user input is not one of your choices... print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" HTH, Jacob From alan.gauld at freenet.co.uk Sat Mar 5 15:20:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Mar 5 15:19:48 2005 Subject: [Tutor] returning table elements with Beautiful Soup References: <42293021.1030309@fastmail.fm> <422941FF.9070205@tds.net> Message-ID: <014c01c5218e$7a6291c0$1cd28751@xp> > > I'm trying to use Beautiful Soup to scrape some data out of an HTML > > table. I can do this using A new one on me, but Beautiful Soup looks very interesting. I've just downloaded it. Thanks for pointing it out. Alan G. From shitizb at yahoo.com Sat Mar 5 15:20:40 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Mar 5 15:20:43 2005 Subject: [Tutor] Linked List In-Reply-To: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> Message-ID: <20050305142041.7620.qmail@web53807.mail.yahoo.com> I could not understand what you exactly mean. In order to explain wat my problem is, here is an example code. Its not exactly what I am doing, I am using multiple threads and a rather complicated code so try and understand the sense rather than the code itself. >>> myls=range(50) >>> for i in myls: print i if i==20: myls.insert(5,5) The point is, the list(both size and elements) is changing even as it is being operated upon. This particular case goes into infinite loop at i=20. Interestingly, I can freely edit the list yet to be traversed, without any ill effects, which would not have been possible if a python list was a pure array(due to immutable length of an array in c). Shitiz --- "Jacob S." <keridee@jayco.net> wrote: > I'm taking a shot in the dark and answering here. > > Have you tried making a copy of the list, iterating > over the copy, and > changing the original based on the copy? > > Jacob > > > Hi, > > Any body has any idea on how to implement a linked > > list in python? > > Ordinary python lists are not quite the same. what > i > > need is a list i can traverse through > sequentially > > without bothering about the indices, as another > > process is continuously editing this list, by > > inserting and deleting elements even as the list > is > > being traversed. > > > > Shitiz > > > > > > > > > > __________________________________ > > Celebrate Yahoo!'s 10th Birthday! > > Yahoo! Netrospective: 100 Moments of the Web > > http://birthday.yahoo.com/netrospective/ > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Sat Mar 5 15:53:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 15:54:01 2005 Subject: [Tutor] (no subject) In-Reply-To: <000901c5218b$e8e3c860$735428cf@JSLAPTOP> References: <d082fff805030407435e6ae83c@mail.gmail.com> <000901c5218b$e8e3c860$735428cf@JSLAPTOP> Message-ID: <4229C804.3030208@tds.net> Jacob S. wrote: > while 1: > play = raw_input("What is your choice? ") > if play in options.keys(): ## This makes sure that the user > input is one of our options 'if play in options' is preferable. options.keys() returns a list of keys that will be searched sequentially. options is a dict which supports fast direct lookup. So when you say 'if play in options.keys()' not only do you type more but you generate an intermediate list and use a slower form of search! > options[play]() ## Call the function that is the > value of the key that is the choice the user made > else: ## Say that the user input > is not one of your choices... > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" But even better is to make the error message a default option: def bad_choice(): print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Then the lookup becomes just options.get(play, bad_choice)() Kent From python at venix.com Sat Mar 5 17:32:01 2005 From: python at venix.com (Lloyd Kvam) Date: Sat Mar 5 17:32:05 2005 Subject: [Tutor] cataloging web Page Information Message-ID: <1110040320.5848.10.camel@laptop.venix.com> A minor addition to Kent's advice: urllib2 can be used to post form data to a web site. This is very convenient if the expected data format is stable. You will still need the urlencode from urllib to encode the data to be posted. -- Lloyd Kvam Venix Corp From kent37 at tds.net Sat Mar 5 19:21:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 5 19:21:18 2005 Subject: [Tutor] Linked List In-Reply-To: <20050305142041.7620.qmail@web53807.mail.yahoo.com> References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> Message-ID: <4229F89A.9030705@tds.net> Shitiz Bansal wrote: > I could not understand what you exactly mean. > > In order to explain wat my problem is, here is an > example code. Its not exactly what I am doing, I am > using multiple threads and a rather complicated code > so try and understand the sense rather than the code > itself. > > >>>>myls=range(50) >>>>for i in myls: > > print i > if i==20: > myls.insert(5,5) > > The point is, the list(both size and elements) is > changing even as it is being operated upon. What Jacob is saying is, one common way to deal with this is to make a copy of the list and iterate over that while changing the original list. Your sample would look like this: myls=range(50) for i in myls[:]: # <-- Note: makes a copy of myls print i if i==20: myls.insert(5,5) Kent > > This particular case goes into infinite loop at i=20. > > Interestingly, I can freely edit the list yet to be > traversed, without any ill effects, which would not > have been possible if a python list was a pure > array(due to immutable length of an array in c). > > Shitiz > > --- "Jacob S." <keridee@jayco.net> wrote: > > >>I'm taking a shot in the dark and answering here. >> >>Have you tried making a copy of the list, iterating >>over the copy, and >>changing the original based on the copy? >> >>Jacob From amonroe at columbus.rr.com Sat Mar 5 23:11:29 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Mar 5 23:12:16 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknown binary graphic file format? Message-ID: <24467817445.20050305171129@columbus.rr.com> I know it's a long shot but... I have some graphics files from an old DOS game that I want to convert to a normal .png or whatever. Anyone know of a program that can load binary data and view it multiple different ways? Like treating the raw data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and offset, etc. in some kind of GUI until you get a recognizable image? The game reads its graphic files in 512 byte increments at runtime, judging by sysinterals filemon. This gave me a little hope that the graphics are uncompressed even multiples of 512 bytes each. I used python to read the 1st 512 bytes of the file and output it to another file, for experimentation. I wrote a script to read that in and output the high 4 bits as a byte, and the low 4 bits as a subsequent byte, but that image didn't really look like anything recognizable, loading it as raw into Photoshop. Alan From dyoo at hkn.eecs.berkeley.edu Sat Mar 5 23:31:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 5 23:31:59 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknown binary graphic file format? In-Reply-To: <24467817445.20050305171129@columbus.rr.com> Message-ID: <Pine.LNX.4.44.0503051426080.22524-100000@hkn.eecs.berkeley.edu> On Sat, 5 Mar 2005, R. Alan Monroe wrote: > I have some graphics files from an old DOS game that I want to convert > to a normal .png or whatever. Anyone know of a program that can load > binary data and view it multiple different ways? Like treating the raw > data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and > offset, etc. in some kind of GUI until you get a recognizable image? Hi Alan, A lot of image types contain a recognizable header that you might be able to use. Python comes with a library that tries its best to recognize certain image file types: http://www.python.org/doc/lib/module-imghdr.html You may want to do a quick check with imghdr to see if it's something standard that 'imghdr' can recognize. Another possibility is to use the 'file' Unix utility, which also recognizes a surprising variety of file formats. Otherwise, I'm out of ideas at the moment. *grin* You may want to ask your question on comp.lang.python, since it is slightly unusual to get a file and have to infer the file type. From shitizb at yahoo.com Sun Mar 6 00:01:34 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sun Mar 6 00:01:37 2005 Subject: [Tutor] Linked List In-Reply-To: <4229F89A.9030705@tds.net> Message-ID: <20050305230134.24036.qmail@web53809.mail.yahoo.com> Got ya, it doesnt however help in my case as inside the for loop also i intend to change the list elements. --- Kent Johnson <kent37@tds.net> wrote: > Shitiz Bansal wrote: > > I could not understand what you exactly mean. > > > > In order to explain wat my problem is, here is an > > example code. Its not exactly what I am doing, I > am > > using multiple threads and a rather complicated > code > > so try and understand the sense rather than the > code > > itself. > > > > > >>>>myls=range(50) > >>>>for i in myls: > > > > print i > > if i==20: > > myls.insert(5,5) > > > > The point is, the list(both size and elements) is > > changing even as it is being operated upon. > > What Jacob is saying is, one common way to deal with > this is to make a copy of the list and iterate > over that while changing the original list. Your > sample would look like this: > > myls=range(50) > for i in myls[:]: # <-- Note: makes a copy of myls > print i > if i==20: > myls.insert(5,5) > > Kent > > > > > This particular case goes into infinite loop at > i=20. > > > > Interestingly, I can freely edit the list yet to > be > > traversed, without any ill effects, which would > not > > have been possible if a python list was a pure > > array(due to immutable length of an array in c). > > > > Shitiz > > > > --- "Jacob S." <keridee@jayco.net> wrote: > > > > > >>I'm taking a shot in the dark and answering here. > >> > >>Have you tried making a copy of the list, > iterating > >>over the copy, and > >>changing the original based on the copy? > >> > >>Jacob > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From cyresse at gmail.com Sun Mar 6 00:11:45 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 6 00:11:50 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknown binary graphic file format? In-Reply-To: <Pine.LNX.4.44.0503051426080.22524-100000@hkn.eecs.berkeley.edu> References: <24467817445.20050305171129@columbus.rr.com> <Pine.LNX.4.44.0503051426080.22524-100000@hkn.eecs.berkeley.edu> Message-ID: <f2ff2d05030515114c81ece1@mail.gmail.com> Slightly OT, but I'd recommend Irfanview, a wonderful piece of freeware. If it can't open it, it's probably not in a standard graphics file format. On Sat, 5 Mar 2005 14:31:50 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Sat, 5 Mar 2005, R. Alan Monroe wrote: > > > I have some graphics files from an old DOS game that I want to convert > > to a normal .png or whatever. Anyone know of a program that can load > > binary data and view it multiple different ways? Like treating the raw > > data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and > > offset, etc. in some kind of GUI until you get a recognizable image? > > Hi Alan, > > A lot of image types contain a recognizable header that you might be able > to use. Python comes with a library that tries its best to recognize > certain image file types: > > http://www.python.org/doc/lib/module-imghdr.html > > You may want to do a quick check with imghdr to see if it's something > standard that 'imghdr' can recognize. Another possibility is to use the > 'file' Unix utility, which also recognizes a surprising variety of file > formats. > > Otherwise, I'm out of ideas at the moment. *grin* You may want to ask > your question on comp.lang.python, since it is slightly unusual to get a > file and have to infer the file type. > > _______________________________________________ > 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. From stbru at teksavvy.com Sun Mar 6 00:28:41 2005 From: stbru at teksavvy.com (=?ISO-8859-1?Q?St=E9phane_Brunet?=) Date: Sun Mar 6 00:28:17 2005 Subject: [Tutor] Linked List In-Reply-To: <4229F89A.9030705@tds.net> References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> <4229F89A.9030705@tds.net> Message-ID: <422A40A9.2000808@teksavvy.com> Kent Johnson wrote: > > What Jacob is saying is, one common way to deal with this is to make a > copy of the list and iterate over that while changing the original > list. Your sample would look like this: Hi, And what if the list is *really* big ? Don't you loose much speed/memory while making a copy ? St?phane From alan.gauld at freenet.co.uk Sun Mar 6 00:56:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 00:56:07 2005 Subject: [Tutor] (no subject) References: <d082fff805030407435e6ae83c@mail.gmail.com> <000901c5218b$e8e3c860$735428cf@JSLAPTOP> Message-ID: <016701c521df$023bbc20$1cd28751@xp> > ## Now the fun part ## > ## We define a dictionary options that stores the strings that the user > would input as keys. The values > ## are the functions that we just defined > > options = {"3":altexit, # Notice no parenthesis--we don't want to > call the functions when putting them in the dicionary! > "2":instruct, > "1":game, > "":choice} > > while 1: > play = raw_input("What is your choice? ") > if play in options.keys(): > options[play]() > else: > print "\nYou need to pick 1, 2 or 3 or hit enter to see choices\n" Or more pythonically: while 1: play = raw_input(... try: options[play]() except KeyError: print "\nYou need...." Avoids the search of keys each time, and follows the idiom of "its better to ask forgiveness" Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Mar 6 01:04:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 01:04:13 2005 Subject: [Tutor] Linked List References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> Message-ID: <016e01c521e0$21f59260$1cd28751@xp> > >>> myls=range(50) > >>> for i in myls: > print i > if i==20: > myls.insert(5,5) > > The point is, the list(both size and elements) is > changing even as it is being operated upon. You are quite right it is, in general a bad idea to alter the thing you are iterating over. > This particular case goes into infinite loop at i=20. For obvious reasons: you insert something before 20 which moves up one position, the next element in the list is now 20 again. Better to use a while loop over the indices if you must do this kind of thing, then increment the index as well as insert the item. myls = range(50) index = 0 while index < len(myls): print myls[index] if myls[index] == 20: myls.insert(5,5) index += 1 index += 1 But if the changes are being made outside your loop (eg by another thread - dangerous practice anyway!) you need the linked list approach and you also need to treat our list as a protected resource in your threads. ie lock it before using otherwise you may wind up deleting the thing you are working on! HTH, Alan G. From alan.gauld at freenet.co.uk Sun Mar 6 01:08:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 01:08:23 2005 Subject: [Tutor] Anyone know of a window utility to reverse engineer unknownbinary graphic file format? References: <24467817445.20050305171129@columbus.rr.com> Message-ID: <017901c521e0$ada59cb0$1cd28751@xp> > I have some graphics files from an old DOS game that I want to convert to > a normal .png or whatever. Anyone know of a program that can load > binary data and view it multiple different ways? Like treating the raw > data as 1 bit, 4 bit, 8 bit, planar, linear, adjust the pitch and > offset, etc. in some kind of GUI until you get a recognizable image? I usually just rename the file by changing the extension till something succeeeds in opening it! There are some graphics format convertors around however so it might be worth googling for them and see if any do auto format detection. Alan G. From kent37 at tds.net Sun Mar 6 01:29:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 6 01:29:26 2005 Subject: [Tutor] Linked List In-Reply-To: <422A40A9.2000808@teksavvy.com> References: <20050305142041.7620.qmail@web53807.mail.yahoo.com> <4229F89A.9030705@tds.net> <422A40A9.2000808@teksavvy.com> Message-ID: <422A4EE2.3020800@tds.net> St?phane Brunet wrote: > Kent Johnson wrote: > >> >> What Jacob is saying is, one common way to deal with this is to make a >> copy of the list and iterate over that while changing the original >> list. Your sample would look like this: > > > Hi, > > And what if the list is *really* big ? Don't you loose much speed/memory > while making a copy ? Well, you do need double the memory and it does take time to copy the list. Whether it is too much will depend on the specific requirements. If you use a linked list instead of a built-in list you will more than double the memory requirements immediately. In a linked list, for each data item you store a reference to the data, a reference to the next node and the overhead of the node class instance. The built-in list just has a single reference for each item and a single instance overhead. The time to traverse a linked list may well be much greater than for a builtin list. Builtins are fast, often faster than anything you can write yourself in Python. In Python often the simple solution works best. Don't dismiss it until you try it :-) Alternatives for filtering a list are - use a list comprehension to build a new list. This is often the best solution. It copies the elements being kept, but it avoids having to shift list elements when one element is deleted. - work from the back of the list - it is safe to iterate a list in reverse and delete elements as you go. I don't think either of these meet the OP's requirements, though. As I understand it, he wants to iterate a list, changing the list as he goes, while the list is also being modified by another thread. A naive linked list will not satisfy these requirements either - some sort of synchronization will be needed to avoid, for example, one thread linking a new item onto an item that is being deleted by the other thread. Kent From kabads at gmail.com Sun Mar 6 08:41:30 2005 From: kabads at gmail.com (Adam Cripps) Date: Sun Mar 6 08:41:35 2005 Subject: [Tutor] (no subject) In-Reply-To: <c7ff3855050305233810d4f08a@mail.gmail.com> References: <d082fff805030407435e6ae83c@mail.gmail.com> <42289774.6010607@po-box.mcgill.ca> <c7ff3855050305233810d4f08a@mail.gmail.com> Message-ID: <c7ff3855050305234132f8bc9f@mail.gmail.com> On Sun, 6 Mar 2005 07:38:54 +0000, Adam Cripps <kabads@gmail.com> wrote: > On Fri, 04 Mar 2005 12:14:28 -0500, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > Kevin said unto the world upon 2005-03-04 10:43: > > Hello all. I have just completed my very first python program just a > > simple number guessing. I would like for someone to try it out if they > > could and let me know how I did with it and where I could have > > improved apon it. There are t files main.py and defs.py > > > > Thanks > > Hi Kevin, > > Though I am a learner, too, I have a few comments. They are more about > style than substance. > > 1) A lot of your code comments get in the way of my reading and easily > understanding the code. Consider: > > .# leading `.'s to foil google groups and other whitespace stripping > readers > .if play == '3': #If user picks 3 > . print "\nHave a nice day!\n" #Tell them to have a nice day > . sys.exit() #Then exit the entire thing > > I think this would be much easier to read if it were like: > > .if play == '3': # If user picks 3 > . print "\nHave a nice day!\n" # Tell them to have a nice day > . sys.exit() # Then exit the entire thing > > (Note that some people hate the comments along the side and would > prefer them the precede the line(s) they comment on. I like the 2 > column approach, but that's just one duffer's view.) > > But, even better would be: > > .if play == '3': > . print "\nHave a nice day!\n" > . sys.exit() > <snip> Is the tutor list mirrored on usenet such as google groups? I've searched and not found it. I think it's a bit harsh to blame the style on a client that strips white-space, where he has no control over it. Are we not better off using another client? I use gmail [1] to collect this kind of email and using the recent thread entitle "Reading Tutor with gmail: monospace fonts" have managed to make my mail monospace, which makes it a lot easier to read. None of the whitespace was stripped in my mail, and the style looked fine. In fact, by littering it with '.' you are making it more of a task to run this script, as you have to strip all the '.' out first - a real pain. Adam [1] Although gmail is far from perfect. From cyresse at gmail.com Sun Mar 6 08:44:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 6 08:44:37 2005 Subject: [Tutor] (no subject) In-Reply-To: <c7ff3855050305234132f8bc9f@mail.gmail.com> References: <d082fff805030407435e6ae83c@mail.gmail.com> <42289774.6010607@po-box.mcgill.ca> <c7ff3855050305233810d4f08a@mail.gmail.com> <c7ff3855050305234132f8bc9f@mail.gmail.com> Message-ID: <f2ff2d0503052344a24348d@mail.gmail.com> How about everyone uses www.rafb.net/paste for long bits of code? I know I do, as it colours functions, classes differently, etc, and it respects tabs. On Sun, 6 Mar 2005 07:41:30 +0000, Adam Cripps <kabads@gmail.com> wrote: > On Sun, 6 Mar 2005 07:38:54 +0000, Adam Cripps <kabads@gmail.com> wrote: > > On Fri, 04 Mar 2005 12:14:28 -0500, Brian van den Broek > > <bvande@po-box.mcgill.ca> wrote: > > Kevin said unto the world upon 2005-03-04 10:43: > > > Hello all. I have just completed my very first python program just a > > > simple number guessing. I would like for someone to try it out if they > > > could and let me know how I did with it and where I could have > > > improved apon it. There are t files main.py and defs.py > > > > > > Thanks > > > > Hi Kevin, > > > > Though I am a learner, too, I have a few comments. They are more about > > style than substance. > > > > 1) A lot of your code comments get in the way of my reading and easily > > understanding the code. Consider: > > > > .# leading `.'s to foil google groups and other whitespace stripping > > readers > > .if play == '3': #If user picks 3 > > . print "\nHave a nice day!\n" #Tell them to have a nice day > > . sys.exit() #Then exit the entire thing > > > > I think this would be much easier to read if it were like: > > > > .if play == '3': # If user picks 3 > > . print "\nHave a nice day!\n" # Tell them to have a nice day > > . sys.exit() # Then exit the entire thing > > > > (Note that some people hate the comments along the side and would > > prefer them the precede the line(s) they comment on. I like the 2 > > column approach, but that's just one duffer's view.) > > > > But, even better would be: > > > > .if play == '3': > > . print "\nHave a nice day!\n" > > . sys.exit() > > > <snip> > > Is the tutor list mirrored on usenet such as google groups? I've > searched and not found it. I think it's a bit harsh to blame the style > on a client that strips white-space, where he has no control over it. > Are we not better off using another client? > > I use gmail [1] to collect this kind of email and using the recent thread > entitle "Reading Tutor with gmail: monospace fonts" have managed to > make my mail monospace, which makes it a lot easier to read. None of > the whitespace was stripped in my mail, and the style looked fine. In > fact, by littering it with '.' you are making it more of a task to run > this script, as you have to strip all the '.' out first - a real pain. > > Adam > > [1] Although gmail is far from perfect. > _______________________________________________ > 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. From bvande at po-box.mcgill.ca Sun Mar 6 09:40:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Mar 6 09:42:16 2005 Subject: [Tutor] (no subject) In-Reply-To: <c7ff3855050305233810d4f08a@mail.gmail.com> References: <d082fff805030407435e6ae83c@mail.gmail.com> <42289774.6010607@po-box.mcgill.ca> <c7ff3855050305233810d4f08a@mail.gmail.com> Message-ID: <422AC1F9.9030403@po-box.mcgill.ca> Adam Cripps said unto the world upon 2005-03-06 02:38: > On Fri, 04 Mar 2005 12:14:28 -0500, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > >>Kevin said unto the world upon 2005-03-04 10:43: >> >>>Hello all. I have just completed my very first python program just a >>>simple number guessing. I would like for someone to try it out if they >>>could and let me know how I did with it and where I could have >>>improved apon it. There are t files main.py and defs.py >>> >>>Thanks >> >>Hi Kevin, >> >>Though I am a learner, too, I have a few comments. They are more about >>style than substance. >> >>1) A lot of your code comments get in the way of my reading and easily >>understanding the code. Consider: >> >>.# leading `.'s to foil google groups and other whitespace stripping >>readers <SNIP> > <snip> > > Is the tutor list mirrored on usenet such as google groups? I've > searched and not found it. I think it's a bit harsh to blame the style > on a client that strips white-space, where he has no control over it. > Are we not better off using another client? Hi Adam, I don't know if tutor is viewable through google groups or not. However, it has proved a problem on comp.lang.python, where I picked up the leading '.' trick. Noting that Kevin (the OP) was using a gmail account and not knowing if the google groups' leading whitespace stripping `feature' was also a gmail feature, I figured it would be better to be safe and put the possibly needless '.'s in. It would indeed have been harsh to complain about his whitespace if it were google-striped whitespace at issue. But, when I commented upon the lack of whitespace in his code, I said B> Whitespace is a good thing. Python needs it horizontally, but B> you can (and, IMHO, should) employ vertical whitespace to chunk B> up the code. So, it is a different issue. > I use gmail to collect this kind of email and using the recent thread > entitle "Reading Tutor with gmail: monospace fonts" have managed to > make my mail monospace, which makes it a lot easier to read. None of > the whitespace was stripped in my mail, and the style looked fine. That is good to know; I won't worry next time. > In fact, by littering it with '.' you are making it more of a task to run > this script, as you have to strip all the '.' out first - a real pain. A bummer, yes. And one to blame on google groups -- it is much less of a pain than loosing all leading whitespace. But, not too much a pain, either (we are programming here, right ;-) : <untested code> # assuming the code has been saved to a .py file whose lines # are available for iteration in python_file stripped_lines = [] for line in python_file: if line.startswith('.'): line = line[1:] stripped_lines.append(line) # write the stripped_line to the original .py file, and you're # good to go. </code> Best, Brian vdB From jeffshannon at gmail.com Sun Mar 6 10:42:11 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Sun Mar 6 10:42:16 2005 Subject: [Tutor] Linked List In-Reply-To: <20050305142041.7620.qmail@web53807.mail.yahoo.com> References: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> <20050305142041.7620.qmail@web53807.mail.yahoo.com> Message-ID: <5d0204a1050306014228206a09@mail.gmail.com> On Sat, 5 Mar 2005 06:20:40 -0800 (PST), Shitiz Bansal <shitizb@yahoo.com> wrote: > In order to explain wat my problem is, here is an > example code. Its not exactly what I am doing, I am > using multiple threads and a rather complicated code > so try and understand the sense rather than the code > itself. > > >>> myls=range(50) > >>> for i in myls: > print i > if i==20: > myls.insert(5,5) > > The point is, the list(both size and elements) is > changing even as it is being operated upon. My first thought was to say, "Use a queue.Queue." But it appears that you need to be able to do more than just add items at the end of the queue. I suspect that what you need is along the lines of a "priority queue". That is, something that works approximately like a queue, but when you add items to it, you also specify a priority for them. Then, when you retrieve an item from the queue, what you get is not necessarily the first-inserted item, but rather the item with highest priority. You might want to check the Cookbook to see if there's a priority queue recipe there. If not, I suspect that Google can be convinced to yield something... Jeff Shannon From pythontut at pusspaws.net Sun Mar 6 10:49:43 2005 From: pythontut at pusspaws.net (Dave S) Date: Sun Mar 6 10:49:51 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem Message-ID: <422AD237.5030205@pusspaws.net> Hello, I need to generate a list 2d matrix of the kind ... [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']] except its dimensions need to be 7 x 75. I thought I had it sorted with map2 = [ [''] *7 ] *75 until the coding screwed up & I realised I had 75 references to the same list :-( so I thought I would be clever with ... >>> a=[0]*5 >>> a [0, 0, 0, 0, 0] >>> b=[a[:]]*5 same problem. It seems realy simple but how do I generate a 7 x 75 list matrix ? Dave Oh PS Is there a more elegant solution to if string == 'sun' or string == 'mon' or string == 'tue' or string == 'wed' or string == 'thu' or string == 'fri' or string == 'sat': the above works but any suggestions would be welcome :-) From jeffshannon at gmail.com Sun Mar 6 11:00:52 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Sun Mar 6 11:00:55 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem In-Reply-To: <422AD237.5030205@pusspaws.net> References: <422AD237.5030205@pusspaws.net> Message-ID: <5d0204a1050306020033cae2e5@mail.gmail.com> On Sun, 06 Mar 2005 09:49:43 +0000, Dave S <pythontut@pusspaws.net> wrote: > I need to generate a list 2d matrix of the kind ... > > [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', > '', '', '', ''], ['', '', '', '', '']] > > except its dimensions need to be 7 x 75. I thought I had it sorted with > > map2 = [ [''] *7 ] *75 > > until the coding screwed up & I realised I had 75 references to the same > list :-( Try: map2 = [['']*7 for n in range(75)] The list comprehension will execute ['']*7 each iteration, creating a new list instead of just creating new references to the same list. > Oh PS > > Is there a more elegant solution to > > if string == 'sun' or string == 'mon' or string == 'tue' or string == > 'wed' or string == 'thu' or string == 'fri' or string == 'sat': Try: if string in ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']: (Or perhaps look into using the datetime module, depending on how detailed your needs are.) Jeff Shannon From pythontut at pusspaws.net Sun Mar 6 11:37:13 2005 From: pythontut at pusspaws.net (Dave S) Date: Sun Mar 6 11:37:22 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem In-Reply-To: <5d0204a1050306020033cae2e5@mail.gmail.com> References: <422AD237.5030205@pusspaws.net> <5d0204a1050306020033cae2e5@mail.gmail.com> Message-ID: <422ADD59.6030001@pusspaws.net> Jeff Shannon wrote: >On Sun, 06 Mar 2005 09:49:43 +0000, Dave S <pythontut@pusspaws.net> wrote: > > > >>I need to generate a list 2d matrix of the kind ... >> >>[['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', >>'', '', '', ''], ['', '', '', '', '']] >> >>except its dimensions need to be 7 x 75. I thought I had it sorted with >> >>map2 = [ [''] *7 ] *75 >> >>until the coding screwed up & I realised I had 75 references to the same >>list :-( >> >> > >Try: > >map2 = [['']*7 for n in range(75)] > >The list comprehension will execute ['']*7 each iteration, creating a >new list instead of just creating new references to the same list. > > > > >>Oh PS >> >>Is there a more elegant solution to >> >>if string == 'sun' or string == 'mon' or string == 'tue' or string == >>'wed' or string == 'thu' or string == 'fri' or string == 'sat': >> >> > >Try: > >if string in ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']: > >(Or perhaps look into using the datetime module, depending on how >detailed your needs are.) > >Jeff Shannon >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > Many thanks Dave :-) :-) :-) :-) From maxnoel_fr at yahoo.fr Sun Mar 6 13:42:35 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Mar 6 13:42:43 2005 Subject: [Tutor] 2d list matrix 7 x 75 problem In-Reply-To: <422AD237.5030205@pusspaws.net> References: <422AD237.5030205@pusspaws.net> Message-ID: <7fdc8d047bf956e1c0b6c8fb4d43a1c8@yahoo.fr> On Mar 6, 2005, at 09:49, Dave S wrote: > so I thought I would be clever with ... > >>> a=[0]*5 > >>> a > [0, 0, 0, 0, 0] > >>> b=[a[:]]*5 > > same problem. > > It seems realy simple but how do I generate a 7 x 75 list matrix ? > > Dave Try this: >>> a = [''] * 5 >>> b = [a[:] for i in range(5)] >>> b [['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', ''], ['', '', '', '', '']] >>> b[0] is b[1] False List comprehensions. Gotta love 'em... ^^ > Is there a more elegant solution to > > if string == 'sun' or string == 'mon' or string == 'tue' or string == > 'wed' or string == 'thu' or string == 'fri' or string == 'sat': Yes, there is. if a in ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'): (also works with a list or a dictionary) -- 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?" From alan.gauld at freenet.co.uk Sun Mar 6 16:54:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 6 16:53:05 2005 Subject: [Tutor] (no subject) References: <d082fff805030407435e6ae83c@mail.gmail.com><42289774.6010607@po-box.mcgill.ca><c7ff3855050305233810d4f08a@mail.gmail.com> <c7ff3855050305234132f8bc9f@mail.gmail.com> Message-ID: <019b01c52264$b89d2eb0$1cd28751@xp> > Is the tutor list mirrored on usenet such as google groups? I've > searched and not found it. Nope, the archives are available but there is no usenet mirroe. > I think it's a bit harsh to blame the style > on a client that strips white-space, where he has no control over it. > Are we not better off using another client? Unfortunately there seem to be several clients that do this. And in fat even clients that don;t do it can be configured to do so! It seems to be particularly true of HTML based mail tools, yet another reason to avoid HTML mail!. > the whitespace was stripped in my mail, and the style looked fine. In > fact, by littering it with '.' you are making it more of a task to run > this script, as you have to strip all the '.' out first - a real pain. Most decent text editors can do a search/replace on the start of line, :.,%s/^\.// in vim for example... But you are right, it does clutter it up, but rather that than lose the all important formatting due to some rogue email client (or even server in some cases!) Alan G. From jfouhy at paradise.net.nz Sun Mar 6 19:07:45 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Sun Mar 6 19:07:42 2005 Subject: [Tutor] Linked List In-Reply-To: <5d0204a1050306014228206a09@mail.gmail.com> References: <002201c5211f$cb9660e0$a95428cf@JSLAPTOP> <20050305142041.7620.qmail@web53807.mail.yahoo.com> <5d0204a1050306014228206a09@mail.gmail.com> Message-ID: <422B46F1.9040404@paradise.net.nz> Jeff Shannon wrote: > You might want to check the Cookbook to see if there's a priority > queue recipe there. If not, I suspect that Google can be convinced to > yield something... From the bisect module docs: import Queue, bisect class PriorityQueue(Queue.Queue): def _put(self, item): bisect.insort(self.queue, item) # usage queue = PriorityQueue(0) queue.put((2, "second")) queue.put((1, "first")) queue.put((3, "third")) priority, value = queue.get() -- John. From amonroe at columbus.rr.com Sun Mar 6 19:39:32 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Mar 6 19:40:16 2005 Subject: [Tutor] (no subject) In-Reply-To: <019b01c52264$b89d2eb0$1cd28751@xp> References: <d082fff805030407435e6ae83c@mail.gmail.com> <42289774.6010607@po-box.mcgill.ca> <c7ff3855050305233810d4f08a@mail.gmail.com> <c7ff3855050305234132f8bc9f@mail.gmail.com> <019b01c52264$b89d2eb0$1cd28751@xp> Message-ID: <7541500466.20050306133932@columbus.rr.com> >> Is the tutor list mirrored on usenet such as google groups? I've >> searched and not found it. > Nope, the archives are available but there is no usenet mirroe. What about this: http://dir.gmane.org/gmane.comp.python.tutor Alan From apple_py at biz-experts.net Sun Mar 6 20:28:43 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Sun Mar 6 20:28:45 2005 Subject: [Tutor] MySQLdb error while inserting records Message-ID: <422B59EB.2030907@biz-experts.net> Hi all, I consider myself fairly proficient with SQL, but I'm still getting the hang of the MySQL API. I am working through the examples in "Open Source Web Development with LAMP: Using Linux, Apache, MySQL, Perl, and PHP" by James Lee and Brent Ware, and trying to make the third "P" to be Python. :) There is an example in the book which is written in Perl, used to insert new records to MySQL. I tried it as it is written and it works fine. I have migrated to Python another example that gets all of the records in the age_information table (SELECT query), and it is getting the data successfully. However, I am having problems with the program to insert records. The following is my modified code in Python: ------------------------------ 1 #!/usr/bin/python 2 # connect.py 3 4 import sys 5 import MySQLdb 6 7 if len(sys.argv) != 4: 8 print "You have to enter lastname, firstname and age\n" 9 sys.exit(1) 10 11 # This is to change the age type from str to int 12 last, first, strAge = sys.argv[1:] 13 age = int(strAge) 14 15 # Some debugging lines 16 print last, first, age 17 print type(last), type(first), type(age) 18 print 19 #sys.exit() 20 21 22 try: 23 conn = MySQLdb.connect(host='localhost', 24 user='apache', passwd='LampIsCool', db='people') 25 except: 26 print "Could not connect\n" 27 sys.exit(1) 28 29 c = conn.cursor() 30 31 # prepare the SQL, exit() if the preparation fails 32 query = ''' 33 INSERT INTO age_information 34 (lastname, firstname, age) 35 VALUES (?, ?, ?) 36 ''' 37 38 # execute the SQL 39 records = c.execute(query, (last, first, age)) 40 if records >= 1: 41 print "Succesfully inserted %d records" % records 42 else: 43 print "Could not insert anything, sorry." 44 45 c.commit() 46 c.close() 47 conn.close() 48 ------------------------------ Executing the script from the command line, I get the following output: ------------------------------ $ ./insert.py Cool Joe 13 Cool Joe 13 <type 'str'> <type 'str'> <type 'int'> Traceback (most recent call last): File "./insert.py", line 39, in ? records = c.execute(query, (last, first, age)) File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 95, in execute return self._execute(query, args) File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 110, in _execute self.errorhandler(self, TypeError, m) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue TypeError: not all arguments converted during string formatting ------------------------------ I was getting this same error so I entered lines 12 and 13 to change the age from type string to integer. No change. Do you know what am I missing? Thanks to all. -- Victor Bouffier Finance Manager www.grupoandersons.com From kent37 at tds.net Sun Mar 6 20:40:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 6 20:40:53 2005 Subject: [Tutor] MySQLdb error while inserting records In-Reply-To: <422B59EB.2030907@biz-experts.net> References: <422B59EB.2030907@biz-experts.net> Message-ID: <422B5CBC.10907@tds.net> Victor Bouffier wrote: > > Hi all, > > I consider myself fairly proficient with SQL, but I'm still getting the > hang of the MySQL API. I am working through the examples in "Open Source > Web Development with LAMP: Using Linux, Apache, MySQL, Perl, and PHP" by > James Lee and Brent Ware, and trying to make the third "P" to be Python. :) > > There is an example in the book which is written in Perl, used to insert > new records to MySQL. I tried it as it is written and it works fine. I > have migrated to Python another example that gets all of the records in > the age_information table (SELECT query), and it is getting the data > successfully. However, I am having problems with the program to insert > records. According to this page http://sourceforge.net/docman/display_doc.php?docid=26238&group_id=22307 MySQLdb uses the 'format' style of passing parameters to SQL, not the questionmark style you have used below. So change query to > 32 query = ''' > 33 INSERT INTO age_information > 34 (lastname, firstname, age) > 35 VALUES (%s, %s, %s) > 36 ''' Kent > > The following is my modified code in Python: > > ------------------------------ > 1 #!/usr/bin/python > 2 # connect.py > 3 > 4 import sys > 5 import MySQLdb > 6 > 7 if len(sys.argv) != 4: > 8 print "You have to enter lastname, firstname and age\n" > 9 sys.exit(1) > 10 > 11 # This is to change the age type from str to int > 12 last, first, strAge = sys.argv[1:] > 13 age = int(strAge) > 14 > 15 # Some debugging lines > 16 print last, first, age > 17 print type(last), type(first), type(age) > 18 print > 19 #sys.exit() > 20 > 21 > 22 try: > 23 conn = MySQLdb.connect(host='localhost', > 24 user='apache', passwd='LampIsCool', db='people') > 25 except: > 26 print "Could not connect\n" > 27 sys.exit(1) > 28 > 29 c = conn.cursor() > 30 > 31 # prepare the SQL, exit() if the preparation fails > 32 query = ''' > 33 INSERT INTO age_information > 34 (lastname, firstname, age) > 35 VALUES (?, ?, ?) > 36 ''' > 37 > 38 # execute the SQL > 39 records = c.execute(query, (last, first, age)) > 40 if records >= 1: > 41 print "Succesfully inserted %d records" % records > 42 else: > 43 print "Could not insert anything, sorry." > 44 > 45 c.commit() > 46 c.close() > 47 conn.close() > 48 > ------------------------------ > > Executing the script from the command line, I get the following output: > > > ------------------------------ > $ ./insert.py Cool Joe 13 > Cool Joe 13 > <type 'str'> <type 'str'> <type 'int'> > > Traceback (most recent call last): > File "./insert.py", line 39, in ? > records = c.execute(query, (last, first, age)) > File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 95, in > execute > return self._execute(query, args) > File "/usr/lib/python2.3/site-packages/MySQLdb/cursors.py", line 110, > in _execute > self.errorhandler(self, TypeError, m) > File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line > 33, in defaulterrorhandler > raise errorclass, errorvalue > TypeError: not all arguments converted during string formatting > ------------------------------ > > I was getting this same error so I entered lines 12 and 13 to change the > age from type string to integer. No change. > Do you know what am I missing? > > Thanks to all. > From apple_py at biz-experts.net Mon Mar 7 01:09:53 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Mon Mar 7 01:10:07 2005 Subject: [Tutor] MySQLdb error while inserting records In-Reply-To: <422B5CBC.10907@tds.net> References: <422B59EB.2030907@biz-experts.net> <422B5CBC.10907@tds.net> Message-ID: <422B9BD1.4000701@biz-experts.net> Yes! That did it. I got confused since Programming Python mentions the '?' for arguments, although I failed to notice it was just used as an example. Actual identifiers could vary depending on the database. Thanks a lot Kent. Kent Johnson wrote: > Victor Bouffier wrote: > >> >> Hi all, >> >> I consider myself fairly proficient with SQL, but I'm still getting >> the hang of the MySQL API. I am working through the examples in "Open >> Source Web Development with LAMP: Using Linux, Apache, MySQL, Perl, >> and PHP" by James Lee and Brent Ware, and trying to make the third >> "P" to be Python. :) >> >> There is an example in the book which is written in Perl, used to >> insert new records to MySQL. I tried it as it is written and it works >> fine. I have migrated to Python another example that gets all of the >> records in the age_information table (SELECT query), and it is >> getting the data successfully. However, I am having problems with the >> program to insert records. > > > According to this page > http://sourceforge.net/docman/display_doc.php?docid=26238&group_id=22307 > MySQLdb uses the 'format' style of passing parameters to SQL, not the > questionmark style you have used below. So change query to > > 32 query = ''' > > 33 INSERT INTO age_information > > 34 (lastname, firstname, age) > > 35 VALUES (%s, %s, %s) > > 36 ''' > > Kent > -- Victor Bouffier Finance Manager www.grupoandersons.com From tameyer at ihug.co.nz Mon Mar 7 01:18:55 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Mar 7 01:19:08 2005 Subject: [Tutor] Intro for interfacing with Microsoft Access? In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E802419D3C@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFF28@its-xchg4.massey.ac.nz> > Does anyone know of any online resource that explains how to > interface to Microsoft Access via Python, where the intended > audience is someone who knows Python, but not the Microsoft innards? These two pages are quite good: <http://starship.python.net/crew/bwilk/access.html> <http://www.ecp.cc/pyado.html> =Tony.Meyer From kent37 at tds.net Mon Mar 7 01:29:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 01:29:50 2005 Subject: [Tutor] Intro for interfacing with Microsoft Access? In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFF28@its-xchg4.massey.ac.nz> References: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFF28@its-xchg4.massey.ac.nz> Message-ID: <422BA07A.30106@tds.net> Tony Meyer wrote: >>Does anyone know of any online resource that explains how to >>interface to Microsoft Access via Python, where the intended >>audience is someone who knows Python, but not the Microsoft innards? > > > These two pages are quite good: > > <http://starship.python.net/crew/bwilk/access.html> > <http://www.ecp.cc/pyado.html> adodbapi gives a Python DB-API interface to ADO. It seems to work with Access. http://sourceforge.net/projects/adodbapi Kent > > =Tony.Meyer > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tameyer at ihug.co.nz Mon Mar 7 01:53:02 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Mon Mar 7 01:53:11 2005 Subject: [Tutor] Intro for interfacing with Microsoft Access? In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E80245AA65@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFF2A@its-xchg4.massey.ac.nz> [Terry Carroll] >>> Does anyone know of any online resource that explains how to >>> interface to Microsoft Access via Python, where the intended >>> audience is someone who knows Python, but not the Microsoft innards? [Tony Meyer] >> These two pages are quite good: >> >> <http://starship.python.net/crew/bwilk/access.html> >> <http://www.ecp.cc/pyado.html> [Terry Carroll] > Thanks. Unfortunately, both of those seem to assume you know > Python and the Win APIs, but not how to connect the, For > someone who doesn't know the APIs, they're actually not very helpful. The second link has very simple steps - you basically just retype the code from steps 1 to 3 and you're all connected. Then pick one of the following steps, depending on what you want to (read, insert, etc), and retype the code from there. Once you have the recordset object (steps 1-3), you can easily modify the existing examples to do whatever you want just by referencing the reference material in Access itself (I forget what it's called - the object reference material that you get to via the macro stuff). When I first needed to work with Access, I knew nothing about ADO or coding Access, but something about writing Python, and this got me up and running very easily. > But I do appreciate you taking the time to point them out. No worries. =Tony.Meyer From GLS33782 at msn.com Sat Mar 5 19:16:57 2005 From: GLS33782 at msn.com (Gregory Sexton) Date: Mon Mar 7 02:27:14 2005 Subject: [Tutor] help Message-ID: <BAY4-DAV7F066591E7489E809F2F3805D0@phx.gbl> Is there a forum for the complete beginning Python student? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050305/c305c807/attachment.html From GLS33782 at msn.com Sun Mar 6 02:50:22 2005 From: GLS33782 at msn.com (Gregory Sexton) Date: Mon Mar 7 02:27:16 2005 Subject: [Tutor] help Message-ID: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> Does sp1 and sp2 in Wwindows XP block certain python commands? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050305/26c130ab/attachment.htm From dyoo at hkn.eecs.berkeley.edu Mon Mar 7 02:48:04 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 7 02:48:07 2005 Subject: [Tutor] Linked List In-Reply-To: <5d0204a1050306014228206a09@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503061744550.22470-100000@hkn.eecs.berkeley.edu> > > >>> myls=range(50) > > >>> for i in myls: > > print i > > if i==20: > > myls.insert(5,5) > > > > The point is, the list(both size and elements) is > > changing even as it is being operated upon. > > My first thought was to say, "Use a queue.Queue." But it appears that > you need to be able to do more than just add items at the end of the > queue. > > I suspect that what you need is along the lines of a "priority queue". > That is, something that works approximately like a queue, but when you > add items to it, you also specify a priority for them. Then, when you > retrieve an item from the queue, what you get is not necessarily the > first-inserted item, but rather the item with highest priority. Priority queues are already a part of the Standard Library in the 'heapq' module: http://www.python.org/doc/lib/module-heapq.html We used this as part of a program that showed an example of a discrete simulation: http://aspn.activestate.com/ASPN/Mail/Message/python-tutor/2503815 Best of wishes! From kent37 at tds.net Mon Mar 7 03:19:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 03:19:50 2005 Subject: [Tutor] help In-Reply-To: <BAY4-DAV7F066591E7489E809F2F3805D0@phx.gbl> References: <BAY4-DAV7F066591E7489E809F2F3805D0@phx.gbl> Message-ID: <422BBA3F.3020909@tds.net> Gregory Sexton wrote: > Is there a forum for the complete beginning Python student? Yes, this is it. Kent From kent37 at tds.net Mon Mar 7 03:20:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 03:20:35 2005 Subject: [Tutor] help In-Reply-To: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> References: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> Message-ID: <422BBA6F.6020304@tds.net> Gregory Sexton wrote: > Does sp1 and sp2 in Wwindows XP block certain python commands? I haven't heard of any; is there a command you are having trouble with? Kent From ravikishants at yahoo.com Mon Mar 7 06:35:16 2005 From: ravikishants at yahoo.com (Ravi Kishan T.S) Date: Mon Mar 7 06:35:23 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: 6667 Message-ID: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Hi! I am working on Python on Windows XP, Iam being able to create or generate an Excel file using python, but unable to write the excel file with the graphs in it. I want to represent some data in the form of Graph (Gant chart, Pie chart and all), Can somebody help me with this. Regards Ravi __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050306/9e324331/attachment.htm From ravikishants at yahoo.com Mon Mar 7 06:35:16 2005 From: ravikishants at yahoo.com (Ravi Kishan T.S) Date: Mon Mar 7 06:35:24 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: 6667 Message-ID: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Hi! I am working on Python on Windows XP, Iam being able to create or generate an Excel file using python, but unable to write the excel file with the graphs in it. I want to represent some data in the form of Graph (Gant chart, Pie chart and all), Can somebody help me with this. Regards Ravi __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050306/9e324331/attachment.html From cyresse at gmail.com Mon Mar 7 11:48:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Mar 7 11:48:12 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: <20050307053516.48114.qmail@web50402.mail.yahoo.com> References: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Message-ID: <f2ff2d05030702481f042c58@mail.gmail.com> Erm.... win32api? On Sun, 6 Mar 2005 21:35:16 -0800 (PST), Ravi Kishan T.S <ravikishants@yahoo.com> wrote: > Hi! > > I am working on Python on Windows XP, Iam being able to create or generate > an Excel file using python, but unable to write the excel file with the > graphs in it. I want to represent some data in the form of Graph (Gant > chart, Pie chart and all), > > Can somebody help me with this. > > Regards > Ravi > > > > __________________________________________________ > 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 > > > -- '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. From kent37 at tds.net Mon Mar 7 17:46:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 7 17:46:52 2005 Subject: [Tutor] help In-Reply-To: <BAY4-DAV1363ECF5CBF09F34F87ECB805F0@phx.gbl> References: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> <422BBA6F.6020304@tds.net> <BAY4-DAV1363ECF5CBF09F34F87ECB805F0@phx.gbl> Message-ID: <422C8572.5030605@tds.net> Gregory Sexton wrote: > Thanks for the help! Sorry for the trivial questions, but I guess we all > have to start somewhere. Beginning python student, OS Windows XP,using > Python 2.4. Also novice to programming. I cant get the "/a" command to > work. I don't know what the "/a" command is, please give more details. I get an elongated 0 in my Python interpreter, but no sound. I don't know what you mean by that either. Some tips for getting help from this list: - post actual code. It's OK if it's broken, we will help fix it - post actual error messages including the entire stack trace (everything from the line that says "Traceback (most recent call last)"). Python error messages have a lot of useful content that can help someone else diagnose a problem. - please send replies to the list so everyone can benefit and help Kent By > the way I am learning from a book entitled "Python Programming for the > absolute beginner" by Michael Dawson. Thanks again. > From maxnoel_fr at yahoo.fr Mon Mar 7 17:52:54 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Mar 7 17:53:00 2005 Subject: [Tutor] help In-Reply-To: <422C8572.5030605@tds.net> References: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> <422BBA6F.6020304@tds.net> <BAY4-DAV1363ECF5CBF09F34F87ECB805F0@phx.gbl> <422C8572.5030605@tds.net> Message-ID: <e03f941026e0b0831137a5804e399c3f@yahoo.fr> On Mar 7, 2005, at 16:46, Kent Johnson wrote: > Gregory Sexton wrote: >> Thanks for the help! Sorry for the trivial questions, but I guess we >> all have to start somewhere. Beginning python student, OS Windows >> XP,using Python 2.4. Also novice to programming. I cant get the >> "/a" command to work. > > I don't know what the "/a" command is, please give more details. I find it extremely unlikely that Python, even in its Windows incarnation, support a "/a" switch, or any slash switch for that matter. Python is a UNIX program -- its switches start with one or two dashes, as the slash is the directory separator. -- 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?" From klappnase at freenet.de Mon Mar 7 18:33:45 2005 From: klappnase at freenet.de (Michael Lange) Date: Mon Mar 7 18:30:37 2005 Subject: [Tutor] help In-Reply-To: <422C8572.5030605@tds.net> References: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> <422BBA6F.6020304@tds.net> <BAY4-DAV1363ECF5CBF09F34F87ECB805F0@phx.gbl> <422C8572.5030605@tds.net> Message-ID: <20050307183345.1bfc23bf.klappnase@freenet.de> On Mon, 07 Mar 2005 11:46:42 -0500 Kent Johnson <kent37@tds.net> wrote: > Gregory Sexton wrote: > > Thanks for the help! Sorry for the trivial questions, but I guess we all > > have to start somewhere. Beginning python student, OS Windows XP,using > > Python 2.4. Also novice to programming. I cant get the "/a" command to > > work. > > I don't know what the "/a" command is, please give more details. > > I get an elongated 0 in my Python interpreter, but no sound. > Sound? Maybe you meant print "\a" ? Michael From stygian at tesco.net Mon Mar 7 18:44:30 2005 From: stygian at tesco.net (glen) Date: Mon Mar 7 18:43:12 2005 Subject: [Tutor] help Message-ID: <1110217470.2915.18.camel@localhost> Gregory Sexton wrote: > Thanks for the help! Sorry for the trivial questions, but I guess we all > have to start somewhere. Beginning python student, OS Windows XP,using > Python 2.4. Also novice to programming. I cant get the "/a" command to > work. Shouldn't it be "\a", and it won't work from IDLE. You can save the file with the .py extension, and double click it from the file manager and it works fine. I booted XP JUST to test it :) > the way I am learning from a book entitled "Python Programming for the > absolute beginner" by Michael Dawson. Thanks again. On page 25 there is a paragraph called 'trap' that warns about this. Hope this has helped, a little. Glen From dyoo at hkn.eecs.berkeley.edu Mon Mar 7 19:11:18 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 7 19:11:24 2005 Subject: [Tutor] How to get graphical representation in Excel file In-Reply-To: <f2ff2d05030702481f042c58@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503071008570.14759-100000@hkn.eecs.berkeley.edu> [Ravi] > > I am working on Python on Windows XP, Iam being able to create or > > generate an Excel file using python, but unable to write the excel > > file with the graphs in it. I want to represent some data in the form > > of Graph (Gant chart, Pie chart and all), [Liam] > Erm.... win32api? Hi Ravi, As Liam mentions, your question is really specific to win32api material; I'm not sure if we at Tutor will be as expert about this topic as the folks on the win32api list. Try asking your question on the win32api list: http://mail.python.org/mailman/listinfo/python-win32 Best of wishes to you! From alan.gauld at freenet.co.uk Mon Mar 7 19:14:56 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 7 19:14:42 2005 Subject: [Tutor] help References: <BAY4-DAV7F066591E7489E809F2F3805D0@phx.gbl> Message-ID: <002b01c52341$91aba9c0$dbc98751@xp> > Is there a forum for the complete beginning Python student? Yes, this is it! Welcome. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Mar 7 19:15:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 7 19:15:43 2005 Subject: [Tutor] help References: <BAY4-DAV7C5B99C86F2802C223AE1805E0@phx.gbl> Message-ID: <003901c52341$b7511d40$dbc98751@xp> > Does sp1 and sp2 in Wwindows XP block certain python commands? Nope. Although SP2 does various strange things that could cause some bits of Python to behave strangely but there are plenty people using SP2 and Python suvccessfully. Alan G. From alan.gauld at freenet.co.uk Mon Mar 7 19:18:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 7 19:18:48 2005 Subject: [Tutor] How to get graphical representation in Excel file References: <20050307053516.48114.qmail@web50402.mail.yahoo.com> Message-ID: <004d01c52342$1e91c310$dbc98751@xp> > I am working on Python on Windows XP, Iam being able to create or > generate an Excel file using python, but unable to write the excel > file with the graphs in it. I want to represent some data in the > form of Graph (Gant chart, Pie chart and all), Creating graphs in Excel is best done within Excel! You can do it using the COM inteface and the Python winall package but its not simple unless you are very familiar with COM. Does it have to be in Excel? It might be easier to draw the graphs direct from the data in Python? Alan G. From amonroe at columbus.rr.com Tue Mar 8 00:47:38 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Mar 8 00:48:25 2005 Subject: [Tutor] Can you get python to force a number to remain 32 bit instead of autoconverting to type 'long'? Message-ID: <30646386554.20050307184738@columbus.rr.com> I tried to convert this pseudocode function IntNoise(32-bit integer: x) x = (x<<13) ^ x; return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0); end IntNoise function from this website http://freespace.virgin.net/hugo.elias/models/m_perlin.htm to python. But it seems to rely on wraparound within the 32 bit int. Can you duplicate this behavior in python? Alan From apple_py at biz-experts.net Tue Mar 8 02:30:19 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Tue Mar 8 02:30:27 2005 Subject: [Tutor] Paradox database files Message-ID: <422D002B.6030403@biz-experts.net> Hi all. Does anybody know of a Python module to read from Paradox database files? I don't need to write back to the files. These files are being exported using a proprietary application and I need to parse them to extract transaction information. I found something about ODBC being able to connect to several database types, but I am not even sure how this would work with Paradox. Any OS solution you suggest works fine for me, since I have access to both a unix (linux) box and Python on Windows too. Thanks. -- Victor Bouffier Finance Manager www.grupoandersons.com From dyoo at hkn.eecs.berkeley.edu Tue Mar 8 02:51:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 8 02:51:49 2005 Subject: [Tutor] Paradox database files In-Reply-To: <422D002B.6030403@biz-experts.net> Message-ID: <Pine.LNX.4.44.0503071740280.12598-100000@hkn.eecs.berkeley.edu> On Mon, 7 Mar 2005, Victor Bouffier wrote: > Does anybody know of a Python module to read from Paradox database > files? I don't need to write back to the files. These files are being > exported using a proprietary application and I need to parse them to > extract transaction information. Hi Victor, You might be interested in 'pxview': http://pxlib.sourceforge.net/pxview.html which can extract CSV-formatted files out of Paradox Database files. Once you have your data in CSV format, then Python's "csv" module can come into play: http://www.python.org/doc/lib/module-csv.html Alternatively, you might be able to use the pxlib Python bindings directly. According to: http://pxlib.sourceforge.net/documentation.php?manpage=pxlib a Python binding exists somewhere out there, though I haven't been able to find it yet... ok, found it, but it appears you might need to check it out of CVS: http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ so this might not be as easy to use right out of the box. From bgailer at alum.rpi.edu Mon Mar 7 19:31:26 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Mar 8 03:51:56 2005 Subject: ****SPAM(11.8)**** Re: [Tutor] returning table elements with Beautiful Soup In-Reply-To: <014c01c5218e$7a6291c0$1cd28751@xp> References: <42293021.1030309@fastmail.fm> <422941FF.9070205@tds.net> <014c01c5218e$7a6291c0$1cd28751@xp> Message-ID: <6.1.2.0.0.20050307103102.0357d7a8@mail.mric.net> At 06:20 AM 3/5/2005, Alan Gauld wrote: > > > I'm trying to use Beautiful Soup to scrape some data out of an >HTML > > > table. I can do this using > >A new one on me, but Beautiful Soup looks very interesting. I've just >downloaded it. From where? My Google search does not help. >Thanks for pointing it out. > >Alan G. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 510 558 3275 home 303 442 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050307/14d8722f/attachment-0001.html From kent37 at tds.net Tue Mar 8 04:06:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 8 04:06:19 2005 Subject: ****SPAM(11.8)**** Re: [Tutor] returning table elements with Beautiful Soup In-Reply-To: <6.1.2.0.0.20050307103102.0357d7a8@mail.mric.net> References: <42293021.1030309@fastmail.fm> <422941FF.9070205@tds.net> <014c01c5218e$7a6291c0$1cd28751@xp> <6.1.2.0.0.20050307103102.0357d7a8@mail.mric.net> Message-ID: <422D16A5.4040609@tds.net> Bob Gailer wrote: > At 06:20 AM 3/5/2005, Alan Gauld wrote: > >> > > I'm trying to use Beautiful Soup to scrape some data out of an >> HTML >> > > table. I can do this using >> >> A new one on me, but Beautiful Soup looks very interesting. I've just >> downloaded it. > > > From where? My Google search does not help. Actually it's the second listing if you Google 'Beautiful Soup'. http://www.crummy.com/software/BeautifulSoup/ Kent From apple_py at biz-experts.net Tue Mar 8 03:53:07 2005 From: apple_py at biz-experts.net (apple_py) Date: Tue Mar 8 04:53:12 2005 Subject: [Tutor] Paradox database files Message-ID: <20050308035307.8666.qmail@thehosting123.com> Hi Danny, Thanks a lot for your help. I have not been able to try it out, but I will first thing tomorrow. It seems that this is just what I need. I love this forum. Thanks to all. Victor -------Original Message------- > From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> > Subject: Re: [Tutor] Paradox database files > Sent: 08 Mar 2005 01:51:35 > > On Mon, 7 Mar 2005, Victor Bouffier wrote: > > > Does anybody know of a Python module to read from Paradox database > > files? I don't need to write back to the files. These files are being > > exported using a proprietary application and I need to parse them to > > extract transaction information. > > > Hi Victor, > > You might be interested in 'pxview': > > http://pxlib.sourceforge.net/pxview.html > > which can extract CSV-formatted files out of Paradox Database files. Once > you have your data in CSV format, then Python's "csv" module can come into > play: > > http://www.python.org/doc/lib/module-csv.html > > > Alternatively, you might be able to use the pxlib Python bindings > directly. According to: > > http://pxlib.sourceforge.net/documentation.php?manpage=pxlib > > a Python binding exists somewhere out there, though I haven't been able to > find it yet... ok, found it, but it appears you might need to check it out > of CVS: > > http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ > > so this might not be as easy to use right out of the box. -------Original Message------- From apple_py at biz-experts.net Tue Mar 8 17:06:50 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Tue Mar 8 17:07:06 2005 Subject: [Tutor] Paradox database files In-Reply-To: <20050308035307.8666.qmail@thehosting123.com> References: <20050308035307.8666.qmail@thehosting123.com> Message-ID: <422DCD9A.4060608@biz-experts.net> Hi all, I know this is OT from Python, but does anybody know how to fix my library issues. I get some awkward dependencies issues from these pylib libraries. # rpm -Uvh pxlib-0.4.3-1.i386.rpm error: Failed dependencies: libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386 but when I look into my libraries I find the necessary ones under /usr/lib: # ll /usr/lib/libbz2* -rwxr-xr-x 1 root root 67594 Jun 15 2004 /usr/lib/libbz2.a lrwxrwxrwx 1 root root 11 Feb 6 11:02 /usr/lib/libbz2.so -> libbz2.so.1 lrwxrwxrwx 1 root root 15 Feb 6 10:10 /usr/lib/libbz2.so.1 -> libbz2.so.1.0.2 lrwxrwxrwx 1 root root 24 Mar 8 09:41 /usr/lib/libbz2.so.1.0 -> /usr/lib/libbz2.so.1.0.2 -rwxr-xr-x 1 root root 71724 Jun 15 2004 /usr/lib/libbz2.so.1.0.2 I created the second-to-last symlink with no success. I also added '/usr/lib' to /etc/ld.so.conf as suggested in a newsgroup. I've got a Fedora Core3 with both apt and yum installed, and both tell me I've got the latest libraries (bzip2-libs). If you believe I should post my question elsewhere, please let me know. Thanks. Victor apple_py wrote: >-------Original Message------- > > >>From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> >>Subject: Re: [Tutor] Paradox database files >>Sent: 08 Mar 2005 01:51:35 >> >> On Mon, 7 Mar 2005, Victor Bouffier wrote: >> >> > Does anybody know of a Python module to read from Paradox database >> > files? I don't need to write back to the files. These files are being >> > exported using a proprietary application and I need to parse them to >> > extract transaction information. >> >> >> Hi Victor, >> >> You might be interested in 'pxview': >> >> http://pxlib.sourceforge.net/pxview.html >> >> which can extract CSV-formatted files out of Paradox Database files. Once >> you have your data in CSV format, then Python's "csv" module can come into >> play: >> >> http://www.python.org/doc/lib/module-csv.html >> >> >> Alternatively, you might be able to use the pxlib Python bindings >> directly. According to: >> >> http://pxlib.sourceforge.net/documentation.php?manpage=pxlib >> >> a Python binding exists somewhere out there, though I haven't been able to >> find it yet... ok, found it, but it appears you might need to check it out >> of CVS: >> >> http://cvs.sourceforge.net/viewcvs.py/pxlib/bindings/ >> >> so this might not be as easy to use right out of the box. >> >> >-------Original Message------- >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > -- Victor Bouffier Finance Manager www.grupoandersons.com From phthenry at iglou.com Tue Mar 8 17:21:29 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Tue Mar 8 17:20:14 2005 Subject: [Tutor] getting a webpage via python Message-ID: <20050308162129.GE2055@localhost.localdomain> Is there a simple way to get a web page with python? I have done no network programming with python before. My router (a Linksys 54G model) stores the IP/MAC addresss in a web page. There is no way for me to access them except through the web. Righ now, I am using this code: command = 'lynx -reload -auth %s:%s -source http://%s/DHCPTable.asp > %s' % ( self.__log_name, self.__log_password, self.__router_address, temp_out1) (exit_status, out_text) = commands.getstatusoutput(command) The lynx terminal browser dumps the raw HTML page to the out_text, and I can then parse it. I would like to make the code independent of lynx, if possible. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From ewald.ertl at hartter.com Tue Mar 8 17:28:46 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 8 17:28:50 2005 Subject: [Tutor] Paradox database files In-Reply-To: <422DCD9A.4060608@biz-experts.net> References: <20050308035307.8666.qmail@thehosting123.com> <422DCD9A.4060608@biz-experts.net> Message-ID: <20050308172846.00004032@sunray1> Hi Victor on Tue, 08 Mar 2005 10:06:50 -0600 Victor Bouffier <apple_py@biz-experts.net> wrote : --------------------------------------------------------------------------------------------- Victor Bouffier > Hi all, Victor Bouffier > I know this is OT from Python, but does anybody know how to fix my Victor Bouffier > library issues. I get some awkward dependencies issues from these pylib Victor Bouffier > libraries. Victor Bouffier > Victor Bouffier > # rpm -Uvh pxlib-0.4.3-1.i386.rpm Victor Bouffier > error: Failed dependencies: Victor Bouffier > libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386 Victor Bouffier > Victor Bouffier > but when I look into my libraries I find the necessary ones under /usr/lib: Victor Bouffier > Victor Bouffier > # ll /usr/lib/libbz2* Victor Bouffier > -rwxr-xr-x 1 root root 67594 Jun 15 2004 /usr/lib/libbz2.a Victor Bouffier > lrwxrwxrwx 1 root root 11 Feb 6 11:02 /usr/lib/libbz2.so -> libbz2.so.1 Victor Bouffier > lrwxrwxrwx 1 root root 15 Feb 6 10:10 /usr/lib/libbz2.so.1 -> Victor Bouffier > libbz2.so.1.0.2 Victor Bouffier > lrwxrwxrwx 1 root root 24 Mar 8 09:41 /usr/lib/libbz2.so.1.0 -> Victor Bouffier > /usr/lib/libbz2.so.1.0.2 Victor Bouffier > -rwxr-xr-x 1 root root 71724 Jun 15 2004 /usr/lib/libbz2.so.1.0.2 Victor Bouffier > Perhap's there is a problem with the RPM-Database. I don't know how rpm works internaly, but it controls somewhere in a "database", which packages are installed on the system. On an old SuSE-System I can search, to which package a file belongs rpm -q -f /usr/lib/libbz2.so bzip2-1.0.2-103 Here I see, that libbz2.so belongs to the bzip2-Package. The other way is to list the files belonging to a package: rpm -q -l bzip2-1.0.2-103 /usr/bin/bunzip2 /usr/bin/bzcat /usr/bin/bzip2 /usr/bin/bzip2recover /usr/include/bzlib.h /usr/lib/libbz2.a /usr/lib/libbz2.la /usr/lib/libbz2.so /usr/lib/libbz2.so.1 /usr/lib/libbz2.so.1.0.0 During the installation/update-Process, I think, rpm looks up, all dependencys mentioned in the rpm if they are installed on the system via the "database" where it logs, what is installed. Try if you can get a package to which your /usr/lib/libbz2.so.1 belongs. The other way is, to install the rpm-Package without depdency-check's, but this could result in the availability of the pxlib-Package, but it perhaps does not work. You've to test this, before you keep the package. "rpm -Uvh --nodeps" This should ignore the dependencies and install the package. ------------------- end ---------------------- HTH Ewald From eculpepper at hcc-care.com Tue Mar 8 17:30:49 2005 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Tue Mar 8 17:29:31 2005 Subject: [Tutor] getting a webpage via python Message-ID: <48CA63C679F03D4187762B7CE066AAD202D0AAB0@hccexchange.hcccorp.hcc-care.com> You could use the builtin modules like urllib2, httplib, or you could use John Lee's spifftastic module "mechanize". I use mechanize a lot for automating downloading files from various partner websites my company has relations with. http://docs.python.org/lib/module-httplib.html http://docs.python.org/lib/module-urllib2.html http://wwwsearch.sourceforge.net/mechanize/ Good luck. Eric Culpepper eculpepper@hcc-care.com -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Paul Tremblay Sent: Tuesday, March 08, 2005 10:21 AM To: python tutor Subject: [Tutor] getting a webpage via python Is there a simple way to get a web page with python? I have done no network programming with python before. My router (a Linksys 54G model) stores the IP/MAC addresss in a web page. There is no way for me to access them except through the web. Righ now, I am using this code: command = 'lynx -reload -auth %s:%s -source http://%s/DHCPTable.asp > %s' % ( self.__log_name, self.__log_password, self.__router_address, temp_out1) (exit_status, out_text) = commands.getstatusoutput(command) The lynx terminal browser dumps the raw HTML page to the out_text, and I can then parse it. I would like to make the code independent of lynx, if possible. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ewald.ertl at hartter.com Tue Mar 8 17:33:56 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 8 17:34:01 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <20050308162129.GE2055@localhost.localdomain> References: <20050308162129.GE2055@localhost.localdomain> Message-ID: <20050308173356.000000b0@sunray1> Hi Paul! As mentioned earlier by Kent in this group under the subject: Subject: Re: [Tutor] Downloading from http Mark Kels wrote: > On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. <keridee@jayco.net> wrote: > >>urllib or urllib2 or maybe httplib maybe? >> >> urlopen( url[, data]) > I'm sorry, but I didn't understood a thing (maybe its because of my > bad english, and mybe its because I'm just dumb :). Anyway, can you > give me a code example or a link to a tutorial that talks about this ? >>> from urllib import urlopen >>> u=urlopen('http://www.google.com') >>> d=u.read() >>> print d[:200] <html><head><meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"><title>Google</title><style><!-- body,td,a,p,.h{font-family:arial,sans-serif;} .h{font-size: 20px;} .q{color:#0000cc HTH Ewald From kent37 at tds.net Tue Mar 8 17:50:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 8 17:50:16 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <20050308162129.GE2055@localhost.localdomain> References: <20050308162129.GE2055@localhost.localdomain> Message-ID: <422DD7C4.1070300@tds.net> Paul Tremblay wrote: > Is there a simple way to get a web page with python? I have done no > network programming with python before. > > My router (a Linksys 54G model) stores the IP/MAC addresss in a web > page. There is no way for me to access them except through the web. > > Righ now, I am using this code: > > command = 'lynx -reload -auth %s:%s -source http://%s/DHCPTable.asp > %s' % ( > self.__log_name, self.__log_password, self.__router_address, temp_out1) > (exit_status, out_text) = commands.getstatusoutput(command) You can use urllib2 to do this. It is a little work to set it up to use Basic authentication. Here is an example (slightly modified from the urllib2 example page): import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password('realm', '127.0.0.1', 'username', 'password') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) print urllib2.urlopen('http://127.0.0.1/my/protected/page.html').read() Kent From apple_py at biz-experts.net Tue Mar 8 18:37:53 2005 From: apple_py at biz-experts.net (Victor Bouffier) Date: Tue Mar 8 18:38:08 2005 Subject: [Tutor] Paradox database files In-Reply-To: <20050308172846.00004032@sunray1> References: <20050308035307.8666.qmail@thehosting123.com> <422DCD9A.4060608@biz-experts.net> <20050308172846.00004032@sunray1> Message-ID: <422DE2F1.7050207@biz-experts.net> That did the trick. Thanks Ewald. FYI, I used the '--nodeps' directive once I realized there were really no major issues. I still needed to keep the added symlink since the px libraries couldn't find the libbz2.so.1.0 file. Thanks again to all. That was great help. Victor Ewald Ertl wrote: >Hi Victor > >on Tue, 08 Mar 2005 10:06:50 -0600 Victor Bouffier <apple_py@biz-experts.net> wrote : >--------------------------------------------------------------------------------------------- > >Victor Bouffier > Hi all, >Victor Bouffier > I know this is OT from Python, but does anybody know how to fix my >Victor Bouffier > library issues. I get some awkward dependencies issues from these pylib >Victor Bouffier > libraries. >Victor Bouffier > >Victor Bouffier > # rpm -Uvh pxlib-0.4.3-1.i386.rpm >Victor Bouffier > error: Failed dependencies: >Victor Bouffier > libbz2.so.1.0 is needed by pxlib-0.4.3-1.i386 >Victor Bouffier > >Victor Bouffier > but when I look into my libraries I find the necessary ones under /usr/lib: >Victor Bouffier > >Victor Bouffier > # ll /usr/lib/libbz2* >Victor Bouffier > -rwxr-xr-x 1 root root 67594 Jun 15 2004 /usr/lib/libbz2.a >Victor Bouffier > lrwxrwxrwx 1 root root 11 Feb 6 11:02 /usr/lib/libbz2.so -> libbz2.so.1 >Victor Bouffier > lrwxrwxrwx 1 root root 15 Feb 6 10:10 /usr/lib/libbz2.so.1 -> >Victor Bouffier > libbz2.so.1.0.2 >Victor Bouffier > lrwxrwxrwx 1 root root 24 Mar 8 09:41 /usr/lib/libbz2.so.1.0 -> >Victor Bouffier > /usr/lib/libbz2.so.1.0.2 >Victor Bouffier > -rwxr-xr-x 1 root root 71724 Jun 15 2004 /usr/lib/libbz2.so.1.0.2 >Victor Bouffier > > >Perhap's there is a problem with the RPM-Database. I don't know how rpm works internaly, but it >controls somewhere in a "database", which packages are installed on the system. > >On an old SuSE-System I can search, to which package a file belongs > >rpm -q -f /usr/lib/libbz2.so >bzip2-1.0.2-103 > >Here I see, that libbz2.so belongs to the bzip2-Package. >The other way is to list the files belonging to a package: > >rpm -q -l bzip2-1.0.2-103 >/usr/bin/bunzip2 >/usr/bin/bzcat >/usr/bin/bzip2 >/usr/bin/bzip2recover >/usr/include/bzlib.h >/usr/lib/libbz2.a >/usr/lib/libbz2.la >/usr/lib/libbz2.so >/usr/lib/libbz2.so.1 >/usr/lib/libbz2.so.1.0.0 > >During the installation/update-Process, I think, rpm looks up, all dependencys mentioned >in the rpm if they are installed on the system via the "database" where it logs, >what is installed. > >Try if you can get a package to which your /usr/lib/libbz2.so.1 belongs. > >The other way is, to install the rpm-Package without depdency-check's, but this >could result in the availability of the pxlib-Package, but it perhaps does not work. >You've to test this, before you keep the package. > >"rpm -Uvh --nodeps" > >This should ignore the dependencies and install the package. > > > >------------------- end ---------------------- >HTH Ewald > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > -- Victor Bouffier Finance Manager www.grupoandersons.com From cyresse at gmail.com Tue Mar 8 18:52:57 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 8 18:53:03 2005 Subject: [Tutor] Re: [Pysqlite-users] Querying 2 databases together In-Reply-To: <028c01c523f8$0c07b360$7864a8c0@arborescence.local> References: <028c01c523f8$0c07b360$7864a8c0@arborescence.local> Message-ID: <f2ff2d0503080952465e04ad@mail.gmail.com> Care to post the SQL of what you're trying to do? On Tue, 8 Mar 2005 17:01:07 +0100, Pierre-Yves Delens <py.delens@lienterfaces.be> wrote: > bonjour, > > Iread through SqLite syntax (Attach), and found some old posts on PySqLite, > but.. > > I didn't manage to join a table from a 2d database file in my query. > > Does someone have examples or snippets ? > > Thanks on forward > > ___________________________________________________ > P-Y Delens, ing-arch. manager > > LIENTERFACES - PY Delens, sprl > Avenue Dolez, 243 - 1180 Bruxelles > > phone : 32 2 375 55 62 > fax : 32 2 374 75 74 > mail : py.delens@lienterfaces.be > web : www.lienterfaces.be > ___________________________________________________ > > ------------------------------------------------------- > SF email is sponsored by - The IT Product Guide > Read honest & candid reviews on hundreds of IT Products from real users. > Discover which products truly live up to the hype. Start reading now. > http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click > _______________________________________________ > Pysqlite-users mailing list > Pysqlite-users@lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/pysqlite-users > -- '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. From cyresse at gmail.com Tue Mar 8 18:53:21 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 8 18:53:25 2005 Subject: [Tutor] Re: [Pysqlite-users] Querying 2 databases together In-Reply-To: <f2ff2d0503080952465e04ad@mail.gmail.com> References: <028c01c523f8$0c07b360$7864a8c0@arborescence.local> <f2ff2d0503080952465e04ad@mail.gmail.com> Message-ID: <f2ff2d0503080953686a0ed2@mail.gmail.com> Ack - wrong list. On Wed, 9 Mar 2005 06:52:57 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Care to post the SQL of what you're trying to do? > > > On Tue, 8 Mar 2005 17:01:07 +0100, Pierre-Yves Delens > <py.delens@lienterfaces.be> wrote: > > bonjour, > > > > Iread through SqLite syntax (Attach), and found some old posts on PySqLite, > > but.. > > > > I didn't manage to join a table from a 2d database file in my query. > > > > Does someone have examples or snippets ? > > > > Thanks on forward > > > > ___________________________________________________ > > P-Y Delens, ing-arch. manager > > > > LIENTERFACES - PY Delens, sprl > > Avenue Dolez, 243 - 1180 Bruxelles > > > > phone : 32 2 375 55 62 > > fax : 32 2 374 75 74 > > mail : py.delens@lienterfaces.be > > web : www.lienterfaces.be > > ___________________________________________________ > > > > ------------------------------------------------------- > > SF email is sponsored by - The IT Product Guide > > Read honest & candid reviews on hundreds of IT Products from real users. > > Discover which products truly live up to the hype. Start reading now. > > http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click > > _______________________________________________ > > Pysqlite-users mailing list > > Pysqlite-users@lists.sourceforge.net > > https://lists.sourceforge.net/lists/listinfo/pysqlite-users > > > > -- > '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. > -- '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. From phthenry at iglou.com Tue Mar 8 19:23:47 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Tue Mar 8 19:22:30 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <422DD7C4.1070300@tds.net> References: <20050308162129.GE2055@localhost.localdomain> <422DD7C4.1070300@tds.net> Message-ID: <20050308182347.GA3162@localhost.localdomain> On Tue, Mar 08, 2005 at 11:50:12AM -0500, Kent Johnson wrote: > > Paul Tremblay wrote: > > You can use urllib2 to do this. It is a little work to set it up to use > Basic authentication. Here is an example (slightly modified from the > urllib2 example page): > > import urllib2 > > # Create an OpenerDirector with support for Basic HTTP Authentication... > auth_handler = urllib2.HTTPBasicAuthHandler() > auth_handler.add_password('realm', '127.0.0.1', 'username', 'password') > opener = urllib2.build_opener(auth_handler) > # ...and install it globally so it can be used with urlopen. > urllib2.install_opener(opener) > print urllib2.urlopen('http://127.0.0.1/my/protected/page.html').read() > > Kent > This is giving me 401 error, authorization required. Here's what I have: auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password('realm', '127.0.0.1', 'myname', 'password') opener = urllib2.build_opener(auth_handler) # ...and install it globally so it can be used with urlopen. urllib2.install_opener(opener) print urllib2.urlopen('http://nnn.nnn.n.n').read() This is almost the literal code, except I changed my log in name and passowrd. What am I supposed to put for realm? I checked the docs on line, and it doens't mention what realm is. Also, I assume I am supposed to use the loopback address when I set up the handler? Also, I know I am going to have another question once I solve this one, and since it is directly related, I'll ask it now. How can I use a password system that is not hardcoded in my text? Should I just setup a password file? Thanks Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From kent37 at tds.net Tue Mar 8 19:42:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 8 19:42:44 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <20050308182347.GA3162@localhost.localdomain> References: <20050308162129.GE2055@localhost.localdomain> <422DD7C4.1070300@tds.net> <20050308182347.GA3162@localhost.localdomain> Message-ID: <422DF220.7030108@tds.net> Paul Tremblay wrote: > This is giving me 401 error, authorization required. Here's what I have: > > > auth_handler = urllib2.HTTPBasicAuthHandler() > auth_handler.add_password('realm', '127.0.0.1', 'myname', 'password') > opener = urllib2.build_opener(auth_handler) > # ...and install it globally so it can be used with urlopen. > urllib2.install_opener(opener) > print urllib2.urlopen('http://nnn.nnn.n.n').read() > > This is almost the literal code, except I changed my log in name and > passowrd. > > What am I supposed to put for realm? I checked the docs on line, and it > doens't mention what realm is. The realm name is part of the web server authentication configuration. If you browse to the web page in your browser it will show the realm in the auth dialog. For example my browser (Firefox) shows Enter user name and password for "Curriculum Builder" at http://localhost The realm name is "Curriculum Builder" > Also, I assume I am supposed to use the loopback address when I set up > the handler? No, use your server name, in your example nnn.nn.n.n > Also, I know I am going to have another question once I solve this one, > and since it is directly related, I'll ask it now. How can I use a > password system that is not hardcoded in my text? Should I just setup a > password file? Yes, something like that. You will have to store the password in plaintext (or a reversible cipher) since that is what HTTPBasicAuthHandler needs. Kent From phthenry at iglou.com Tue Mar 8 20:38:09 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Tue Mar 8 20:36:53 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <422DF220.7030108@tds.net> References: <20050308162129.GE2055@localhost.localdomain> <422DD7C4.1070300@tds.net> <20050308182347.GA3162@localhost.localdomain> <422DF220.7030108@tds.net> Message-ID: <20050308193809.GA3363@localhost.localdomain> On Tue, Mar 08, 2005 at 01:42:40PM -0500, Kent Johnson wrote: > Date: Tue, 08 Mar 2005 13:42:40 -0500 > From: Kent Johnson <kent37@tds.net> > User-Agent: Mozilla Thunderbird 1.0 (Windows/20041206) > Cc: python tutor <tutor@python.org> > Subject: Re: [Tutor] getting a webpage via python > > Paul Tremblay wrote: > >This is giving me 401 error, authorization required. Here's what I have: > > > > > >auth_handler = urllib2.HTTPBasicAuthHandler() > >auth_handler.add_password('realm', '127.0.0.1', 'myname', 'password') > >opener = urllib2.build_opener(auth_handler) > ># ...and install it globally so it can be used with urlopen. > >urllib2.install_opener(opener) > >print urllib2.urlopen('http://nnn.nnn.n.n').read() > > > >This is almost the literal code, except I changed my log in name and > >passowrd. > > > >What am I supposed to put for realm? I checked the docs on line, and it > >doens't mention what realm is. > > The realm name is part of the web server authentication configuration. If > you browse to the web page in your browser it will show the realm in the > auth dialog. For example my browser (Firefox) shows > > Enter user name and password for "Curriculum Builder" at http://localhost > > The realm name is "Curriculum Builder" Thanks. I got it to work. I tired to open the page in Koqueror web browser and got this message: Authorization Dialog ==================== You need to supply a username and password to access this site. Site: WRT54G at nnn.nnn.n.n I tried useing "Authorizaiton Dialog" with no success. So I tried opening the same page with lynx with the trace option on. I found that lynx used WRT54G as the realm, so I tried it and it worked. > > >Also, I assume I am supposed to use the loopback address when I set up > >the handler? > > No, use your server name, in your example nnn.nn.n.n > > >Also, I know I am going to have another question once I solve this one, > >and since it is directly related, I'll ask it now. How can I use a > >password system that is not hardcoded in my text? Should I just setup a > >password file? > > Yes, something like that. You will have to store the password in plaintext > (or a reversible cipher) since that is what HTTPBasicAuthHandler needs. > So I just make a file called /etc/router_passwords and include something like WRT54G username password Then parse the file, and supply the info to the password handler? This is easy to do, and I guess it is secure. I am networking on a home system, so security is not so big a concern. However, I have seen a lot of people struggle with getting router addresses from the WRT54G,so I thought I might offer my script, and I wanted to do things a secure, normal way. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From kent37 at tds.net Tue Mar 8 20:58:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 8 20:58:18 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <20050308193809.GA3363@localhost.localdomain> References: <20050308162129.GE2055@localhost.localdomain> <422DD7C4.1070300@tds.net> <20050308182347.GA3162@localhost.localdomain> <422DF220.7030108@tds.net> <20050308193809.GA3363@localhost.localdomain> Message-ID: <422E03D7.2000307@tds.net> Paul Tremblay wrote: > So I just make a file called /etc/router_passwords and include > something like > > WRT54G username password > > Then parse the file, and supply the info to the password handler? This > is easy to do, and I guess it is secure. No, it's not secure at all. In either case (password in the script, password in a file) you are saving a cleartext password in a text file on your computer. I don't think either one is really any more secure than the other. To make your separate file really secure you would have to encrypt it some how. The thing is, Basic auth is inherently insecure - the password is sent Base64 encoded to the web server. Base64 is easily reversed, it is not a secure encoding. So unless you are using HTTPS for a secure link, you are pretty much out of luck anyway. I am networking on a home > system, so security is not so big a concern. However, I have seen a lot > of people struggle with getting router addresses from the WRT54G,so I > thought I might offer my script, and I wanted to do things a secure, > normal way. If it were me, for my own use, I would probably just put the password in the script. One advantage of putting it in a separate file is that you can share the script as is, you don't have to edit out your password each time you send it. On the other hand you have to document the separate file. So for a script you are going to share there might be a small convenience factor to using a separate file. But I don't think there is any difference in security. Kent From klappnase at freenet.de Tue Mar 8 22:18:10 2005 From: klappnase at freenet.de (Michael Lange) Date: Tue Mar 8 22:15:01 2005 Subject: [Tutor] Using signal handlers Message-ID: <20050308221810.3caba7d6.klappnase@freenet.de> Hello tutors, I experience problems with signal handlers, and the explanatzions in the docs don't seem to help me much. The code I try to handle basically comes down to this (it's supposed to run on linux only, btw): from Tkinter import * import tkSnack root = Tk() tkSnack.initializeSnack(root) root.mainloop() initializeSnack() tries to access the sound device, however if this fails it tries forever and doesn't return. I *thought* a signal handler might be what I need, and in fact it partially works, at least initializeSnack() is stopped when I add this: from Tkinter import * import tkSnack, signal root = Tk() signal.signal(signal.SIGALRM, signal.getsignal(signal.SIGALRM)) signal.alarm(5) tkSnack.initializeSnack(root) signal.alarm(0) root.mainloop() Now when the audio device is busy, after 5 seconds the app prints "Alarm clock" and exits. However I would prefer to have a more controlled exit, but as soon as I define a custom signal handler it's the same as before - it never gets called. Any help is much appreciated Michael From shidai.liu at gmail.com Tue Mar 8 23:10:11 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Tue Mar 8 23:10:15 2005 Subject: [Tutor] HELP: subclass of int Message-ID: <33194d7305030814107da27d9e@mail.gmail.com> Hi all, I'll sum up a question as following: def int5(): '''return 5''' return 5 class my_int(int): def __init__(self): self.id = int5() int.__init__(self, self.id) # FIXME: this line doesn't work the above code act like this: >>> I = my_int() >>> I 0 I want it to be like this: >>> I = my_int() >>> I 5 Please, if you know a solution, help me out! -- With best wishes! Shidai From maxnoel_fr at yahoo.fr Tue Mar 8 23:16:50 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 8 23:16:55 2005 Subject: [Tutor] HELP: subclass of int In-Reply-To: <33194d7305030814107da27d9e@mail.gmail.com> References: <33194d7305030814107da27d9e@mail.gmail.com> Message-ID: <42b92f85c295e3509ecd1b59c66b87d1@yahoo.fr> On Mar 8, 2005, at 22:10, Shidai Liu wrote: > Hi all, > > I'll sum up a question as following: > > def int5(): > '''return 5''' > return 5 > > class my_int(int): > def __init__(self): > self.id = int5() > int.__init__(self, self.id) # FIXME: this line doesn't work I'm not absolutely confident with inheritance in Python (nearly all of my serious OO work has been in Java), but shouldn't the call to the superclass's constructor be the very first statement of the subclass's constructor? -- 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?" From pythontut at pusspaws.net Tue Mar 8 23:24:24 2005 From: pythontut at pusspaws.net (Dave S) Date: Tue Mar 8 23:24:34 2005 Subject: [Tutor] Acessing files in Windows 2000 Message-ID: <422E2618.4030601@pusspaws.net> I have a script that converts data relating to my work. It works great on my Linux system but some of my colleagues run windows. I am attempting to convert the file paths to windows but am having no luck. I need to access 'memo.txt' in 'my documents' on windows & am struggling. I have tried just about every combination of \ and / and \\ and // but to no avail. I need something like ... C:\My Documents\memo.txt Can anyone advise me ? Dave From johnp at milwaukielumber.com Tue Mar 8 23:26:31 2005 From: johnp at milwaukielumber.com (John Purser) Date: Tue Mar 8 23:26:39 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422E2618.4030601@pusspaws.net> Message-ID: <200503082226.j28MQVFd010334@email.morseintranet.com> Try c:\\my documents\\memo.txt John -----Original Message----- From: tutor-bounces+johnp=milwaukielumber.com@python.org [mailto:tutor-bounces+johnp=milwaukielumber.com@python.org] On Behalf Of Dave S Sent: Tuesday, March 08, 2005 14:24 To: Python Tutor Subject: [Tutor] Acessing files in Windows 2000 I have a script that converts data relating to my work. It works great on my Linux system but some of my colleagues run windows. I am attempting to convert the file paths to windows but am having no luck. I need to access 'memo.txt' in 'my documents' on windows & am struggling. I have tried just about every combination of \ and / and \\ and // but to no avail. I need something like ... C:\My Documents\memo.txt Can anyone advise me ? Dave _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jfouhy at paradise.net.nz Tue Mar 8 23:40:11 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 8 23:40:15 2005 Subject: [Tutor] HELP: subclass of int In-Reply-To: <42b92f85c295e3509ecd1b59c66b87d1@yahoo.fr> References: <33194d7305030814107da27d9e@mail.gmail.com> <42b92f85c295e3509ecd1b59c66b87d1@yahoo.fr> Message-ID: <1110321611.422e29cb77796@www.paradise.net.nz> Quoting Max Noel <maxnoel_fr@yahoo.fr>: > I'm not absolutely confident with inheritance in Python (nearly all of > my serious OO work has been in Java), but shouldn't the call to the > superclass's constructor be the very first statement of the subclass's > constructor? No ... Or, well, maybe --- but __init__ is technically not the constructor. The constructor is responsible for doing the nitty gritty work of constructing an object, which is, I guess, why you feel it should be called first (because you don't want to be messing with an object that does not fully exist yet). But in python, by the time __init__ is called, the object has been fully constructed. __init__ is just a special method that gets called immediately after construction. But otherwise, there is nothing special or magical about it. You could even do this if you wanted: class myClass(object): ... def reInitialise(self): self.__init__() although I'm not sure if this would be considered good practice :-) [as to the original question --- someone else will have to answer, sorry, 'cause I don't know] -- John. From eculpepper at hcc-care.com Tue Mar 8 23:43:14 2005 From: eculpepper at hcc-care.com (Eric Culpepper) Date: Tue Mar 8 23:41:55 2005 Subject: [Tutor] Acessing files in Windows 2000 Message-ID: <48CA63C679F03D4187762B7CE066AAD202D0AE1D@hccexchange.hcccorp.hcc-care.com> Try something like this (change the username to the user you're logged in as, or Administrator if that's how you're logged in): c:\\documents and settings\\<username|Administrator>\\my documents\\memo.txt -----Original Message----- From: tutor-bounces+eculpepper=hcc-care.com@python.org [mailto:tutor-bounces+eculpepper=hcc-care.com@python.org]On Behalf Of Dave S Sent: Tuesday, March 08, 2005 4:24 PM To: Python Tutor Subject: [Tutor] Acessing files in Windows 2000 I have a script that converts data relating to my work. It works great on my Linux system but some of my colleagues run windows. I am attempting to convert the file paths to windows but am having no luck. I need to access 'memo.txt' in 'my documents' on windows & am struggling. I have tried just about every combination of \ and / and \\ and // but to no avail. I need something like ... C:\My Documents\memo.txt Can anyone advise me ? Dave _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From maxnoel_fr at yahoo.fr Tue Mar 8 23:41:57 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 8 23:42:11 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <200503082226.j28MQVFd010334@email.morseintranet.com> References: <200503082226.j28MQVFd010334@email.morseintranet.com> Message-ID: <580411766b0fce255f9a516b23df11ee@yahoo.fr> On Mar 8, 2005, at 22:26, John Purser wrote: > Try c:\\my documents\\memo.txt > > John Or even better, c:/My Documents/memo.txt In most programming languages, you can use the slash as a path separator under Windows as well. It'll save you a lot of trouble. -- 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?" From jfouhy at paradise.net.nz Tue Mar 8 23:48:12 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 8 23:48:16 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422E2618.4030601@pusspaws.net> References: <422E2618.4030601@pusspaws.net> Message-ID: <1110322092.422e2bacdd3cd@www.paradise.net.nz> Quoting Dave S <pythontut@pusspaws.net>: > I need to access 'memo.txt' in 'my documents' on windows & am > struggling. > I have tried just about every combination of \ and / and \\ and // but > to no avail. > I need something like ... > > C:\My Documents\memo.txt > > Can anyone advise me ? I've never had any trouble accessing files in Win2k with python. The following would all work for me: f1 = file('c:\\My Docments\\memo.txt') f2 = file('c:/My Documents/memo.txt') f3 = file(os.path.normpath('c:/My Documents/memo.txt')) # os.path.normpath normalizes a path; it also converts / to \\ on Windows platforms Is your path correct? The "My Documents" folder doesn't normally live in the root in Win2k; it is more likely to be found somewhere like C:\Documents and Settings\Username\My Documents. Or, in an office environment, it might be on a network share --- eg, H:\. HTH. -- John. From pythontut at pusspaws.net Tue Mar 8 23:50:16 2005 From: pythontut at pusspaws.net (Dave S) Date: Tue Mar 8 23:50:31 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <200503082226.j28MQVFd010334@email.morseintranet.com> References: <200503082226.j28MQVFd010334@email.morseintranet.com> Message-ID: <422E2C28.10704@pusspaws.net> John Purser wrote: >Try c:\\my documents\\memo.txt > > >John > > Unfortunately thats a no go ... palm.py palm memo.txt to oocalc data.csv convertor, written by lentil ;) jk@pusspaws.net - enter "palm software" in the title or it will be junked 09-03-2005 v1.02w Coded for Windows 07-03-2005 v1.02 Coded capitalization() + default to mon 03-03-2005 v1.01 Squished 1/9 decode bug 02-03-2005 v1.00 Coded for Linux Traceback (most recent call last): File "C:\Documents and Settings\Administrator\Desktop\palm.py", line 268, in ? palm_conv() File "C:\Documents and Settings\Administrator\Desktop\palm.py", line 54, in palm_conv memo = open(memo_file, 'r') IOError: [Errno 2] No such file or directory: 'c:\\my documents\\memo.txt' >>> If I try c:\\ or c:\ it always comes out as c:\\... and fails Dave From johnp at milwaukielumber.com Tue Mar 8 23:53:51 2005 From: johnp at milwaukielumber.com (John Purser) Date: Tue Mar 8 23:53:57 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422E2C28.10704@pusspaws.net> Message-ID: <200503082253.j28MrpTu011578@email.morseintranet.com> I agree with a previous poster, check your path. I think either the path doesn't exist or you don't have permission to get to it. John -----Original Message----- From: Dave S [mailto:pythontut@pusspaws.net] Sent: Tuesday, March 08, 2005 14:50 To: johnp@milwaukielumber.com Cc: 'Python Tutor' Subject: Re: [Tutor] Acessing files in Windows 2000 John Purser wrote: >Try c:\\my documents\\memo.txt > > >John > > Unfortunately thats a no go ... palm.py palm memo.txt to oocalc data.csv convertor, written by lentil ;) jk@pusspaws.net - enter "palm software" in the title or it will be junked 09-03-2005 v1.02w Coded for Windows 07-03-2005 v1.02 Coded capitalization() + default to mon 03-03-2005 v1.01 Squished 1/9 decode bug 02-03-2005 v1.00 Coded for Linux Traceback (most recent call last): File "C:\Documents and Settings\Administrator\Desktop\palm.py", line 268, in ? palm_conv() File "C:\Documents and Settings\Administrator\Desktop\palm.py", line 54, in palm_conv memo = open(memo_file, 'r') IOError: [Errno 2] No such file or directory: 'c:\\my documents\\memo.txt' >>> If I try c:\\ or c:\ it always comes out as c:\\... and fails Dave From shitizb at yahoo.com Wed Mar 9 02:13:44 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 9 02:13:48 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: 6667 Message-ID: <20050309011345.95866.qmail@web53803.mail.yahoo.com> I faced the same problem once.Dont remember the solution, but it is definitely the slashes which are causing the problem.I couldnt find a specific rule in whole of microsoft documentation, so i assume it has to be hit and try.Try a mix of backslashes n forward slashes till u get there. Whats worse, I had found that the rule is different for different versions of windows.Just proves what we all know...Windows Suxx. --- John Purser <johnp@milwaukielumber.com> wrote: > I agree with a previous poster, check your path. I > think either the path > doesn't exist or you don't have permission to get to > it. > > John > > -----Original Message----- > From: Dave S [mailto:pythontut@pusspaws.net] > Sent: Tuesday, March 08, 2005 14:50 > To: johnp@milwaukielumber.com > Cc: 'Python Tutor' > Subject: Re: [Tutor] Acessing files in Windows 2000 > > John Purser wrote: > > >Try c:\\my documents\\memo.txt > > > > > >John > > > > > Unfortunately thats a no go ... > > palm.py > > palm memo.txt to oocalc data.csv convertor, written > by lentil ;) > jk@pusspaws.net - enter "palm software" in the title > or it will be junked > > 09-03-2005 v1.02w Coded for Windows > 07-03-2005 v1.02 Coded capitalization() + default > to mon > 03-03-2005 v1.01 Squished 1/9 decode bug > 02-03-2005 v1.00 Coded for Linux > > Traceback (most recent call last): > File "C:\Documents and > Settings\Administrator\Desktop\palm.py", line > 268, in ? > palm_conv() > File "C:\Documents and > Settings\Administrator\Desktop\palm.py", line > 54, in palm_conv > memo = open(memo_file, 'r') > IOError: [Errno 2] No such file or directory: > 'c:\\my documents\\memo.txt' > >>> > > If I try c:\\ > > or > > c:\ > > it always comes out as c:\\... and fails > > Dave > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From carroll at tjc.com Wed Mar 9 02:15:00 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Mar 9 02:15:04 2005 Subject: [Tutor] HELP: subclass of int In-Reply-To: <33194d7305030814107da27d9e@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503081712080.29226-100000@green.rahul.net> On Tue, 8 Mar 2005, Shidai Liu wrote: > I'll sum up a question as following: > > def int5(): > '''return 5''' > return 5 > > class my_int(int): > def __init__(self): > self.id = int5() > int.__init__(self, self.id) # FIXME: this line doesn't work > > the above code act like this: > >>> I = my_int() > >>> I > 0 > > I want it to be like this: > >>> I = my_int() > >>> I > 5 You'll want to use the __new__ method, see http://www.python.org/2.2.3/descrintro.html#__new__ Example: >>> def int5(): ... '''return 5''' ... return 5 ... >>> class my_int(int): ... def __new__(self): ... return int.__new__(self, int5()) ... >>> i = my_int() >>> i 5 >>> As someone else pointed out, you probably ought to call int.__init__ as well. From carroll at tjc.com Wed Mar 9 02:30:17 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Mar 9 02:30:20 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422E2C28.10704@pusspaws.net> Message-ID: <Pine.LNX.4.44.0503081717060.29226-100000@green.rahul.net> On Tue, 8 Mar 2005, Dave S wrote: > IOError: [Errno 2] No such file or directory: 'c:\\my documents\\memo.txt' My two thoughts. 1) is there actually a directory named "my documents" at the root? I don't know about Win2000, but for Win XP, the "my documents" directory is actually C:\Documents and Settings\username\My Documents 2) The embedded space may be the issue, although I doubt that's it. From michael.hall at critterpixstudios.com Wed Mar 9 02:34:24 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 02:34:11 2005 Subject: [Tutor] regular expression question Message-ID: <cab2030dd30baff888e44d5bb91dccc8@critterpixstudios.com> I'd like to get a match for a position in a string preceded by a specified word (let's call it "Dog"), unless that spot in the string (after "Dog") is directly followed by a specific word(let's say "Cat"), in which case I want my match to occur directly after "Cat", and not "Dog." I can easily get the spot after "Dog," and I can also get it to ignore this spot if "Dog" is followed by "Cat." But what I'm having trouble with is how to match the spot after "Cat" if this word does indeed exist in the string. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 528 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050308/cce9cb93/attachment-0001.bin From shidai.liu at gmail.com Wed Mar 9 02:34:57 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Wed Mar 9 02:35:00 2005 Subject: [Tutor] HELP: subclass of int In-Reply-To: <Pine.LNX.4.44.0503081712080.29226-100000@green.rahul.net> References: <33194d7305030814107da27d9e@mail.gmail.com> <Pine.LNX.4.44.0503081712080.29226-100000@green.rahul.net> Message-ID: <33194d73050308173477f3c012@mail.gmail.com> On Tue, 8 Mar 2005 17:15:00 -0800 (PST), Terry Carroll <carroll@tjc.com> wrote: > On Tue, 8 Mar 2005, Shidai Liu wrote: > > > I'll sum up a question as following: > > > > def int5(): > > '''return 5''' > > return 5 > > > > class my_int(int): > > def __init__(self): > > self.id = int5() > > int.__init__(self, self.id) # FIXME: this line doesn't work > > > > the above code act like this: > > >>> I = my_int() > > >>> I > > 0 > > > > I want it to be like this: > > >>> I = my_int() > > >>> I > > 5 > > You'll want to use the __new__ method, see > http://www.python.org/2.2.3/descrintro.html#__new__ Great link. It explains so much. > > Example: > > >>> def int5(): > ... '''return 5''' > ... return 5 > ... > >>> class my_int(int): > ... def __new__(self): > ... return int.__new__(self, int5()) > ... > >>> i = my_int() > >>> i > 5 > >>> > > As someone else pointed out, you probably ought to call int.__init__ as > well. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > It works. Thanks very much! -- With best wishes! Shidai From shaleh at speakeasy.net Wed Mar 9 02:54:13 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 9 02:55:30 2005 Subject: [Tutor] regular expression question In-Reply-To: <cab2030dd30baff888e44d5bb91dccc8@critterpixstudios.com> References: <cab2030dd30baff888e44d5bb91dccc8@critterpixstudios.com> Message-ID: <422E5745.5000001@speakeasy.net> Mike Hall wrote: > I'd like to get a match for a position in a string preceded by a > specified word (let's call it "Dog"), unless that spot in the string > (after "Dog") is directly followed by a specific word(let's say "Cat"), > in which case I want my match to occur directly after "Cat", and not "Dog." > > I can easily get the spot after "Dog," and I can also get it to ignore > this spot if "Dog" is followed by "Cat." But what I'm having trouble > with is how to match the spot after "Cat" if this word does indeed exist > in the string. > > . >>> import re . >>> my_re = re.compile(r'(dog)(cat)?') # the ? means "find one or zero of these, in other words cat is optional. . >>> m = my_re.search("This is a nice dog is it not?") . >>> dir(m) ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', 'groups', 'span', 'start'] . >>> m.span() (15, 18) . >>> m = my_re.search("This is a nice dogcat is it not?") . >>> m.span() (15, 21) If m is None then no match was found. span returns the locations in the string where the match occured. So in the dogcat sentence the last char is 21. . >>> "This is a nice dogcat is it not?"[21:] ' is it not?' Hope that helps. From dyoo at hkn.eecs.berkeley.edu Wed Mar 9 03:05:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 9 03:05:42 2005 Subject: [Tutor] regular expression question In-Reply-To: <cab2030dd30baff888e44d5bb91dccc8@critterpixstudios.com> Message-ID: <Pine.LNX.4.44.0503081802420.11830-100000@hkn.eecs.berkeley.edu> On Tue, 8 Mar 2005, Mike Hall wrote: > I'd like to get a match for a position in a string preceded by a > specified word (let's call it "Dog"), unless that spot in the string > (after "Dog") is directly followed by a specific word(let's say "Cat"), > in which case I want my match to occur directly after "Cat", and not > "Dog." Hi Mike, You may want to look at "lookahead" assertions. These are patterns of the form '(?=...)' or '(?!...). The documentation mentions them here: http://www.python.org/doc/lib/re-syntax.html and AMK's excellent "Regular Expression HOWTO" covers how one might use them: http://www.amk.ca/python/howto/regex/regex.html#SECTION000540000000000000000 From michael.hall at critterpixstudios.com Wed Mar 9 03:12:29 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 03:12:14 2005 Subject: [Tutor] regular expression question In-Reply-To: <422E5745.5000001@speakeasy.net> References: <cab2030dd30baff888e44d5bb91dccc8@critterpixstudios.com> <422E5745.5000001@speakeasy.net> Message-ID: <b2d8e1a56bd10f1413147cc856a90b9d@critterpixstudios.com> First, thanks for the response. Using your re: > my_re = re.compile(r'(dog)(cat)?') ...I seem to simply be matching the pattern "Dog". Example: >>> str1 = "The dog chased the car" >>> str2 = "The dog cat parade was under way" >>> x1 = re.compile(r'(dog)(cat)?') >>> rep1 = x1.sub("REPLACE", str1) >>> rep2 = x2.sub("REPLACE", str2) >>> print rep1 The REPLACE chased the car >>> print rep2 The REPLACE cat parade was under way ...what I'm looking for is a match for the position in front of "Cat", should it exist. On Mar 8, 2005, at 5:54 PM, Sean Perry wrote: > Mike Hall wrote: >> I'd like to get a match for a position in a string preceded by a >> specified word (let's call it "Dog"), unless that spot in the string >> (after "Dog") is directly followed by a specific word(let's say >> "Cat"), in which case I want my match to occur directly after "Cat", >> and not "Dog." >> I can easily get the spot after "Dog," and I can also get it to >> ignore this spot if "Dog" is followed by "Cat." But what I'm having >> trouble with is how to match the spot after "Cat" if this word does >> indeed exist in the string. > > . >>> import re > . >>> my_re = re.compile(r'(dog)(cat)?') # the ? means "find one or > zero of these, in other words cat is optional. > . >>> m = my_re.search("This is a nice dog is it not?") > . >>> dir(m) > ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict', > 'groups', 'span', 'start'] > . >>> m.span() > (15, 18) > . >>> m = my_re.search("This is a nice dogcat is it not?") > . >>> m.span() > (15, 21) > > If m is None then no match was found. span returns the locations in > the string where the match occured. So in the dogcat sentence the last > char is 21. > > . >>> "This is a nice dogcat is it not?"[21:] > ' is it not?' > > Hope that helps. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From amonroe at columbus.rr.com Wed Mar 9 03:15:10 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Mar 9 03:16:01 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422E2618.4030601@pusspaws.net> References: <422E2618.4030601@pusspaws.net> Message-ID: <35741637728.20050308211510@columbus.rr.com> > I have a script that converts data relating to my work. > It works great on my Linux system but some of my colleagues run windows. > I am attempting to convert the file paths to windows but am having no luck. > I need to access 'memo.txt' in 'my documents' on windows & am struggling. > I have tried just about every combination of \ and / and \\ and // but > to no avail. > I need something like ... > C:\My Documents\memo.txt You'll have to come up with some windows-specific trick to find out the current user, because "my documents" is actually in c:\documents and settings\currentusername\my documents\ Try getting it from the HOMEPATH environment variable. import os print os.environ['HOMEPATH'] Alan From maxnoel_fr at yahoo.fr Wed Mar 9 03:23:34 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Mar 9 03:23:39 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <20050309011345.95866.qmail@web53803.mail.yahoo.com> References: <20050309011345.95866.qmail@web53803.mail.yahoo.com> Message-ID: <5cae85d7b1b50a4a2514c39c67825289@yahoo.fr> On Mar 9, 2005, at 01:13, Shitiz Bansal wrote: > Whats worse, I had found that the rule is different > for different versions of windows.Just proves what we > all know...Windows Suxx. The Windows OS sucks! And blows! At the same time! (name the reference, get a cookie ;) ) -- 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?" From shaleh at speakeasy.net Wed Mar 9 03:28:21 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 9 03:29:49 2005 Subject: [Tutor] regular expression question In-Reply-To: <b2d8e1a56bd10f1413147cc856a90b9d@critterpixstudios.com> References: <cab2030dd30baff888e44d5bb91dccc8@critterpixstudios.com> <422E5745.5000001@speakeasy.net> <b2d8e1a56bd10f1413147cc856a90b9d@critterpixstudios.com> Message-ID: <422E5F45.7070707@speakeasy.net> Mike Hall wrote: > First, thanks for the response. Using your re: > >> my_re = re.compile(r'(dog)(cat)?') > > > ...I seem to simply be matching the pattern "Dog". Example: > > >>> str1 = "The dog chased the car" > >>> str2 = "The dog cat parade was under way" > >>> x1 = re.compile(r'(dog)(cat)?') > >>> rep1 = x1.sub("REPLACE", str1) > >>> rep2 = x2.sub("REPLACE", str2) > >>> print rep1 > The REPLACE chased the car > >>> print rep2 > The REPLACE cat parade was under way > > > ...what I'm looking for is a match for the position in front of "Cat", > should it exist. > Because my regex says 'look for the word "dog" and remember where you found it. If you also find the word "cat", remember that too'. Nowhere does it say "watch out for whitespace". r'(dog)\s*(cat)?' says match 'dog' followed by zero or more whitespace (spaces, tabs, etc.) and maybe 'cat'. There is a wonderful O'Reilly book called "Mastering Regular Expressions" or as Danny points out the AMK howto is good. From michael.hall at critterpixstudios.com Wed Mar 9 03:40:48 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 03:40:43 2005 Subject: [Tutor] regular expression question In-Reply-To: <Pine.LNX.4.44.0503081802420.11830-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503081802420.11830-100000@hkn.eecs.berkeley.edu> Message-ID: <346b77beb5919d8ea65645b1faeffd8c@critterpixstudios.com> This will match the position in front of "dog": (?<=dog) This will match the position in front of "cat": (?<=cat) This will not match in front of "dog" if "dog" is followed by "cat": (?<=dog)\b (?!cat) Now my question is how to get this: (?<=cat) ...but ONLY if "cat" is following "dog." If "dog" does not have "cat" following it, then I simply want this: (?<=dog) ...if that makes sense :) thanks. On Mar 8, 2005, at 6:05 PM, Danny Yoo wrote: > > > On Tue, 8 Mar 2005, Mike Hall wrote: > >> I'd like to get a match for a position in a string preceded by a >> specified word (let's call it "Dog"), unless that spot in the string >> (after "Dog") is directly followed by a specific word(let's say >> "Cat"), >> in which case I want my match to occur directly after "Cat", and not >> "Dog." > > Hi Mike, > > You may want to look at "lookahead" assertions. These are patterns of > the > form '(?=...)' or '(?!...). The documentation mentions them here: > > http://www.python.org/doc/lib/re-syntax.html > > and AMK's excellent "Regular Expression HOWTO" covers how one might use > them: > > http://www.amk.ca/python/howto/regex/ > regex.html#SECTION000540000000000000000 > From dyoo at hkn.eecs.berkeley.edu Wed Mar 9 03:42:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 9 03:42:23 2005 Subject: [Tutor] regular expression question In-Reply-To: <190077d35ac1553e1169fc1cead91813@critterpixstudios.com> Message-ID: <Pine.LNX.4.44.0503081837210.11830-100000@hkn.eecs.berkeley.edu> On Tue, 8 Mar 2005, Mike Hall wrote: > Yes, my existing regex is using a look behind assertion: > > (?<=dog) > > ...it's also checking the existence of "Cat": > > (?!Cat) > > ...what I'm stuck on is how to essentially use a lookbehind on "Cat", > but only if it exists. Hi Mike, [Note: Please do a reply-to-all next time, so that everyone can help you.] Regular expressions are a little evil at times; here's what I think you're thinking of: ### >>> import re >>> pattern = re.compile(r"""dog(?!cat) ... | (?<=dogcat)""", re.VERBOSE) >>> pattern.match('dogman').start() 0 >>> pattern.search('dogcatcher').start() >>> pattern.search('dogman').start() 0 >>> pattern.search('catwoman') >>> ### but I can't be sure without seeing some of the examples you'd like the regular expression to match against. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Mar 9 03:47:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 9 03:47:30 2005 Subject: [Tutor] regular expression question In-Reply-To: <Pine.LNX.4.44.0503081837210.11830-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> > > Regular expressions are a little evil at times; here's what I think you're > thinking of: > > ### > >>> import re > >>> pattern = re.compile(r"""dog(?!cat) > ... | (?<=dogcat)""", re.VERBOSE) > >>> pattern.match('dogman').start() > 0 > >>> pattern.search('dogcatcher').start() Hi Mike, Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually does come up with a result: ### >>> pattern.search('dogcatcher').start() 6 ### Sorry about that! From michael.hall at critterpixstudios.com Wed Mar 9 03:51:04 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 03:50:54 2005 Subject: [Tutor] regular expression question In-Reply-To: <Pine.LNX.4.44.0503081837210.11830-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503081837210.11830-100000@hkn.eecs.berkeley.edu> Message-ID: <39e63c71cb47e3d24c750b50db901f85@critterpixstudios.com> Sorry, my last reply crossed this one (and yes, I forgot again to CC the list). I'm experimenting now with your use of the "or" operator( "|") between two expressions, thanks. On Mar 8, 2005, at 6:42 PM, Danny Yoo wrote: > > > On Tue, 8 Mar 2005, Mike Hall wrote: > >> Yes, my existing regex is using a look behind assertion: >> >> (?<=dog) >> >> ...it's also checking the existence of "Cat": >> >> (?!Cat) >> >> ...what I'm stuck on is how to essentially use a lookbehind on "Cat", >> but only if it exists. > > Hi Mike, > > > > [Note: Please do a reply-to-all next time, so that everyone can help > you.] > > Regular expressions are a little evil at times; here's what I think > you're > thinking of: > > ### >>>> import re >>>> pattern = re.compile(r"""dog(?!cat) > ... | (?<=dogcat)""", re.VERBOSE) >>>> pattern.match('dogman').start() > 0 >>>> pattern.search('dogcatcher').start() >>>> pattern.search('dogman').start() > 0 >>>> pattern.search('catwoman') >>>> > ### > > but I can't be sure without seeing some of the examples you'd like the > regular expression to match against. > > > Best of wishes to you! > From dyoo at hkn.eecs.berkeley.edu Wed Mar 9 03:56:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 9 03:56:49 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <5cae85d7b1b50a4a2514c39c67825289@yahoo.fr> Message-ID: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> [Windows bashing cut] Python's support for Windows stuff is actually quite good, thanks to the work of Mark Hammond: http://starship.python.net/crew/mhammond/ A lot of us here do use Windows for COM programming. Let's get back to talking about Python programming and let's help Dave with his problem. The os.path module contains a function called expanduser() that returns the home directory of a given user. http://www.python.org/doc/lib/module-os.path.html#l2h-1720 I believe this should reliably return a path that looks something like '\\Documents and Settings\\[username]' on Windows systems. Dave, what happens if you try something like this? ###### import os.path print os.path.expanduser('~/memo.txt') f = open(os.path.expanduser('~/memo.txt')) ###### Show us what you see, and we can work from there. Can you also give us the complete path where you see 'memo.txt' on your system? Just right click the file; it should show up somewhere on the file's property page. Best of wishes to you! From kent37 at tds.net Wed Mar 9 06:19:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 9 06:19:30 2005 Subject: [Tutor] HELP: subclass of int In-Reply-To: <33194d7305030814107da27d9e@mail.gmail.com> References: <33194d7305030814107da27d9e@mail.gmail.com> Message-ID: <422E875C.1040305@tds.net> Shidai Liu wrote: > Hi all, > > I'll sum up a question as following: > > def int5(): > '''return 5''' > return 5 > > class my_int(int): > def __init__(self): > self.id = int5() > int.__init__(self, self.id) # FIXME: this line doesn't work > > the above code act like this: > >>>>I = my_int() >>>>I > > 0 > > I want it to be like this: > >>>>I = my_int() >>>>I > > 5 > > Please, if you know a solution, help me out! When you subclass an immutable type like int (or float, string, ...) you have to define __new__ instead of __init__. See this page for an example and some explanation: http://www.python.org/2.2.3/descrintro.html#__new__ Kent > From smichr at hotmail.com Wed Mar 9 08:22:14 2005 From: smichr at hotmail.com (C Smith) Date: Wed Mar 9 08:23:07 2005 Subject: [Tutor] working with new classes Message-ID: <BAY101-DAV151EF46FA83EBE5E1B3980C1510@phx.gbl> Hello, After learning about the new class behavior, I am trying to implement a circular type list where, for example, you can compare the nth value to the "(n+1)th" value without worrying about going past the end of the list. (An old approach might be to create a function that converts a given index to the real index (e.g. maps the "(n+1)th" value back to the 1st value), but I thought I would try subclassing the list behavior.) Seeing an ASPN entry on circular lists (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52246), I first tried to define a "turn" method for the list. The following works ### class ring(list): def turn(self, incr=1): tail=self[incr:] head = self[:incr] self[:] = tail+head l=ring(range(10)) l.turn(5) #the list now has a turn method print l #--> [5, 6, 7, 8, 9, 0, 1, 2, 3, 4] ### Then I tried to redefine how the list is initialized, desiring to give it a "zero" attribute which will be used whenever an item from the list is requested. I'm hoping not to have work with slices of the list--I just change how it is accessed. BUT...it doesn't work. Apparently __getitem__ is not accessed in order to print the list; and Python crashes when I try to print a single element. Am I trying to subclass the wrong aspects of the list? ### class Ring(list): def __init__(self, l): self[:] = l self._zero = 0 def turn(self, incr=1): self._zero+=incr def __getitem__(self, i): return self[(i-self._zero)%len(self)] l=Ring(range(10)) print l l.turn(5) print l #same as original print l[0] #crashes python ### /c From shaleh at speakeasy.net Wed Mar 9 09:55:22 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 9 09:56:41 2005 Subject: [Tutor] working with new classes In-Reply-To: <BAY101-DAV151EF46FA83EBE5E1B3980C1510@phx.gbl> References: <BAY101-DAV151EF46FA83EBE5E1B3980C1510@phx.gbl> Message-ID: <422EB9FA.3050600@speakeasy.net> C Smith wrote: > ### > class Ring(list): > def __init__(self, l): > self[:] = l > self._zero = 0 > > def turn(self, incr=1): > self._zero+=incr > > def __getitem__(self, i): > return self[(i-self._zero)%len(self)] > > l=Ring(range(10)) > print l > l.turn(5) > print l #same as original > print l[0] #crashes python > ### > This is a classic mistake. l[0] --> l.__getitem__(l, 0), which you understand. However in __getitem__ you then call self[] which will just call __getitem__ again. and again. and again. .... The way out is to explicitly call the parent's __getitem__. def __getitem__(self, i): # list is out parent, call its method return list.__getitem__(self, (i - self._zero) % len(self)) From kent37 at tds.net Wed Mar 9 12:37:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 9 12:37:14 2005 Subject: [Tutor] working with new classes In-Reply-To: <422EB9FA.3050600@speakeasy.net> References: <BAY101-DAV151EF46FA83EBE5E1B3980C1510@phx.gbl> <422EB9FA.3050600@speakeasy.net> Message-ID: <422EDFE5.2060006@tds.net> Sean Perry wrote: > C Smith wrote: > >> ### >> class Ring(list): >> def __init__(self, l): >> self[:] = l >> self._zero = 0 >> def turn(self, incr=1): >> self._zero+=incr >> >> def __getitem__(self, i): >> return self[(i-self._zero)%len(self)] >> >> l=Ring(range(10)) >> print l >> l.turn(5) >> print l #same as original >> print l[0] #crashes python >> ### >> > > This is a classic mistake. l[0] --> l.__getitem__(l, 0), which you > understand. However in __getitem__ you then call self[] which will just > call __getitem__ again. and again. and again. .... > > The way out is to explicitly call the parent's __getitem__. > > def __getitem__(self, i): > # list is out parent, call its method > return list.__getitem__(self, (i - self._zero) % len(self)) Two other changes: - in __init__(), instead of modifying self, I think it is safer to call list.__init__(). This is the usual thing do do in a subclass. - You can change the behaviour of print by defining __repr__() or __str__(). Here is a complete version that seems to work, though you may find other list methods you need to override: class Ring(list): def __init__(self, l): list.__init__(self, l) self._zero = 0 def turn(self, incr=1): self._zero+=incr def __getitem__(self, i): return list.__getitem__(self, (i - self._zero) % len(self)) def __repr__(self): return repr([self[i] for i in range(len(self))]) l=Ring(range(10)) print l l.turn(5) print l print l[0] Kent From kent37 at tds.net Wed Mar 9 14:29:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 9 14:29:50 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <422E03D7.2000307@tds.net> References: <20050308162129.GE2055@localhost.localdomain> <422DD7C4.1070300@tds.net> <20050308182347.GA3162@localhost.localdomain> <422DF220.7030108@tds.net> <20050308193809.GA3363@localhost.localdomain> <422E03D7.2000307@tds.net> Message-ID: <422EFA4A.1090203@tds.net> Kent Johnson wrote: > Paul Tremblay wrote: > >> So I just make a file called /etc/router_passwords and include >> something like >> WRT54G username password >> >> Then parse the file, and supply the info to the password handler? This >> is easy to do, and I guess it is secure. The book "Foundations of Python Network Programming" has a sample program that uses a custom urllib2.HTTPPasswordMgr to ask the user for the username and password, maybe you would like to use that? The examples can be downloaded from the book Web site at http://www.apress.com/book/bookDisplay.html?bID=363 Look for the one called dump_info_auth.py Kent From pythontut at pusspaws.net Wed Mar 9 15:06:01 2005 From: pythontut at pusspaws.net (Dave S) Date: Wed Mar 9 15:06:12 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> Message-ID: <422F02C9.3060502@pusspaws.net> Danny Yoo wrote: >[Windows bashing cut] > >Python's support for Windows stuff is actually quite good, thanks to the >work of Mark Hammond: > > http://starship.python.net/crew/mhammond/ > >A lot of us here do use Windows for COM programming. Let's get back to >talking about Python programming and let's help Dave with his problem. > > >The os.path module contains a function called expanduser() that returns >the home directory of a given user. > > http://www.python.org/doc/lib/module-os.path.html#l2h-1720 > >I believe this should reliably return a path that looks something like >'\\Documents and Settings\\[username]' on Windows systems. > > >Dave, what happens if you try something like this? > >###### >import os.path >print os.path.expanduser('~/memo.txt') >f = open(os.path.expanduser('~/memo.txt')) >###### > >Show us what you see, and we can work from there. Can you also give us >the complete path where you see 'memo.txt' on your system? Just right >click the file; it should show up somewhere on the file's property page. > > >Best of wishes to you! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > Hello again, Wow what a lot of replies. OK here goes. I know little about win 2000 so when I My computer > C > My documents I assumed that was where the my documents folder was, Having gone through what you guys said I also have C:\Documents and Settings\Administrator\My Documents So I copied memo.txt to C:\Documents and Settings\Administrator\My Documents, ammended my code memo_file = 'C:\Documents and Settings\Administrator\My Documents\memo.txt' csv_file = 'c:\data.csv' def palm_conv(): # The money sheet map1 = [[0]*5 for n in xrange(42)] map1_count = 6 # The time sheet map2 = [['']*7 for n in xrange(75)] map2_count = 0 day_map = {'sun':0, 'mon':1, 'tue':2, 'wed':3, 'thu':4, 'fri':5, 'sat':6} sh_offset = 0 ot_offset = 0 ca_offset = 0 pa_offset = 0 su_offset = 0 time_slot = 0 text_slot = 0 memo = open(memo_file, 'r') count = 0 raw_line = ' ' ... And got the following again ... Traceback (most recent call last): File "C:\Documents and Settings\Administrator\Desktop\palm.py", line 268, in ? palm_conv() File "C:\Documents and Settings\Administrator\Desktop\palm.py", line 54, in palm_conv memo = open(memo_file, 'r') IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\Administrator\\My Documents\\memo.txt' >>> So I tried your test code & got ... >>> >>> >>> import os.path >>> print os.path.expanduser('~/memo.txt') C:\Documents and Settings\Administrator/memo.txt >>> f = open(os.path.expanduser('~/memo.txt')) Traceback (most recent call last): File "<pyshell#15>", line 1, in ? f = open(os.path.expanduser('~/memo.txt')) IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\\Administrator/memo.txt' >>> Now starting to doubt my sanity I again re-checked C:\Documents and Settings\Administrator\My Documents and yes I do have a memo.txt there. In C:\Documents and Settings I have the folders administrator, all users and compy, I put a copy of memo.txt in compy as well & changed my code, same problem Any ideas Dave From bill.mill at gmail.com Wed Mar 9 19:13:50 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed Mar 9 19:13:53 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422F02C9.3060502@pusspaws.net> References: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> <422F02C9.3060502@pusspaws.net> Message-ID: <797fe3d4050309101377478395@mail.gmail.com> Dave, > >>> > >>> > >>> import os.path > >>> print os.path.expanduser('~/memo.txt') > C:\Documents and Settings\Administrator/memo.txt > >>> f = open(os.path.expanduser('~/memo.txt')) > Traceback (most recent call last): > File "<pyshell#15>", line 1, in ? > f = open(os.path.expanduser('~/memo.txt')) > IOError: [Errno 2] No such file or directory: 'C:\\Documents and > Settings\\Administrator/memo.txt' > >>> > > Now starting to doubt my sanity I again re-checked C:\Documents and > Settings\Administrator\My Documents > and yes I do have a memo.txt there. > Using all forward slashes works fine for me. Here's a cut-n-paste from the command line (touch creates a blank file, ls lists dirs, in case you didn't know): C:\Documents and Settings\WMill>touch test.txt C:\Documents and Settings\WMill>ls test.txt test.txt C:\Documents and Settings\WMill>C:\Python24\python.exe Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('c:/Documents and Settings/WMill/test.txt') >>> I'm really pretty convinced that the file you're talking about doesn't exist, or you don't have the security permissions to open it. Peace Bill Mill bill.mill at gmail.com From michael.hall at critterpixstudios.com Wed Mar 9 20:11:57 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 20:11:43 2005 Subject: [Tutor] regular expression question In-Reply-To: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> Message-ID: <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> I'm having some strange results using the "or" operator. In every test I do I'm matching both sides of the "|" metacharacter, not one or the other as all documentation says it should be (the parser supposedly scans left to right, using the first match it finds and ignoring the rest). It should only go beyond the "|" if there was no match found before it, no? Correct me if I'm wrong, but your regex is saying "match dog, unless it's followed by cat. if it is followed by cat there is no match on this side of the "|" at which point we advance past it and look at the alternative expression which says to match in front of cat." However, if I run a .sub using your regex on a string contain both dog and cat, both will be replaced. A simple example will show what I mean: >>> import re >>> x = re.compile(r"(A) | (B)") >>> s = "X R A Y B E" >>> r = x.sub("13", s) >>> print r X R 13Y13 E ...so unless I'm understanding it wrong, "B" is supposed to be ignored if "A" is matched, yet I get both matched. I get the same result if I put "A" and "B" within the same group. On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: > > >> >> Regular expressions are a little evil at times; here's what I think >> you're >> thinking of: >> >> ### >>>>> import re >>>>> pattern = re.compile(r"""dog(?!cat) >> ... | (?<=dogcat)""", re.VERBOSE) >>>>> pattern.match('dogman').start() >> 0 >>>>> pattern.search('dogcatcher').start() > > > > Hi Mike, > > Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually does > come up with a result: > > ### >>>> pattern.search('dogcatcher').start() > 6 > ### > > Sorry about that! > From cyresse at gmail.com Wed Mar 9 21:09:13 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 9 21:09:16 2005 Subject: [Tutor] regular expression question In-Reply-To: <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> Message-ID: <f2ff2d05030912095a1b2fa3@mail.gmail.com> Hi Mike, Do you get the same results for a search pattern of 'A|B'? On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall <michael.hall@critterpixstudios.com> wrote: > I'm having some strange results using the "or" operator. In every test > I do I'm matching both sides of the "|" metacharacter, not one or the > other as all documentation says it should be (the parser supposedly > scans left to right, using the first match it finds and ignoring the > rest). It should only go beyond the "|" if there was no match found > before it, no? > > Correct me if I'm wrong, but your regex is saying "match dog, unless > it's followed by cat. if it is followed by cat there is no match on > this side of the "|" at which point we advance past it and look at the > alternative expression which says to match in front of cat." > > However, if I run a .sub using your regex on a string contain both dog > and cat, both will be replaced. > > A simple example will show what I mean: > > >>> import re > >>> x = re.compile(r"(A) | (B)") > >>> s = "X R A Y B E" > >>> r = x.sub("13", s) > >>> print r > X R 13Y13 E > > ...so unless I'm understanding it wrong, "B" is supposed to be ignored > if "A" is matched, yet I get both matched. I get the same result if I > put "A" and "B" within the same group. > > > On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: > > > > > > >> > >> Regular expressions are a little evil at times; here's what I think > >> you're > >> thinking of: > >> > >> ### > >>>>> import re > >>>>> pattern = re.compile(r"""dog(?!cat) > >> ... | (?<=dogcat)""", re.VERBOSE) > >>>>> pattern.match('dogman').start() > >> 0 > >>>>> pattern.search('dogcatcher').start() > > > > > > > > Hi Mike, > > > > Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually does > > come up with a result: > > > > ### > >>>> pattern.search('dogcatcher').start() > > 6 > > ### > > > > Sorry about that! > > > > _______________________________________________ > 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. From michael.hall at critterpixstudios.com Wed Mar 9 21:19:33 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 21:19:14 2005 Subject: [Tutor] regular expression question In-Reply-To: <f2ff2d05030912095a1b2fa3@mail.gmail.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> <f2ff2d05030912095a1b2fa3@mail.gmail.com> Message-ID: <79b6d2ae023b8a755f4d526665486ed3@critterpixstudios.com> Indeed I do: >>> import re >>> x = re.compile('A|B') >>> s = " Q A R B C" >>> r = x.sub("13", s) >>> print r Q 13 R 13 C On Mar 9, 2005, at 12:09 PM, Liam Clarke wrote: > Hi Mike, > > Do you get the same results for a search pattern of 'A|B'? > > > On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall > <michael.hall@critterpixstudios.com> wrote: >> I'm having some strange results using the "or" operator. In every >> test >> I do I'm matching both sides of the "|" metacharacter, not one or the >> other as all documentation says it should be (the parser supposedly >> scans left to right, using the first match it finds and ignoring the >> rest). It should only go beyond the "|" if there was no match found >> before it, no? >> >> Correct me if I'm wrong, but your regex is saying "match dog, unless >> it's followed by cat. if it is followed by cat there is no match on >> this side of the "|" at which point we advance past it and look at the >> alternative expression which says to match in front of cat." >> >> However, if I run a .sub using your regex on a string contain both dog >> and cat, both will be replaced. >> >> A simple example will show what I mean: >> >>>>> import re >>>>> x = re.compile(r"(A) | (B)") >>>>> s = "X R A Y B E" >>>>> r = x.sub("13", s) >>>>> print r >> X R 13Y13 E >> >> ...so unless I'm understanding it wrong, "B" is supposed to be ignored >> if "A" is matched, yet I get both matched. I get the same result if I >> put "A" and "B" within the same group. >> >> >> On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: >> >>> >>> >>>> >>>> Regular expressions are a little evil at times; here's what I think >>>> you're >>>> thinking of: >>>> >>>> ### >>>>>>> import re >>>>>>> pattern = re.compile(r"""dog(?!cat) >>>> ... | (?<=dogcat)""", re.VERBOSE) >>>>>>> pattern.match('dogman').start() >>>> 0 >>>>>>> pattern.search('dogcatcher').start() >>> >>> >>> >>> Hi Mike, >>> >>> Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually >>> does >>> come up with a result: >>> >>> ### >>>>>> pattern.search('dogcatcher').start() >>> 6 >>> ### >>> >>> Sorry about that! >>> >> >> _______________________________________________ >> 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 > From michael.hall at critterpixstudios.com Wed Mar 9 21:21:37 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 21:21:20 2005 Subject: [Tutor] regular expression question In-Reply-To: <2b46c71505030912071e9cb3bd@mail.gmail.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> <2b46c71505030912071e9cb3bd@mail.gmail.com> Message-ID: <4828fdb559f223fc221602ac2055af7a@critterpixstudios.com> But I only want to ignore "B" if "A" is a match. If "A" is not a match, I'd like it to advance on to "B". On Mar 9, 2005, at 12:07 PM, Marcos Mendon?a wrote: > Hi > > Not and regexp expert. But it seems to me that if you want to ignora > "B" then it should be > (A) | (^B) > > Hope it helps! > > > On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall > <michael.hall@critterpixstudios.com> wrote: >> I'm having some strange results using the "or" operator. In every >> test >> I do I'm matching both sides of the "|" metacharacter, not one or the >> other as all documentation says it should be (the parser supposedly >> scans left to right, using the first match it finds and ignoring the >> rest). It should only go beyond the "|" if there was no match found >> before it, no? >> >> Correct me if I'm wrong, but your regex is saying "match dog, unless >> it's followed by cat. if it is followed by cat there is no match on >> this side of the "|" at which point we advance past it and look at the >> alternative expression which says to match in front of cat." >> >> However, if I run a .sub using your regex on a string contain both dog >> and cat, both will be replaced. >> >> A simple example will show what I mean: >> >>>>> import re >>>>> x = re.compile(r"(A) | (B)") >>>>> s = "X R A Y B E" >>>>> r = x.sub("13", s) >>>>> print r >> X R 13Y13 E >> >> ...so unless I'm understanding it wrong, "B" is supposed to be ignored >> if "A" is matched, yet I get both matched. I get the same result if I >> put "A" and "B" within the same group. >> >> >> On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: >> >>> >>> >>>> >>>> Regular expressions are a little evil at times; here's what I think >>>> you're >>>> thinking of: >>>> >>>> ### >>>>>>> import re >>>>>>> pattern = re.compile(r"""dog(?!cat) >>>> ... | (?<=dogcat)""", re.VERBOSE) >>>>>>> pattern.match('dogman').start() >>>> 0 >>>>>>> pattern.search('dogcatcher').start() >>> >>> >>> >>> Hi Mike, >>> >>> Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually >>> does >>> come up with a result: >>> >>> ### >>>>>> pattern.search('dogcatcher').start() >>> 6 >>> ### >>> >>> Sorry about that! >>> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From cyresse at gmail.com Wed Mar 9 21:28:59 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 9 21:29:03 2005 Subject: [Tutor] regular expression question In-Reply-To: <f2ff2d05030912095a1b2fa3@mail.gmail.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> <f2ff2d05030912095a1b2fa3@mail.gmail.com> Message-ID: <f2ff2d0503091228555e45b4@mail.gmail.com> Actually, you should get that anyway... """ | Alternation, or the ``or'' operator. If A and B are regular expressions, A|B will match any string that matches either "A" or "B". | has very low precedence in order to make it work reasonably when you're alternating multi-character strings. Crow|Servo will match either "Crow" or "Servo", not "Cro", a "w" or an "S", and "ervo". """ So, for each letter in that string, it's checking to see if any letter matches 'A' or 'B' ... the engine steps through one character at a time. sorta like - for letter in s: if letter == 'A': #Do some string stuff elif letter == 'B': #do some string stuff i.e. k = ['A','B', 'C', 'B'] for i in range(len(k)): if k[i] == 'A' or k[i]=='B': k[i]==13 print k [13, 13, 'C', 13] You can limit substitutions using an optional argument, but yeah, it seems you're expecting it to examine the string as a whole. Check out the example here - http://www.amk.ca/python/howto/regex/regex.html#SECTION000320000000000000000 Also http://www.regular-expressions.info/alternation.html Regards, Liam Clarke On Thu, 10 Mar 2005 09:09:13 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Hi Mike, > > Do you get the same results for a search pattern of 'A|B'? > > > On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall > <michael.hall@critterpixstudios.com> wrote: > > I'm having some strange results using the "or" operator. In every test > > I do I'm matching both sides of the "|" metacharacter, not one or the > > other as all documentation says it should be (the parser supposedly > > scans left to right, using the first match it finds and ignoring the > > rest). It should only go beyond the "|" if there was no match found > > before it, no? > > > > Correct me if I'm wrong, but your regex is saying "match dog, unless > > it's followed by cat. if it is followed by cat there is no match on > > this side of the "|" at which point we advance past it and look at the > > alternative expression which says to match in front of cat." > > > > However, if I run a .sub using your regex on a string contain both dog > > and cat, both will be replaced. > > > > A simple example will show what I mean: > > > > >>> import re > > >>> x = re.compile(r"(A) | (B)") > > >>> s = "X R A Y B E" > > >>> r = x.sub("13", s) > > >>> print r > > X R 13Y13 E > > > > ...so unless I'm understanding it wrong, "B" is supposed to be ignored > > if "A" is matched, yet I get both matched. I get the same result if I > > put "A" and "B" within the same group. > > > > > > On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: > > > > > > > > > > >> > > >> Regular expressions are a little evil at times; here's what I think > > >> you're > > >> thinking of: > > >> > > >> ### > > >>>>> import re > > >>>>> pattern = re.compile(r"""dog(?!cat) > > >> ... | (?<=dogcat)""", re.VERBOSE) > > >>>>> pattern.match('dogman').start() > > >> 0 > > >>>>> pattern.search('dogcatcher').start() > > > > > > > > > > > > Hi Mike, > > > > > > Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually does > > > come up with a result: > > > > > > ### > > >>>> pattern.search('dogcatcher').start() > > > 6 > > > ### > > > > > > Sorry about that! > > > > > > > _______________________________________________ > > 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. > -- '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. From cyresse at gmail.com Wed Mar 9 21:30:16 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 9 21:30:20 2005 Subject: [Tutor] regular expression question In-Reply-To: <f2ff2d0503091228555e45b4@mail.gmail.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> <f2ff2d05030912095a1b2fa3@mail.gmail.com> <f2ff2d0503091228555e45b4@mail.gmail.com> Message-ID: <f2ff2d05030912302e6093aa@mail.gmail.com> Oops I mean for i in range(len(k)): i f k[i] == 'A' or k[i]=='B': k[i ]= 13 On Thu, 10 Mar 2005 09:28:59 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Actually, you should get that anyway... > > """ > | > Alternation, or the ``or'' operator. If A and B are regular > expressions, A|B will match any string that matches either "A" or "B". > | has very low precedence in order to make it work reasonably when > you're alternating multi-character strings. Crow|Servo will match > either "Crow" or "Servo", not "Cro", a "w" or an "S", and "ervo". > """ > > So, for each letter in that string, it's checking to see if any letter > matches 'A' or 'B' ... > the engine steps through one character at a time. > sorta like - > > for letter in s: > if letter == 'A': > #Do some string stuff > elif letter == 'B': > #do some string stuff > > i.e. > > k = ['A','B', 'C', 'B'] > > for i in range(len(k)): > if k[i] == 'A' or k[i]=='B': > k[i]==13 > > print k > > [13, 13, 'C', 13] > > You can limit substitutions using an optional argument, but yeah, it > seems you're expecting it to examine the string as a whole. > > Check out the example here - > http://www.amk.ca/python/howto/regex/regex.html#SECTION000320000000000000000 > > Also > > http://www.regular-expressions.info/alternation.html > > Regards, > > Liam Clarke > > > On Thu, 10 Mar 2005 09:09:13 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > Hi Mike, > > > > Do you get the same results for a search pattern of 'A|B'? > > > > > > On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall > > <michael.hall@critterpixstudios.com> wrote: > > > I'm having some strange results using the "or" operator. In every test > > > I do I'm matching both sides of the "|" metacharacter, not one or the > > > other as all documentation says it should be (the parser supposedly > > > scans left to right, using the first match it finds and ignoring the > > > rest). It should only go beyond the "|" if there was no match found > > > before it, no? > > > > > > Correct me if I'm wrong, but your regex is saying "match dog, unless > > > it's followed by cat. if it is followed by cat there is no match on > > > this side of the "|" at which point we advance past it and look at the > > > alternative expression which says to match in front of cat." > > > > > > However, if I run a .sub using your regex on a string contain both dog > > > and cat, both will be replaced. > > > > > > A simple example will show what I mean: > > > > > > >>> import re > > > >>> x = re.compile(r"(A) | (B)") > > > >>> s = "X R A Y B E" > > > >>> r = x.sub("13", s) > > > >>> print r > > > X R 13Y13 E > > > > > > ...so unless I'm understanding it wrong, "B" is supposed to be ignored > > > if "A" is matched, yet I get both matched. I get the same result if I > > > put "A" and "B" within the same group. > > > > > > > > > On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: > > > > > > > > > > > > > > >> > > > >> Regular expressions are a little evil at times; here's what I think > > > >> you're > > > >> thinking of: > > > >> > > > >> ### > > > >>>>> import re > > > >>>>> pattern = re.compile(r"""dog(?!cat) > > > >> ... | (?<=dogcat)""", re.VERBOSE) > > > >>>>> pattern.match('dogman').start() > > > >> 0 > > > >>>>> pattern.search('dogcatcher').start() > > > > > > > > > > > > > > > > Hi Mike, > > > > > > > > Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually does > > > > come up with a result: > > > > > > > > ### > > > >>>> pattern.search('dogcatcher').start() > > > > 6 > > > > ### > > > > > > > > Sorry about that! > > > > > > > > > > _______________________________________________ > > > 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. > > > > -- > '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. > -- '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. From michael.hall at critterpixstudios.com Wed Mar 9 22:01:28 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 9 22:01:16 2005 Subject: [Tutor] regular expression question In-Reply-To: <f2ff2d0503091228555e45b4@mail.gmail.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> <f2ff2d05030912095a1b2fa3@mail.gmail.com> <f2ff2d0503091228555e45b4@mail.gmail.com> Message-ID: <93f651b6345cfa063ed4115f15785a5b@critterpixstudios.com> > but yeah, it > seems you're expecting it to examine the string as a whole. I guess I was, good point. On Mar 9, 2005, at 12:28 PM, Liam Clarke wrote: > Actually, you should get that anyway... > > """ > | > Alternation, or the ``or'' operator. If A and B are regular > expressions, A|B will match any string that matches either "A" or "B". > | has very low precedence in order to make it work reasonably when > you're alternating multi-character strings. Crow|Servo will match > either "Crow" or "Servo", not "Cro", a "w" or an "S", and "ervo". > """ > > So, for each letter in that string, it's checking to see if any letter > matches 'A' or 'B' ... > the engine steps through one character at a time. > sorta like - > > for letter in s: > if letter == 'A': > #Do some string stuff > elif letter == 'B': > #do some string stuff > > > i.e. > > k = ['A','B', 'C', 'B'] > > for i in range(len(k)): > if k[i] == 'A' or k[i]=='B': > k[i]==13 > > print k > > [13, 13, 'C', 13] > > You can limit substitutions using an optional argument, but yeah, it > seems you're expecting it to examine the string as a whole. > > > Check out the example here - > http://www.amk.ca/python/howto/regex/ > regex.html#SECTION000320000000000000000 > > Also > > http://www.regular-expressions.info/alternation.html > > Regards, > > Liam Clarke > > > On Thu, 10 Mar 2005 09:09:13 +1300, Liam Clarke <cyresse@gmail.com> > wrote: >> Hi Mike, >> >> Do you get the same results for a search pattern of 'A|B'? >> >> >> On Wed, 9 Mar 2005 11:11:57 -0800, Mike Hall >> <michael.hall@critterpixstudios.com> wrote: >>> I'm having some strange results using the "or" operator. In every >>> test >>> I do I'm matching both sides of the "|" metacharacter, not one or the >>> other as all documentation says it should be (the parser supposedly >>> scans left to right, using the first match it finds and ignoring the >>> rest). It should only go beyond the "|" if there was no match found >>> before it, no? >>> >>> Correct me if I'm wrong, but your regex is saying "match dog, unless >>> it's followed by cat. if it is followed by cat there is no match on >>> this side of the "|" at which point we advance past it and look at >>> the >>> alternative expression which says to match in front of cat." >>> >>> However, if I run a .sub using your regex on a string contain both >>> dog >>> and cat, both will be replaced. >>> >>> A simple example will show what I mean: >>> >>>>>> import re >>>>>> x = re.compile(r"(A) | (B)") >>>>>> s = "X R A Y B E" >>>>>> r = x.sub("13", s) >>>>>> print r >>> X R 13Y13 E >>> >>> ...so unless I'm understanding it wrong, "B" is supposed to be >>> ignored >>> if "A" is matched, yet I get both matched. I get the same result if >>> I >>> put "A" and "B" within the same group. >>> >>> >>> On Mar 8, 2005, at 6:47 PM, Danny Yoo wrote: >>> >>>> >>>> >>>>> >>>>> Regular expressions are a little evil at times; here's what I think >>>>> you're >>>>> thinking of: >>>>> >>>>> ### >>>>>>>> import re >>>>>>>> pattern = re.compile(r"""dog(?!cat) >>>>> ... | (?<=dogcat)""", re.VERBOSE) >>>>>>>> pattern.match('dogman').start() >>>>> 0 >>>>>>>> pattern.search('dogcatcher').start() >>>> >>>> >>>> >>>> Hi Mike, >>>> >>>> Gaaah, bad copy-and-paste. The example with 'dogcatcher' actually >>>> does >>>> come up with a result: >>>> >>>> ### >>>>>>> pattern.search('dogcatcher').start() >>>> 6 >>>> ### >>>> >>>> Sorry about that! >>>> >>> >>> _______________________________________________ >>> 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. >> > > > -- > '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 > From jfouhy at paradise.net.nz Wed Mar 9 22:18:47 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed Mar 9 22:18:53 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <797fe3d4050309101377478395@mail.gmail.com> References: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> <422F02C9.3060502@pusspaws.net> <797fe3d4050309101377478395@mail.gmail.com> Message-ID: <1110403127.422f6837b48e8@www.paradise.net.nz> > > >>> > > >>> > > >>> import os.path > > >>> print os.path.expanduser('~/memo.txt') > > C:\Documents and Settings\Administrator/memo.txt > > >>> f = open(os.path.expanduser('~/memo.txt')) > > Traceback (most recent call last): > > File "<pyshell#15>", line 1, in ? > > f = open(os.path.expanduser('~/memo.txt')) > > IOError: [Errno 2] No such file or directory: 'C:\\Documents and > > Settings\\Administrator/memo.txt' > > >>> > > > > Now starting to doubt my sanity I again re-checked C:\Documents and > > Settings\Administrator\My Documents > > and yes I do have a memo.txt there. Um --- So you have a file 'C:\Documents and Settings\Administrator\My Documents\memo.txt'... But you are attempting to open the file 'C:\Documents and Settings\Administrator\memo.txt'. There is a difference there! -- John. From kent37 at tds.net Thu Mar 10 00:02:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 10 00:02:10 2005 Subject: [Tutor] regular expression question In-Reply-To: <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> References: <Pine.LNX.4.44.0503081845540.11830-100000@hkn.eecs.berkeley.edu> <4891a73815f2e965a78ad542dfed29eb@critterpixstudios.com> Message-ID: <422F806B.6030306@tds.net> Mike Hall wrote: > A simple example will show what I mean: > > >>> import re > >>> x = re.compile(r"(A) | (B)") > >>> s = "X R A Y B E" > >>> r = x.sub("13", s) > >>> print r > X R 13Y13 E > > ...so unless I'm understanding it wrong, "B" is supposed to be ignored > if "A" is matched, yet I get both matched. I get the same result if I > put "A" and "B" within the same group. The problem is with your use of sub(), not with |. By default, re.sub() substitutes *all* matches. If you just want to substitute the first match, include the optional count parameter: >>> import re >>> s = "X R A Y B E" >>> re.sub(r"(A) | (B)", '13', s) 'X R 13Y13 E' >>> re.sub(r"(A) | (B)", '13', s, 1) 'X R 13Y B E' BTW, there is a very handy interactive regex tester that comes with Python. On Windows, it is installed at C:\Python23\Tools\Scripts\redemo.py Kent From phthenry at iglou.com Thu Mar 10 00:04:19 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Thu Mar 10 00:02:57 2005 Subject: [Tutor] getting a webpage via python In-Reply-To: <422EFA4A.1090203@tds.net> References: <20050308162129.GE2055@localhost.localdomain> <422DD7C4.1070300@tds.net> <20050308182347.GA3162@localhost.localdomain> <422DF220.7030108@tds.net> <20050308193809.GA3363@localhost.localdomain> <422E03D7.2000307@tds.net> <422EFA4A.1090203@tds.net> Message-ID: <20050309230419.GE3346@localhost.localdomain> On Wed, Mar 09, 2005 at 08:29:46AM -0500, Kent Johnson wrote: > > Kent Johnson wrote: > >Paul Tremblay wrote: > > > >>So I just make a file called /etc/router_passwords and include > >>something like > >>WRT54G username password > >> > >>Then parse the file, and supply the info to the password handler? This > >>is easy to do, and I guess it is secure. > > The book "Foundations of Python Network Programming" has a sample program > that uses a custom urllib2.HTTPPasswordMgr to ask the user for the username > and password, maybe you would like to use that? > > The examples can be downloaded from the book Web site at > http://www.apress.com/book/bookDisplay.html?bID=363 > > Look for the one called dump_info_auth.py > Thanks. There are lots of good examples in the free download examples. Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From pythontut at pusspaws.net Thu Mar 10 00:17:51 2005 From: pythontut at pusspaws.net (Dave S) Date: Thu Mar 10 00:18:01 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <1110403127.422f6837b48e8@www.paradise.net.nz> References: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> <422F02C9.3060502@pusspaws.net> <797fe3d4050309101377478395@mail.gmail.com> <1110403127.422f6837b48e8@www.paradise.net.nz> Message-ID: <422F841F.9060702@pusspaws.net> jfouhy@paradise.net.nz wrote: >>>>>>import os.path >>>>>>print os.path.expanduser('~/memo.txt') >>>>>> >>>>>> >>>C:\Documents and Settings\Administrator/memo.txt >>> >>> >>>>>>f = open(os.path.expanduser('~/memo.txt')) >>>>>> >>>>>> >>>Traceback (most recent call last): >>>File "<pyshell#15>", line 1, in ? >>>f = open(os.path.expanduser('~/memo.txt')) >>>IOError: [Errno 2] No such file or directory: 'C:\\Documents and >>>Settings\\Administrator/memo.txt' >>> >>> >>>Now starting to doubt my sanity I again re-checked C:\Documents and >>>Settings\Administrator\My Documents >>>and yes I do have a memo.txt there. >>> >>> > >Um --- > >So you have a file 'C:\Documents and Settings\Administrator\My >Documents\memo.txt'... > >But you are attempting to open the file 'C:\Documents and >Settings\Administrator\memo.txt'. > >There is a difference there! > > > mmm ... I kind of see what you mean. Does anyone have like a realy large shovel so I can dig a hole and hide ? Thanks Dave From smichr at hotmail.com Thu Mar 10 00:17:59 2005 From: smichr at hotmail.com (C Smith) Date: Thu Mar 10 00:19:12 2005 Subject: [Tutor] working with new classes In-Reply-To: <20050309110113.31FEF1E403D@bag.python.org> Message-ID: <BAY101-DAV1613F38A4E2BABB0A478D2C1510@phx.gbl> Thanks to Sean and Kent for replies. I found a site that provided some good examples, too, at http://www.cafepy.com/articles/python_attributes_and_methods/ ch03s02.html Here's a blurb from the title page: ---- wep page excerpt Shalabh Chaturvedi Copyright ? 2004 Shalabh Chaturvedi This book is part of a series: Python Types and Objects Python Attributes and Methods [you are here] ---- After playing with this for a while I get the feeling that trying to create an alternate access for the list is not the way to go. I was able to define the following methods with success... ### class Ring(list): def __init__(self,l): list.__init__(self,l) self._zero=0 def turn(self,incr=1): self._zero+=incr def __getitem__(self,i): if type(i)==int: return list.__getitem__(self,(i-self._zero)%len(self)) else: return [list.__getitem__(self,(k-self._zero)%len(self)) for k in range(i.start,i.stop,i.step)] def __setitem__(self,i,v): list.__setitem__(self,(i-self._zero)%len(self),v) def __getslice__(self,i,j): return list.__getslice__(self,(i-self._zero)%len(self),(j- self._zero)%len(self)) def __setslice__(self,i,j,v): list.__setslice__(self,(i-self._zero)%len(self),(j- self._zero)%len(self),v) def __repr__(self): return repr([self[i] for i in range(len(self))]) ### ..but then something like pop(3) pops the original element not the element in the 3rd position of the turned list: ### >>> l=Ring(range(10)) >>> l.turn(5) >>> print l [5, 6, 7, 8, 9, 0, 1, 2, 3, 4] >>> l.pop(3); print l [5, 6, 7, 8, 9, 0, 1, 2, 4] #I wanted the 8 to go ### So in the absence of being able to redefine in the class the way that indices should be computed (like the way that your own cmp function can be supplied for the sort method) it seems best to use the existing structure and either access the list by passing it indices which have been remapped: ### >>> def ring_index(i): return (i-ring_zero)%ring_length >>> l = range(10) >>> ring_length = len(l) >>> ring_zero = 3 #does a virtual shift to the right 3 elements >>> print l[ring_index(0)] 7 ### But this will only help you look at individual entries and slices that don't go across the boundaries of the list. Alternatively, the list class can be appended with helpers like 'turn' and 'segment' which can actually turn the "ring" and remove a piece from it without worrying about the endpoint: ### >>> class ring(list): def turn(self, incr=1): incr%=len(self) self[:] = self[incr:]+self[:incr] def segment(self, i, length, incr=1): length=min(len(self),length) if i+length>len(self): return self[i::incr]+self[(length-i)%incr:i+length-len(self):incr] >>> l=ring(range(20)); l.turn(3); print l [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2] >>> >>> l.segment(17,5,3) #start at 17, length of 5, stride 3 [0, 3] ### This is my first intoduction to the new class modifications...initially it seems nice to be able to wrap your methods up into a class like this rather than creating dangling functions in one's program. /c From kent37 at tds.net Thu Mar 10 00:41:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 10 00:41:46 2005 Subject: [Tutor] working with new classes In-Reply-To: <BAY101-DAV1613F38A4E2BABB0A478D2C1510@phx.gbl> References: <BAY101-DAV1613F38A4E2BABB0A478D2C1510@phx.gbl> Message-ID: <422F89B3.8050900@tds.net> C Smith wrote: > Alternatively, the list class can be appended with helpers like 'turn' > and 'segment' which can actually turn the "ring" and remove a piece > from it without worrying about the endpoint: > > ### > >>> class ring(list): > def turn(self, incr=1): > incr%=len(self) > self[:] = self[incr:]+self[:incr] > def segment(self, i, length, incr=1): > length=min(len(self),length) > if i+length>len(self): > return > self[i::incr]+self[(length-i)%incr:i+length-len(self):incr] > > >>> l=ring(range(20)); l.turn(3); print l > [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 1, 2] > >>> >>> l.segment(17,5,3) #start at 17, length of 5, stride 3 > [0, 3] > ### This certainly looks like the simplest solution. You might want to look at UserList (in module UserList in the standard library) which is a list work-alike implemented in Python. In the old days, when it wasn't possible to subclass list, you would subclass UserList instead. Looking at the source for UserList shows all the methods that have to change to make your ring class - it is a lot. Kent From bill.mill at gmail.com Thu Mar 10 01:22:28 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Mar 10 01:22:31 2005 Subject: [Tutor] Acessing files in Windows 2000 In-Reply-To: <422F841F.9060702@pusspaws.net> References: <Pine.LNX.4.44.0503081843070.11830-100000@hkn.eecs.berkeley.edu> <422F02C9.3060502@pusspaws.net> <797fe3d4050309101377478395@mail.gmail.com> <1110403127.422f6837b48e8@www.paradise.net.nz> <422F841F.9060702@pusspaws.net> Message-ID: <797fe3d40503091622379ea8d0@mail.gmail.com> > mmm ... I kind of see what you mean. > > Does anyone have like a realy large shovel so I can dig a hole and hide ? No worries, we've all been there before. Sometimes you just can't see what's right in front of your face. Don't let it stop you, or stop you from asking questions. Peace Bill Mill bill.mill at gmail.com > > Thanks > > Dave > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From advancetravel at aapt.net.au Thu Mar 10 02:17:12 2005 From: advancetravel at aapt.net.au (oscar ng) Date: Thu Mar 10 19:57:28 2005 Subject: [Tutor] Newbie in Python Message-ID: <000201c5250e$e3ae2da0$0401a8c0@JonaH> Hi, Needing help on a mail filtering system that explores the headers and text and determines which category the email falls into. The target dataset consists of four types of documents, a list of spam mail messages and a list of messages sent to various newsgroups. The four types of documents are located in different directories. Each document is formatted as an email message with the main text and two email headers: From and Subject. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050310/ee2ea6a3/attachment.html From elwis at linuxmail.org Thu Mar 10 14:24:42 2005 From: elwis at linuxmail.org (Stefan Elwesthal) Date: Thu Mar 10 19:57:42 2005 Subject: [Tutor] simple question on pywin Message-ID: <20050310132443.0658823CFD@ws5-3.us4.outblaze.com> Hi all! After years out of Python and into java it's kind of nice to get back, with some OOP beneath the belt and look upon Python simplicity again. Indeed this is a nice language I need to learn well :) To my question, I'm a penguin man but have written some simple COM script using Python on win32 and there are issues when executing it. If I run it from within PythonWin it's all swell, i get my loginbox, and a messageBox handles me corrct data entries (from an ODBC source) If I run it from Dos... i get the Dos dialogs with isn't really what I wanted for my raw_input So, i read somewhere that rename it .pyw on win32 and it'll work. Well, if I do that and doubleclick it.. nothing happens at all... so Nooooo.. Any help is greatly appreciated Best regards Stefan - junior snake Sweden -- ______________________________________________ Check out the latest SMS services @ http://www.linuxmail.org This allows you to send and receive SMS through your mailbox. Powered by Outblaze From dyoo at hkn.eecs.berkeley.edu Thu Mar 10 20:03:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 10 20:03:46 2005 Subject: [Tutor] Newbie in Python In-Reply-To: <000201c5250e$e3ae2da0$0401a8c0@JonaH> Message-ID: <Pine.LNX.4.44.0503101101080.9542-100000@hkn.eecs.berkeley.edu> On Thu, 10 Mar 2005, oscar ng wrote: > Needing help on a mail filtering system that explores the headers and > text and determines which category the email falls into. [text cut] Hi Oscar, Ok. What help do you need? You have not told us what problems you're having, so we're stuck just twiddling our thumbs. *grin* Are you already aware of projects that do this, or are you doing this for fun? The SpamBayes project has quite a bit of source code that may interest you: http://spambayes.sourceforge.net/ From kent37 at tds.net Thu Mar 10 20:53:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 10 20:53:15 2005 Subject: [Tutor] simple question on pywin In-Reply-To: <20050310132443.0658823CFD@ws5-3.us4.outblaze.com> References: <20050310132443.0658823CFD@ws5-3.us4.outblaze.com> Message-ID: <4230A5A7.8030605@tds.net> Stefan Elwesthal wrote: > If I run it from within PythonWin it's all swell, i get my loginbox, and a messageBox handles me corrct data entries (from an ODBC source) The dialog box is a feature of PythonWin, not Python. > > If I run it from Dos... i get the Dos dialogs with isn't really what I wanted for my raw_input That's what raw_input does - it uses stdin and stdout. If you want a dialog box you have to use a GUI toolkit. EasyGUI might be just what you need, is designed for easy, dialog-box user input: http://www.ferg.org/easygui/ > > So, i read somewhere that rename it .pyw on win32 and it'll work. Well, if I do that and doubleclick it.. nothing happens at all... so Nooooo.. Calling it .pyw makes it open without a console. So you are asking for console input without a console...hmmm...sounds like a bad idea to me :-) Kent From kp8 at mac.com Fri Mar 11 06:43:59 2005 From: kp8 at mac.com (kevin parks) Date: Fri Mar 11 06:44:06 2005 Subject: [Tutor] cyclically rotate a seq In-Reply-To: <20050310110107.02CD51E4014@bag.python.org> References: <20050310110107.02CD51E4014@bag.python.org> Message-ID: <06a00814fb84905368897eb9cfbc837a@mac.com> Hi folks, I am trying to cyclically rotate a seq until it reached the beginning stage again. I would like to be able to rotate in both directions and using any arbitrary interval. I think that I have this correct, but would be happy for someone to check it and also i am interested in any improvements or enhancements. It is important that this work correctly or the whole rest of my code will be in barf *^-^* hee hee. So any help would be appreciated. #!/usr/bin/env python import sys import random # cyclically rotate a sequence # -- -------------------------------------------------------- # should work on any sequence type # should work with any hop(n) interval # should also work in both directions (left or right) # -- -------------------------------------------------------- def rotate(seq, n=1): if len(seq) == 0: return seq # Normalize n, using modulo - even works for negative n n = n % len(seq) return seq[n:] + seq[:n] def test(): start = 1 x = [7, 2, 1, 0, 11, 6, 5, 4] print; print x; print '--' * 8 for i in range(len(x)): out = rotate(x, start) print out start = start + 1 if __name__ == "__main__": test() # -------- EOF -------- From kent37 at tds.net Fri Mar 11 12:04:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 11 12:04:45 2005 Subject: [Tutor] cyclically rotate a seq In-Reply-To: <06a00814fb84905368897eb9cfbc837a@mac.com> References: <20050310110107.02CD51E4014@bag.python.org> <06a00814fb84905368897eb9cfbc837a@mac.com> Message-ID: <42317B49.6030101@tds.net> kevin parks wrote: > Hi folks, > > I am trying to cyclically rotate a seq until it reached the beginning > stage again. > I would like to be able to rotate in both directions and using any > arbitrary interval. I think the code is correct but I have a few suggestions below. > > #!/usr/bin/env python > > import sys > import random > > If you make these comments into a docstring (a triple-quoted string that starts the method) then they will be accessible to IDEs, help(rotate), etc. > # cyclically rotate a sequence > # -- -------------------------------------------------------- > # should work on any sequence type > # should work with any hop(n) interval > # should also work in both directions (left or right) > # -- -------------------------------------------------------- > > def rotate(seq, n=1): > if len(seq) == 0: > return seq I would also check for seq == None. An easy way to check for both None and an empty sequence is if not seq: return seq This will reject also a few other things you probably don't care about such as the number 0 and an empty dict... > # Normalize n, using modulo - even works for negative n > n = n % len(seq) > return seq[n:] + seq[:n] > > > def test(): > start = 1 > x = [7, 2, 1, 0, 11, 6, 5, 4] > print; print x; print '--' * 8 > for i in range(len(x)): If you use for i in range(1, len(x)+1) then you don't need start, i will have the same value > out = rotate(x, start) > print out > start = start + 1 Your test is not nearly as thorough as your docs suggest. You don't test rotation by a negative number or by a number bigger than len(x). You might want to write this as a unittest so the results are checked automatically instead of you having to eyeball them each time. Here is a start: import unittest class RotateTest(unittest.TestCase): def test_rotate(self): x = [7, 2, 1, 0, 11, 6, 5, 4] out = rotate(x, 1) self.assertEquals([2, 1, 0, 11, 6, 5, 4, 7], out) out = rotate(x, -1) self.assertEquals([4, 7, 2, 1, 0, 11, 6, 5], out) if __name__ == '__main__': unittest.main() Kent From kent37 at tds.net Fri Mar 11 12:08:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 11 12:08:09 2005 Subject: [Tutor] Can you get python to force a number to remain 32 bit instead of autoconverting to type 'long'? In-Reply-To: <30646386554.20050307184738@columbus.rr.com> References: <30646386554.20050307184738@columbus.rr.com> Message-ID: <42317C15.3080008@tds.net> R. Alan Monroe wrote: > I tried to convert this pseudocode > > function IntNoise(32-bit integer: x) > x = (x<<13) ^ x; > return ( 1.0 - ( (x * (x * x * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0); > end IntNoise function > > from this website > http://freespace.virgin.net/hugo.elias/models/m_perlin.htm > > to python. But it seems to rely on wraparound within the 32 bit int. > Can you duplicate this behavior in python? If you haven't figured this out I suggest you ask on comp.lang.python. Kent From Jeff420harris00 at wmconnect.com Fri Mar 11 20:21:42 2005 From: Jeff420harris00 at wmconnect.com (Jeff420harris00@wmconnect.com) Date: Fri Mar 11 20:21:50 2005 Subject: [Tutor] Please help me get started on how to program useing python 2.4!!! Message-ID: <13f.eec6acc.2f6349c6@wmconnect.com> OK i have learned that on the python shell if you put, print "some message" the output is, some message and if you put, type> "some message" the output is, true and if you put, type< "some message" the output is, false And if you put, for, in, or and it turns orange like print dose but I don't know why? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/616cf35f/attachment.htm From Jeff420harris00 at wmconnect.com Fri Mar 11 20:26:48 2005 From: Jeff420harris00 at wmconnect.com (Jeff420harris00@wmconnect.com) Date: Fri Mar 11 20:26:55 2005 Subject: [Tutor] and once i have learned how to program ? Message-ID: <84.411fa2ab.2f634af8@wmconnect.com> Once i have learned how to program what can i do with the programs can they run out side of the python shell like on My OS or a game? My OS is window XP home -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/bbf61e62/attachment.html From phthenry at iglou.com Fri Mar 11 21:12:27 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Fri Mar 11 21:10:57 2005 Subject: [Tutor] and once i have learned how to program ? In-Reply-To: <84.411fa2ab.2f634af8@wmconnect.com> References: <84.411fa2ab.2f634af8@wmconnect.com> Message-ID: <20050311201227.GB4462@localhost.localdomain> On Fri, Mar 11, 2005 at 02:26:48PM -0500, Jeff420harris00@wmconnect.com wrote: > From: Jeff420harris00@wmconnect.com > Date: Fri, 11 Mar 2005 14:26:48 EST > To: tutor@python.org > Subject: [Tutor] and once i have learned how to program ? > > Once i have learned how to program what can i do with the programs can they > run out side of the python shell like on My OS or a game? My OS is window XP > home Yes, python will act like any other program, such as C++. If you want to use python to run a gui (graphical user interface), then you would use Tinker. Just to give you an idea, I just downloaded a program called skencil. I get in the shell and type "skencil". I then get a window for to draw in. I take my mouse and make lines and drawings. I point my mouse to the file window and pull down the menu for save to save my document. So the application works exactly like, say, Adobe Draw, with small difference that I had to start it form my shell. I'm pretty sure there are ways to start applications without a shell. That isn't too hard. The hard part is writing a program with a graphical interface. This is always hard, in any languge. Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From askoose at sandia.gov Fri Mar 11 21:43:06 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Fri Mar 11 21:43:44 2005 Subject: [Tutor] and once i have learned how to program ? Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0AEE9B@ES21SNLNT.srn.sandia.gov> http://starship.python.net/crew/theller/py2exe/ This website is a good starting point. Ara -----Original Message----- From: tutor-bounces@python.org on behalf of Jeff420harris00@wmconnect.com Sent: Fri 3/11/2005 12:26 PM To: tutor@python.org Subject: [Tutor] and once i have learned how to program ? Once i have learned how to program what can i do with the programs can they run out side of the python shell like on My OS or a game? My OS is window XP home -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/e1c32a60/attachment.html From jannee at brikks.com Fri Mar 11 21:57:13 2005 From: jannee at brikks.com (=?iso-8859-1?Q?Jan_Ekstr=F6m?=) Date: Fri Mar 11 21:57:16 2005 Subject: [Tutor] Installing Python Message-ID: <001001c5267c$e6b63c30$25e7e953@D7M46F1J> I have tried to install Python 2.4 on two pc-s and get this error when I follow the instruction and type python at the comand window or Idle window. I am running Windows xp home edition. What am I doing wrong? I have also ask for explanation on Googles and got the answer that there is such a problem but can'not understand the message. Sincerely Jan Ekstr?m Here is the error. IDLE 1.1 >>> python Traceback (most recent call last): File "<pyshell#0>", line 1, in -toplevel-python NameError: name 'python' is not defined >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/f7581846/attachment.htm From dyoo at hkn.eecs.berkeley.edu Fri Mar 11 22:07:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 11 22:07:27 2005 Subject: [Tutor] Please help me get started on how to program useing python 2.4!!! In-Reply-To: <13f.eec6acc.2f6349c6@wmconnect.com> Message-ID: <Pine.LNX.4.44.0503111239190.22934-100000@hkn.eecs.berkeley.edu> On Fri, 11 Mar 2005 Jeff420harris00@wmconnect.com wrote: > OK i have learned that on the python shell if you put, print "some > message" the output is, some message Hi Jeff, Ok, yes, that looks right. Let me do that myself: ### >>> print "hello world" hello world ### (The '>>>' thing is what the Python shell prints out, as a "prompt" to tell me that it's ready to read more commands). > and if you put, type > "some message" the output is, true > > and if you put, type< "some message" the output is, false Hmmmm! Let me make sure I understand: are you doing this? ### >>> type < "some message" False >>> >>> >>> type > "some message" True ### What we are asking Python here is actually a bit weird: we are asking it to compare the 'type' function to see if it's either "less than" or "greater than" the string 'some message'. Did you get these expressions from some online tutorial? If so, point us to that tutorial, so I can bonk the author. *grin* How are you learning Python? Are you going through a book, or through some web page tutorial? [Note for advanced users: I know that Python will give something that will return some consistent result. According to: http://www.python.org/doc/ref/comparisons.html "Most other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program." So what Jeff is seeing is a completely arbitrary result, and it's not even guaranteed to be the same between program executions! That's why I think it's the wrong thing to show because it's hard to explain. And I think it's a terrible idea to show something like that to a beginner since it's not something that a sensible programmer would normally do anyway.] Jeff, I think it might make more sense to compare two things that are the same kind of thing. For example, it should make more sense to compare two numbers to see if one is bigger than the other: ### >>> 1 > 2 False >>> 2 > 1 True ### When we ask: "Is the number 'one' greater than the number 'two'?", Python is telling us "No!" by giving us back the value 'False'. Whenever we ask Python a question that's a yes/no sort of thing, Python will respond with a value like 'True' or 'False'. We can also compare strings to see if a word is "bigger" than another word, based on where it might be located in a dictionary. For example: ### >>> "application" < "applied" True >>> "applied" < "application" False ### In technical terms, we are giving Python expressions that "evaluate" to a "boolean" value: we're asking Python questions, and it's saying True or False. Does this make sense so far? If not, please continue to ask questions, and we'll try to show things more clearly. > And if you put, for, in, or and it turns orange like print dose but I > don't know why? If you're using IDLE, then stuff that shows up as orange when it's a special kind of "keyword". A keyword is a word that Python knows is a special word. When you learn more about Python, you'll see a few more of these keywords. The orange coloring is there just to make them stand out from the rest of your program, and doesn't have any other significance, other than just being colorful. *grin* If you have questions on any of this, please feel free to ask. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Fri Mar 11 22:11:21 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 11 22:11:30 2005 Subject: [Tutor] Installing Python In-Reply-To: <001001c5267c$e6b63c30$25e7e953@D7M46F1J> Message-ID: <Pine.LNX.4.44.0503111307360.22934-100000@hkn.eecs.berkeley.edu> On Fri, 11 Mar 2005, [iso-8859-1] Jan Ekstr=F6m wrote: > I have tried to install Python 2.4 on two pc-s and get this error when I > follow the instruction and type python at the comand window or Idle > window. I am running Windows xp home edition. What am I doing wrong? >> > Here is the error. > IDLE 1.1 > >>> python > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in -toplevel-python > NameError: name 'python' is not defined Hi Jan, If you see that message, you're actually ok, because you're already in Python! *grin* When you see the '>>> ' prompt, you're in Python's system. You're doing fine. By the way, you may find this tutorial helpful: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html It's a little outdated; one of these days, I will update the screenshots and fix some of the menu commands. (For example, "Run Script" moved over into the "Run" menu, and is renamed to "Run Module".) If you have more questions, please feel free to ask! From bvande at po-box.mcgill.ca Sat Mar 12 00:23:09 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Mar 12 00:23:31 2005 Subject: [Tutor] Please help me get started on how to program useing python 2.4!!! In-Reply-To: <Pine.LNX.4.44.0503111239190.22934-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503111239190.22934-100000@hkn.eecs.berkeley.edu> Message-ID: <4232285D.2040505@po-box.mcgill.ca> Danny Yoo said unto the world upon 2005-03-11 16:07: > > On Fri, 11 Mar 2005 Jeff420harris00@wmconnect.com wrote: <SNIP> > When we ask: "Is the number 'one' greater than the number 'two'?", Python > is telling us "No!" by giving us back the value 'False'. Whenever we ask > Python a question that's a yes/no sort of thing, Python will respond with > a value like 'True' or 'False'. > > > We can also compare strings to see if a word is "bigger" than another > word, based on where it might be located in a dictionary. For example: > > ### > >>>>"application" < "applied" > > True > >>>>"applied" < "application" > > False > ### A slight refinement of what Danny said: for strings, comparisons determine which string is "bigger" based on a concept of `dictionary order' where x is `bigger' than y if it comes later in a dictionary which puts uppercase letters before lower case ones. Hence: >>> 'z' < 'a' False >>> 'Z' < 'a' True >>> Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Sat Mar 12 00:38:40 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 12 00:38:44 2005 Subject: [Tutor] Installing Python....Getting Started (fwd) Message-ID: <Pine.LNX.4.44.0503111537410.2758-100000@hkn.eecs.berkeley.edu> [Forwarding to tutor@python.org. When you are replying to a message, please use your email's "Reply-to-All" feature so that your message reaches both me and the mailing list.] ---------- Forwarded message ---------- Date: Fri, 11 Mar 2005 22:38:55 +0100 From: Jan Ekstr?m <jannee@brikks.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] Installing Python....Getting Started Thank you for Your answer. I felt fresh air in my face. I got the instruction to start like this below.................... What will we cover? How to start Python and what an error message looks like - just in case... For the next set of exercises I will assume you have a properly installed version of Python on your computer. If not, go fetch the latest version from the Python web site and follow the install instructions for your platform. Now from a command prompt type python and the Python prompt should appear looking something like this: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Alternatively you might find a shortcut to something called IDLE, or the Python GUI, in your start menus. If you start IDLE instead of the command line version you will get a similar prompt but in a window of its own and with some pretty font colors! Danny Yoo has written a pretty good IDLE Tutorial to get you started with IDLE and I recommend you pay it a visit if you want to stick with it rather than the basic command prompt. It duplicates some of the early material here but repetition of the basics is no bad thing! Jan ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Jan Ekstr?m" <jannee@brikks.com> Cc: <tutor@python.org> Sent: Friday, March 11, 2005 10:11 PM Subject: Re: [Tutor] Installing Python On Fri, 11 Mar 2005, [iso-8859-1] Jan Ekstrm wrote: > I have tried to install Python 2.4 on two pc-s and get this error when I > follow the instruction and type python at the comand window or Idle > window. I am running Windows xp home edition. What am I doing wrong? >> > Here is the error. > IDLE 1.1 > >>> python > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in -toplevel-python > NameError: name 'python' is not defined Hi Jan, If you see that message, you're actually ok, because you're already in Python! *grin* When you see the '>>> ' prompt, you're in Python's system. You're doing fine. By the way, you may find this tutorial helpful: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html It's a little outdated; one of these days, I will update the screenshots and fix some of the menu commands. (For example, "Run Script" moved over into the "Run" menu, and is renamed to "Run Module".) If you have more questions, please feel free to ask! From dyoo at hkn.eecs.berkeley.edu Sat Mar 12 00:39:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 12 00:40:00 2005 Subject: [Tutor] Please help me get started on how to program useing python 2.4!!! (fwd) Message-ID: <Pine.LNX.4.44.0503111539040.2758-100000@hkn.eecs.berkeley.edu> [Forwarding to tutor@python.org. Please use your email client's "Reply-to-all" feature whenever you're replying to messages on the tutor list. Otherwise, no one else gets to see your questions.] ---------- Forwarded message ---------- Date: Fri, 11 Mar 2005 17:07:15 EST From: Jeff420harris00@wmconnect.com To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] Please help me get started on how to program useing python 2.4!!! ok i understand some of that like the = things being ture or false but i am not realy wanting to know if its = or not, i was just trying to figer out how to make a progarm or just program... and figer out the language..lol.....if you can help me do that i would be realy thankful From dyoo at hkn.eecs.berkeley.edu Sat Mar 12 00:40:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Mar 12 00:40:26 2005 Subject: [Tutor] Please help me get started on how to program useing python 2.4!!! (fwd) Message-ID: <Pine.LNX.4.44.0503111540010.2758-100000@hkn.eecs.berkeley.edu> [Forwarding to tutor@python.org. Sorry about the repetition.] ---------- Forwarded message ---------- Date: Fri, 11 Mar 2005 17:18:03 EST From: Jeff420harris00@wmconnect.com To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] Please help me get started on how to program useing python 2.4!!! ok heres where i got the for,in, and range....http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html and i tryed what it say and the...print "hello world"..and the next step works...print "here are the ten numbers from 0 to 9".....but the next dose not... for i in range(10): print i,.......... From Jeff420harris00 at wmconnect.com Sat Mar 12 01:00:24 2005 From: Jeff420harris00 at wmconnect.com (Jeff420harris00@wmconnect.com) Date: Sat Mar 12 01:00:29 2005 Subject: [Tutor] help me please!!! Message-ID: <105.5c936f61.2f638b18@wmconnect.com> Ok some thing is messed up.. when i try to open the python shell i get a error meesage saying .... socket error:connection refused and the head line at the top says IDLE subprocess error...... and then the python shell pops up with a error message on it saying..... IDLE's subprocess didn't make connention. Either IDLE can't start or personal firewall software is blocking the connection. and the head line at the top says subprocess startup error...... and i did not even have to be online to use to befor i don't know what it problem is please help me..lol......thank you!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/011e442a/attachment.htm From bvande at po-box.mcgill.ca Sat Mar 12 01:59:02 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Mar 12 01:59:12 2005 Subject: [Tutor] help me please!!! In-Reply-To: <105.5c936f61.2f638b18@wmconnect.com> References: <105.5c936f61.2f638b18@wmconnect.com> Message-ID: <42323ED5.9020107@po-box.mcgill.ca> Jeff420harris00@wmconnect.com said unto the world upon 2005-03-11 19:00: > Ok some thing is messed up.. when i try to open the python shell i get a > error meesage saying .... socket error:connection refused and the head line at the > top says IDLE subprocess error...... and then the python shell pops up with a > error message on it saying..... IDLE's subprocess didn't make connention. > Either IDLE can't start or personal firewall software is blocking the connection. > and the head line at the top says subprocess startup error...... > and i did not even have to be online to use to befor i don't know what it > problem is please help me..lol......thank you!!! > Hi, IDLE isn't the python shell. You appear to be on Windows XP. A python shell is what you get when you open a command prompt (a DOS prompt on older Windows version; I don't know XP) and type python. IDLE is a basic Integrated DeLopment Environment with an enhanced shell. The problem you are experiencing with IDLE is a known bug. When it occurs, open up your task manager (CTRL + ALT + DEL on pre-XP Windows at least) and look for a Python related process (one with python in the name). Kill it. Try launching IDLE again. You should be fine thereafter. There is more information about this bug (and a more permanent fix) in one or both of the archives of this list and of the edu-sig list. Last, as a windows user, you might be interested in PythonWin. It is part of the Windows extensions by Mark Hammond <http://starship.python.net/crew/mhammond>. The editor is a bit nicer and more featurefull than that of IDLE. If you try that and have problems running it consistently (I did) see <http://mail.python.org/pipermail/python-win32/2002-July/000460.html> Best, Brian vdB From ralfasy2k at hotmail.com Sat Mar 12 02:33:53 2005 From: ralfasy2k at hotmail.com (Ralfas Jegorovas) Date: Sat Mar 12 02:33:57 2005 Subject: [Tutor] Python on USB device Message-ID: <BAY101-F35481077400A768F6BC7A2E4540@phx.gbl> Hi everyone, I would like to know if it is possible to install python on a usb device and run it. I found some references to this topic in the archives but I didnt find the information conclusive. Any information would be appreciated. Ralf From bvande at po-box.mcgill.ca Sat Mar 12 03:03:20 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Mar 12 03:06:59 2005 Subject: [Tutor] help me please!!! In-Reply-To: <146.409e82d0.2f639e29@wmconnect.com> References: <146.409e82d0.2f639e29@wmconnect.com> Message-ID: <42324DE8.50409@po-box.mcgill.ca> Jeff420harris00@wmconnect.com said unto the world upon 2005-03-11 20:21: > ok i just restarted my pc and it works now thank you ..ok when i go to the > start menu then go to all programs then to python 2.4 it gives me five things ok > it says IDLE (python GUI) > Module Docs > python (command line) > python manuals > uninstall python > When i click on IDLE (python GUI) the screan pops up and at the top it say > python shell > *PLEASE* Reply to All. (For the reasons Danny Yoo mentioned. More than once.) Yes, the window that pops up and is entitled 'Python Shell' is IDLE's enhanced python shell. I believe that 'python shell' (without further modification) is conventionally understood to mean the bare Python shell one gets from clicking on Python (command line). (That is the same you get by opening a DOS box and typing Python.) The IDLE shell is only a part of the IDLE program. (Try File->New Window. Now you've got an IDLE editor window where you can write, save, and load scripts.[1].) The IDLE shell is enhanced by things such as syntax highlighting, and, compared to the bare shell on my Windows version at least, a scrollable and saveable history. There are also things that won't work well from the IDLE shell -- since it is itself a Python Tkinter GUI program, running a Tkinter GUI program from within it doesn't work too well. [1] To stave off future worries -- when saving a script from IDLE, you have to explicitly give it the .py extension if you want your script to have it. (You do -- it makes it runable in Windows by double-click on the icon and tells IDLE to use the Python syntax highlighting which makes editing Python code much easier.) Best, Brian vdB From bvande at po-box.mcgill.ca Sat Mar 12 03:18:02 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Mar 12 03:18:22 2005 Subject: [Tutor] Python on USB device In-Reply-To: <BAY101-F35481077400A768F6BC7A2E4540@phx.gbl> References: <BAY101-F35481077400A768F6BC7A2E4540@phx.gbl> Message-ID: <4232515A.7060709@po-box.mcgill.ca> Ralfas Jegorovas said unto the world upon 2005-03-11 20:33: > Hi everyone, > > I would like to know if it is possible to install python on a usb device > and run it. I found some references to this topic in the archives but I > didnt find the information conclusive. Any information would be > appreciated. > > Ralf > > <http://www.voidspace.org.uk/python/movpy/> is the home of Movable Python developed by Michael Foord and Bruno Thoorens. I've not tried it, but I do know that the contact developer (Foord AKA Fuzzyman) is a very friendly and helpful guy, who would almost certainly be happy to help you if you get stuck. (I would be interested to hear how it went if you do try it.) Best, Brian vdB From ralfasy2k at hotmail.com Sat Mar 12 04:01:33 2005 From: ralfasy2k at hotmail.com (Ralfas Jegorovas) Date: Sat Mar 12 04:01:37 2005 Subject: [Tutor] Python on USB device In-Reply-To: <4232515A.7060709@po-box.mcgill.ca> Message-ID: <BAY101-F3592D6ECB0675D742B1829E4540@phx.gbl> I have just downloaded the package and from what I've seen of it, it looks excellent. As a bonus it is quite well documented (always a good thing :-) ). I'll spend more time playing with it tommorow hopefully. Thanks for your help. All the best, Ralf From mark.kels at gmail.com Sat Mar 12 14:04:38 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Mar 12 14:04:42 2005 Subject: [Tutor] Whats so good about OOP ? Message-ID: <c225925305031205042d1f6ce4@mail.gmail.com> Hi list ! I want to know whats so great in OOP... I have learned some of it, but I don't understand why everybody like it so much... Can anyone give me an example for a task that could be done only with OOP or will be much simpler to do with it ? Thanks in advance. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From billk at fastmail.fm Sat Mar 12 15:24:21 2005 From: billk at fastmail.fm (Bill Kranec) Date: Sat Mar 12 15:24:17 2005 Subject: [Tutor] Whats so good about OOP ? In-Reply-To: <c225925305031205042d1f6ce4@mail.gmail.com> References: <c225925305031205042d1f6ce4@mail.gmail.com> Message-ID: <Pine.WNT.4.62.0503120850410.3008@Desktop> Hi Mark, In my brief experience with OOP, I would say that the main advantage is organization of code. All functions and attributes that you need to work with an object are wrapped up nicely inside the object. Also, object inheritance provides a great framework for easy customization. For example, to write some code to model a car, you might use an object: class car: def __init__( self, name ): self.name = name self.numberOfDoors = 4 self.milesPerGallon = 25 def drive( self, time ): print self.name+' drove for '+str(time)+' hours, and used '\ +str(self.milesPerGallon*time)+' gallons of gas.' In this example, the drive function will only be accessible to things that we have defined as cars. You can also have specialized versions of the car class (for example, to model a Porsche) which have different attributes ( self.milesPerGallon = 15 ), but have the same methods (you still want the drive() method). Note that this task isn't necessarily easier to do with OOP, (you could just as easily define a function which takes all of the attributes as inputs), but I believe the structure is clearer, and you get the added bonus of expandability. I hope my example has been helpful, and that someone here will correct me if I've said something wrong. Good luck using OOP! Bill On Sat, 12 Mar 2005, Mark Kels wrote: > Hi list ! > I want to know whats so great in OOP... > I have learned some of it, but I don't understand why everybody like > it so much... > Can anyone give me an example for a task that could be done only with > OOP or will be much simpler to do with it ? > > Thanks in advance. > > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Mar 12 16:00:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 12 16:00:31 2005 Subject: [Tutor] Whats so good about OOP ? In-Reply-To: <c225925305031205042d1f6ce4@mail.gmail.com> References: <c225925305031205042d1f6ce4@mail.gmail.com> Message-ID: <42330408.7060008@tds.net> Mark Kels wrote: > Hi list ! > I want to know whats so great in OOP... > I have learned some of it, but I don't understand why everybody like > it so much... - One of the great challenges in programming is managing complexity. A program of any size is too complex to hold in your brain all at once. Techniques for breaking up a program into understandable pieces are essential. OOP gives you a way to break up a program into self-contained bundles of code and data that become building blocks for other pieces of the program. OOP lets you create abstractions that become components or tools for other abstractions. - OOP enables many techniques for organizing code and reducing duplication. Many design patterns use cooperating objects. For example Composite, Decorator, Facade, Proxy, Chain of Responsibility, Command, Mediator, Observer, State, Strategy, Template Method... :-) http://c2.com/cgi-bin/wiki?CategoryPattern > Can anyone give me an example for a task that could be done only with > OOP or will be much simpler to do with it ? See this essay for some simple examples: http://www.pycs.net/users/0000323/stories/15.html Most modern GUI toolkits are heavily object-oriented including Tkinter and wxPython. Having a widget as a clear abstraction is very useful. Much of the Python standard library is object-oriented. Since Python offers a choice between object-oriented and procedural style, if a library module is implemented with objects then presumably the author thought it would be simpler that way. Of course Python is profoundly object-oriented in its core - strings, integers, lists and dicts are all objects providing simple abstractions of complex behaviour. Kent From jannee at brikks.com Sat Mar 12 18:06:38 2005 From: jannee at brikks.com (=?utf-8?Q?Jan_Ekstr=C3=B6m?=) Date: Sat Mar 12 18:06:42 2005 Subject: [Tutor] Installing Python....Getting Started (fwd)....sorry References: <Pine.LNX.4.44.0503111537410.2758-100000@hkn.eecs.berkeley.edu> Message-ID: <003301c52725$dac453e0$25e7e953@D7M46F1J> I didn't understand. But now I think I have done right. Answer all is an alternative to answer. Sorry for your trouble. Jan ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Tutor" <tutor@python.org> Cc: <jannee@brikks.com> Sent: Saturday, March 12, 2005 12:38 AM Subject: Re: [Tutor] Installing Python....Getting Started (fwd) [Forwarding to tutor@python.org. When you are replying to a message, please use your email's "Reply-to-All" feature so that your message reaches both me and the mailing list.] ---------- Forwarded message ---------- Date: Fri, 11 Mar 2005 22:38:55 +0100 From: Jan Ekstr?m <jannee@brikks.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] Installing Python....Getting Started Thank you for Your answer. I felt fresh air in my face. I got the instruction to start like this below.................... What will we cover? How to start Python and what an error message looks like - just in case... For the next set of exercises I will assume you have a properly installed version of Python on your computer. If not, go fetch the latest version from the Python web site and follow the install instructions for your platform. Now from a command prompt type python and the Python prompt should appear looking something like this: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Alternatively you might find a shortcut to something called IDLE, or the Python GUI, in your start menus. If you start IDLE instead of the command line version you will get a similar prompt but in a window of its own and with some pretty font colors! Danny Yoo has written a pretty good IDLE Tutorial to get you started with IDLE and I recommend you pay it a visit if you want to stick with it rather than the basic command prompt. It duplicates some of the early material here but repetition of the basics is no bad thing! Jan ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Jan Ekstr?m" <jannee@brikks.com> Cc: <tutor@python.org> Sent: Friday, March 11, 2005 10:11 PM Subject: Re: [Tutor] Installing Python On Fri, 11 Mar 2005, [iso-8859-1] Jan Ekstrm wrote: > I have tried to install Python 2.4 on two pc-s and get this error when I > follow the instruction and type python at the comand window or Idle > window. I am running Windows xp home edition. What am I doing wrong? >> > Here is the error. > IDLE 1.1 > >>> python > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in -toplevel-python > NameError: name 'python' is not defined Hi Jan, If you see that message, you're actually ok, because you're already in Python! *grin* When you see the '>>> ' prompt, you're in Python's system. You're doing fine. By the way, you may find this tutorial helpful: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html It's a little outdated; one of these days, I will update the screenshots and fix some of the menu commands. (For example, "Run Script" moved over into the "Run" menu, and is renamed to "Run Module".) If you have more questions, please feel free to ask! From bvande at po-box.mcgill.ca Sat Mar 12 18:53:39 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Mar 12 19:18:14 2005 Subject: [Tutor] Whats so good about OOP ? In-Reply-To: <c225925305031205042d1f6ce4@mail.gmail.com> References: <c225925305031205042d1f6ce4@mail.gmail.com> Message-ID: <42332CA3.7060604@po-box.mcgill.ca> Mark Kels said unto the world upon 2005-03-12 08:04: > Hi list ! I want to know whats so great in OOP... I have learned > some of it, but I don't understand why everybody like it so much... > Can anyone give me an example for a task that could be done only > with OOP or will be much simpler to do with it ? > > Thanks in advance. > Hi Mark and all, I've fairly recently began to use OOP myself. In addition to the organization and reusability mentioned by Kent and Bill, I'd mention the instance namespace and subclass specialization. 1) Namespace issues With procedural (or imperative -- don't know which is the right terms for non-OOP code which employs functions) code, you can have issues caused by namespaces. Just yesterday, someone on the main python list/newsgroup had code something like: .>> a = 1 .>> b = 2 .>> def silly(): ... if a: ... b = b + 1 ... .>> silly() Traceback (most recent call last): File "<interactive input>", line 1, in ? File "<interactive input>", line 3, in silly UnboundLocalError: local variable 'b' referenced before assignment .>> This raises an exception, because the b = b + 1 line in silly() is interpreted as saying "OK, create a function local name and assign it the result of adding 1 to the function local name b -- hey wait, that doesn't exist yet! BARF." A class based approach works fine: .>> class Silly_Test: ... def __init__(self): ... self.a = 1 ... self.b = 2 ... def silly(self): ... if self.a: ... self.b = self.b + 1 ... print self.b ... .>> st = Silly_Test() .>> st.silly() 3 Similiarly, if you have functions with function local names that call other functions, without classes you often need either 1) to make the names global (and thus have less transparent code) or 2) to pass objects as arguments and return them as values (and thus have ugly noisy code) just so all of the functions can `see' all of the values that they need to know about. With classes, a few selfs but you an instance namespace which makes the issue go away. (The `selfs' felt like noisy clutter to me at first, but I soon got used to them.) 2) Specialization With a lot of help from this list, the project I recently used to get the OOP groove was a toolkit for processing files from a freeware/shareware program I use a lot. The app is a tree-style folding notebook or outliner, and every tree node has an article. Those articles might be in text, RTF, or html. I made a Node class and three subclasses Text_Node, RTF_Node and HTML_Node. When parsing a file, I then create an instance of the appropriate Node class to store a node's worth of data. This pays off when doing things which differently formatted nodes need to do differently. For instance, the application supports internal links between nodes on its tree. The links in the html formatted nodes are like html links, those in the text nodes are in a simple linking syntax the developer of the app came up with. Giving each node subclass its own create link method: def create_link(self, target): # logic to make and return a link to target goes here means that I can `tell' a node instance to create a link and trust it to make the sort of link appropriate to its own article format. With a procedural approach, there would have to be something more like: def create_link(current_node, target): current_node_format = get_node_format(current_node) if current_node_format = 'Text': return create_text_link(target) if current_node_format = 'HTML': return create_html_link(target) # and so forth A while back, on this list, Bob Gailer wrote: > Whenever you find yourself writing an if statement ask whether this > would be better handled by subclasses. I didn't get it at first, but what Bob meant were the sorts of `ifs' in def create_link(current_node, target). It turns out these are wise words. Hope there is some help in all these words :-) Brian vdB From jannee at brikks.com Sat Mar 12 19:26:11 2005 From: jannee at brikks.com (=?iso-8859-1?Q?Jan_Ekstr=F6m?=) Date: Sat Mar 12 19:26:15 2005 Subject: [Tutor] python>data>sqlite>python>data>paper Message-ID: <000801c52730$f79a5f90$25e7e953@D7M46F1J> I have looked through a lot of tutor documentation. But I would ask someone to show me python code for putting som data in a sqlite database and code showing how I get data out of such a database and finaly code for printing data on a special part of a paper. Anybody knewing? Jan -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050312/4f5c3b85/attachment.html From richard at inferspace.com Sat Mar 12 19:44:43 2005 From: richard at inferspace.com (Richard Dybowski) Date: Sat Mar 12 19:46:53 2005 Subject: [Tutor] Cannot use 'Browse PythonPath' in PythonWin Message-ID: <5.2.1.1.2.20050312182502.00a100b0@mailhost.zen.co.uk> I have installed PythonWin 2.4 via ActivePython 2.4.0.244 . My OS is Windows 98 SE. When I try to use the 'Browse PythonPath' menu item in the PythonWin IDE, I get a long error output starting with >>> Failed to execute command: from pywin.tools import browseProjects;browseProjects.Browse() Traceback (most recent call last): File "C:\PYTHON24\LIB\SITE-PACKAGES\PYTHONWIN\pywin\framework\toolmenu.py", line 103, in HandleToolCommand exec "%s\n" % pyCmd File "<string>", line 1, in ? File "C:\PYTHON24\LIB\SITE-PACKAGES\PYTHONWIN\pywin\tools\browseProjects.py", line 251, in DockablePathBrowser bar.CreateWindow(win32ui.GetMainFrame(), DockableBrowserCreator, "Path Browser", 0x8e0a) File "C:\PYTHON24\LIB\SITE-PACKAGES\PYTHONWIN\pywin\docking\DockingBar.py", line 71, in CreateWindow self.dialog = apply(childCreator, (self,) + childCreatorArgs) File "C:\PYTHON24\LIB\SITE-PACKAGES\PYTHONWIN\pywin\tools\browseProjects.py", line 245, in DockableBrowserCreator list = hl.HierInit (parent, control) [.................. continues ........................] How can I solve this problem? Richard ------------------------------- Dr Richard Dybowski 143 Village Way Pinner HA5 5AA, UK Tel: 07976 250092 From mwagman at charter.net Sat Mar 12 22:14:50 2005 From: mwagman at charter.net (Mike Wagman) Date: Sat Mar 12 22:14:55 2005 Subject: [Tutor] Code example Message-ID: <1110662090.2923.4.camel@c66.190.56.129.jvl.wi.charter.com> Trying to work on two programs that talk to each other - and just not getting the basics. Can someone please show me an example of two programs - you run one in console one - then when you run one in console two - it talks to the first program = sending a specific string instructing the first one to close. Once I have an example of that - I should be set. Thanks From keridee at jayco.net Sun Mar 13 01:20:33 2005 From: keridee at jayco.net (Jacob S.) Date: Sun Mar 13 01:20:00 2005 Subject: [Tutor] and once i have learned how to program ? References: <84.411fa2ab.2f634af8@wmconnect.com> Message-ID: <005501c52762$84cc0a90$255428cf@JSLAPTOP> In IDLE, go to File, New Window. Type in your scripts there. Go to file, click save, and save it with a py extension ex. "myscript.py" Since you're on XP, you should be able to double click on it... If you can't, then you have to go into file associations and junk like that. HTH, Jacob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050312/3c91d02a/attachment-0001.htm From alan.gauld at freenet.co.uk Sun Mar 13 01:27:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 13 01:26:56 2005 Subject: [Tutor] Code example References: <1110662090.2923.4.camel@c66.190.56.129.jvl.wi.charter.com> Message-ID: <002301c52763$790a4950$1ade8751@xp> > Can someone please show me an example of two programs - you run one in > console one - then when you run one in console two - it talks to the > first program = sending a specific string instructing the first one to > close. Look at the socket examples in the Python web pages. The sender and receiver programs are exactly what you want. If you don't understand them come back with more specific questions HTH, Alan G. From alan.gauld at freenet.co.uk Sun Mar 13 01:34:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 13 01:34:16 2005 Subject: [Tutor] Whats so good about OOP ? References: <c225925305031205042d1f6ce4@mail.gmail.com> Message-ID: <002801c52764$7cfb1610$1ade8751@xp> > Can anyone give me an example for a task that could be done only with > OOP or will be much simpler to do with it ? Anything that can be done in OOP can be done without it. But OOP makes many things easier. But OOP only really becomes useful in bigger programs. If your biggest program is less than 100 lines of code then you probably haven't hit the kinds of problems that OOP solves. Between 100 and 1000 lines you increasingly hit problems of complexity, name collisions ( two things with the same name), and writing nearly identical code lots of times. By the time you get over 1000 lines all of those problems are compounded by the fact that you can't actually keep all the details in your head anymore! Objects help bring some sanity to the procedings. Finally, once you get your head around the concept of objects being like little independant programms communicating via messages then they start to fit certain types of problem very well. THe classic case is the GUI with each window, doalog box, button, menu etc being independant objects, but with a lot of common functions and a lot of inter-communication. When you coule that to the event-driven style of most GUI toolkits then events translate easily into inter-object messages and OOP becomes a very natural way to program GUIs. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From shaleh at speakeasy.net Sun Mar 13 08:49:28 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sun Mar 13 08:51:08 2005 Subject: [Tutor] Whats so good about OOP ? In-Reply-To: <42332CA3.7060604@po-box.mcgill.ca> References: <c225925305031205042d1f6ce4@mail.gmail.com> <42332CA3.7060604@po-box.mcgill.ca> Message-ID: <4233F088.4080508@speakeasy.net> Brian van den Broek wrote: > > 1) Namespace issues > With procedural (or imperative -- don't know which is the right terms > for non-OOP code which employs functions) code, you can have issues > caused by namespaces. Just yesterday, someone on the main python > list/newsgroup had code something like: > procedural v. OO imperative v. functional In an imperative language you tell the computer what to do (imperative): "put 5 in X, use X in function foo, store foo's result in blah". The base component is an imperative statement. If you have not had an English grammar class recently imperative sentences are things like "You, bring me my supper". In a functional language, the base item is a function. foo(X(blah())) or for the lispy people (foo (x (blah))). You could do OO in a functional language. Haskell for instance has a concept of classes, user defined types, polymorphism, etc. The point is, these are two axes on the programming language chart. procedural, imperative -> C OO, functional -> OCaml (close enough anyways) From shaleh at speakeasy.net Sun Mar 13 08:57:50 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sun Mar 13 08:59:28 2005 Subject: [Tutor] Whats so good about OOP ? In-Reply-To: <c225925305031205042d1f6ce4@mail.gmail.com> References: <c225925305031205042d1f6ce4@mail.gmail.com> Message-ID: <4233F27E.1060907@speakeasy.net> Mark Kels wrote: > Hi list ! > I want to know whats so great in OOP... > I have learned some of it, but I don't understand why everybody like > it so much... > Can anyone give me an example for a task that could be done only with > OOP or will be much simpler to do with it ? > > Thanks in advance. > Other commenters on this thread have covered OO fairly well. I have one clarification detail to add. In procedural code, you spend a lot of time micromanaging: put that there blah + quz is bar etc In OO code, you tell each object how to handle its data. Then your actual program just becomes a bunch of requests for objects to talk to each other. I know, you are thinking that is how your procedural code works today. But as you program, look at how much time you are telling the pieces what their jobs are and how much time you spend telling pieces to do their jobs. For further knowledge, read the Design Patterns book. It will seem like obvious, simple ideas you already know. It did for me. It is not until you start talking to other people that you realize what you learned. I am currently reading Holub's "On Patterns". He hammers OO ideas home pretty well. As Alan Gauld said, OO does not really start to shine until you reach a certain level of complexity. It takes most people quite a while to really get into the mindset. Take it slow, get it wrong, do it again (-: We all have. From Jeff420harris00 at wmconnect.com Sat Mar 12 01:47:57 2005 From: Jeff420harris00 at wmconnect.com (Jeff420harris00@wmconnect.com) Date: Sun Mar 13 09:21:20 2005 Subject: [Tutor] help Message-ID: <13f.ef2562d.2f63963d@wmconnect.com> ok i have learned that on the python shell or new window you can type in......>>>print "hello world"...and the output is ..'hello world'.. or you can put in anything realy and it say it back to you.....is this a program or what and what is the purpose of this can you realy use this for any thing other then it just saying it back. if this is not a program please teach me what is a program and what i need to know to write them and if this is a program teach me how to write better programs i can use outside of the python shell...and i have been reading and reading web pages and they talk about languges and things but i have yet to see any languges or anything to teach me the languges....please help me....THANK YOU ALL VERY MUCH !!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/dbb754f2/attachment.html From kent37 at tds.net Sun Mar 13 14:08:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 13 14:08:37 2005 Subject: [Tutor] help In-Reply-To: <13f.ef2562d.2f63963d@wmconnect.com> References: <13f.ef2562d.2f63963d@wmconnect.com> Message-ID: <42343B50.7060306@tds.net> Jeff420harris00@wmconnect.com wrote: > * > ok i have learned that on the python shell or new window you can type > in......>>>print "hello world"...and the output is ..'hello world'.. or > you can put in anything realy and it say it back to you.....is this a > program or what and what is the purpose of this can you realy use this > for any thing other then it just saying it back. print "hello world" is a very simple program. It is traditionally used as the first program in any programming language. When you are able to run this program, you have learned a little bit about how to write a program in that language. For Python, you have learned how to install Python, how to start IDLE and how to run commands in the Python shell. The print command in general can be very useful in a larger program. It is a simple way to give feedback to the user of the program. if this is not a > program please teach me what is a program and what i need to know to > write them and if this is a program teach me how to write better > programs i can use outside of the python shell... This mailing list is not a programming class, it is a place to get help when you have a specific problem. You have to do most of the work yourself. If you are looking for someone to take your hand and teach you all about programming you should find a class. Imagine you are taking a math class. You will have a teacher, a textbook and homework. When you have problems with the homework you ask a tutor for help. and i have been reading > and reading web pages and they talk about languges and things but i have > yet to see any languges or anything to teach me the languges....please > help me....THANK YOU ALL VERY MUCH !!!!!* Try the introductions for non-programmers linked on this page: http://www.python.org/doc/Intros.html When you have specific questions or problems ask questions here. Kent From alan.gauld at freenet.co.uk Sun Mar 13 15:28:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 13 15:27:59 2005 Subject: [Tutor] help References: <13f.ef2562d.2f63963d@wmconnect.com> Message-ID: <004901c527d8$fe2f9e80$1ade8751@xp> > ok i have learned that on the python shell or new window you can type > in......>>>print "hello world"...and the output is ..'hello world'.. or you can > put in anything realy and it say it back to you.....is this a program or what Yes it is a program. And believe it or not the PC processor is actually performing literally hundreds of micro steps to do that one print statement. > and what is the purpose of this can you realy use this for any thing other then > it just saying it back. Yes, once you learn how to store data you can use print to print it back out again. A program that can't display any results is not much use! > program and what i need to know to write them and if this is a program teach me > how to write better programs i can use outside of the python shell... Try one of the non programmers tutorials on the Python web site. Mine is one example, try it, if you don't like the style try another there are several to choose from. If you find a bit you don't understand, first try it again to see if you can figure it out (best way to learn!) then if still stuck send a queston to this list. Include any error messages you get in the posting! > have been reading and reading web pages and they talk about languges and things > but i have yet to see any languges or anything to teach me the > languges....please help me....THANK YOU ALL VERY MUCH !!!!! Hopefully my tutorial and the other non-programmers ones will do just that. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From amonroe at columbus.rr.com Sun Mar 13 16:01:23 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun Mar 13 16:02:15 2005 Subject: [Tutor] help In-Reply-To: <13f.ef2562d.2f63963d@wmconnect.com> References: <13f.ef2562d.2f63963d@wmconnect.com> Message-ID: <481133210861.20050313100123@columbus.rr.com> > ok i have learned that on the python shell or new window you can type in......>>>>print "hello world"...and the output is ..'hello world'.. or you can > put in anything realy and it say it back to you.....is this a program or what Yep, that's a program. Just an ultra, ultra-simple one. > program and what i need to know to write them and if this is a program teach me > how to write better programs Have you learnt the "if" statement yet? If not, that's the next thing you want to learn. Tell us if you get stuck. Alan From nbbalane at gmail.com Sun Mar 13 18:48:25 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sun Mar 13 18:48:28 2005 Subject: [Tutor] creating a tab delimited filename Message-ID: <2cad209005031309482f03e0b6@mail.gmail.com> what does a tab delimited filename mean? how am i going to make this? also how does it differs from space delimited, csv, and others? can't really find an article that could put me in the right direction so i posted here. thanks in advance. From davholla2002 at yahoo.co.uk Sun Mar 13 19:15:56 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sun Mar 13 19:15:59 2005 Subject: [Tutor] Clear the text in an entry widget Message-ID: <20050313181557.26005.qmail@web25405.mail.ukl.yahoo.com> I have written a simple test your maths program. There is just one question, how do you clear the text in a tkinter widget ? The only way that I could do it was to create a function to create the entry widget and then have it re-created. Is there a better way. This is the way I did :- def create_entry(self): #self.label2_lbl.grid(row = 10, column = 0, columnspan = 2, sticky = W) self.answer_ent = Entry(self, width = 20) self.answer_ent.grid(row = 10, column = 2, columnspan = 4) self.answer_txt = Text(self, width = 80, height = 5) self.answer_txt.grid(row = 14, column = 2, columnspan = 4) When the user asks for another a question and when the program is initiated this is called. Send instant messages to your online friends http://uk.messenger.yahoo.com From davholla2002 at yahoo.co.uk Sun Mar 13 19:29:48 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sun Mar 13 19:29:51 2005 Subject: [Tutor] Clear the text in an entry widget In-Reply-To: 6667 Message-ID: <20050313182948.3895.qmail@web25401.mail.ukl.yahoo.com> Thanks John, That works, the problem was that I had written self.answer_ent.grid.delete(0.0, END) However when I replaced the 0.0 with a 0, it worked fine. At least I found a work around but your idea is much more elegant. David --- John Fouhy <jfouhy@paradise.net.nz> wrote: > David Holland wrote: > > I have written a simple test your maths program. > > There is just one question, how do you clear the > text > > in a tkinter widget ? > > If you have an entry widget e, then e.delete(0, END) > will clear it. > > Have a look at the docs here: > http://www.pythonware.com/library/tkinter/introduction/ > > They aren't complete, but they are the best I have > found... > > -- > John. > Send instant messages to your online friends http://uk.messenger.yahoo.com From kent37 at tds.net Sun Mar 13 19:45:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 13 19:45:13 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad209005031309482f03e0b6@mail.gmail.com> References: <2cad209005031309482f03e0b6@mail.gmail.com> Message-ID: <42348A32.3030203@tds.net> jrlen balane wrote: > what does a tab delimited filename mean? how am i going to make this? > also how does it differs from space delimited, csv, and others? I think you probably mean "tab-delimited file", not "filename". A tab-delimited file is similar to a space-delimited file. It is typically a record-oriented text file with one record per line, with fields of a record separated by tabs. Like space-delimited files, this is a very easy format to read and write. Kent > > can't really find an article that could put me in the right direction > so i posted here. thanks in advance. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Sun Mar 13 19:38:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Mar 13 19:59:39 2005 Subject: [Tutor] Terminology WAS Whats so good about OOP ? In-Reply-To: <4233F088.4080508@speakeasy.net> References: <c225925305031205042d1f6ce4@mail.gmail.com> <42332CA3.7060604@po-box.mcgill.ca> <4233F088.4080508@speakeasy.net> Message-ID: <4234889A.3080800@po-box.mcgill.ca> Sean Perry said unto the world upon 2005-03-13 02:49: > Brian van den Broek wrote: > >> >> 1) Namespace issues >> With procedural (or imperative -- don't know which is the right terms >> for non-OOP code which employs functions) code, you can have issues >> caused by namespaces. Just yesterday, someone on the main python >> list/newsgroup had code something like: >> > > procedural v. OO > imperative v. functional > > In an imperative language you tell the computer what to do (imperative): > "put 5 in X, use X in function foo, store foo's result in blah". The > base component is an imperative statement. If you have not had an > English grammar class recently imperative sentences are things like > "You, bring me my supper". > > In a functional language, the base item is a function. > > foo(X(blah())) or for the lispy people (foo (x (blah))). > > You could do OO in a functional language. Haskell for instance has a > concept of classes, user defined types, polymorphism, etc. > > The point is, these are two axes on the programming language chart. > > procedural, imperative -> C > OO, functional -> OCaml (close enough anyways) Thanks for the explanation, Sean. The reference to grammatical theory here does seem to make sense. But, relying on correspondence between the technical terms in programming/comp. sci. and other fields with similar terminology can get in the way, too. I've a background in formal logic; it took me some effort to stop being upset that in Pythonic programming parlance get_a_random_element is a "function": import random def get_a_random_element(sequence): return random.choice(sequence) (Never mind that you wouldn't really write this; I needed it to genuinely be a function for the example.) Where I come from, the output of a function is determined by the input to the function. Anyway, thanks again. Best to all, Brian vdB From maxnoel_fr at yahoo.fr Sun Mar 13 21:19:55 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Mar 13 21:19:59 2005 Subject: [Tutor] Terminology WAS Whats so good about OOP ? In-Reply-To: <4234889A.3080800@po-box.mcgill.ca> References: <c225925305031205042d1f6ce4@mail.gmail.com> <42332CA3.7060604@po-box.mcgill.ca> <4233F088.4080508@speakeasy.net> <4234889A.3080800@po-box.mcgill.ca> Message-ID: <4767acdcc37886a8537c4091e8e851af@yahoo.fr> On Mar 13, 2005, at 18:38, Brian van den Broek wrote: > Thanks for the explanation, Sean. > > The reference to grammatical theory here does seem to make sense. But, > relying on correspondence between the technical terms in > programming/comp. sci. and other fields with similar terminology can > get in the way, too. > > I've a background in formal logic; it took me some effort to stop > being upset that in Pythonic programming parlance get_a_random_element > is a "function": > > <SNIP> > Where I come from, the output of a function is determined by the input > to the function. Well, actually, your being upset at that is the exact point of functional programming languages: in functional programming, the output of a function is determined by its input, and *only* its input. Therefore, there are no side-effects (variables being one) calling a function twice with the same arguments will *always* yield the same result. The only time this paradigm is broken is (of course) when dealing with I/O. -- 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?" From dyoo at hkn.eecs.berkeley.edu Sun Mar 13 22:50:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 13 22:50:54 2005 Subject: [Tutor] Newbie in Python (fwd) Message-ID: <Pine.LNX.4.44.0503131350460.18516-100000@hkn.eecs.berkeley.edu> ---------- Forwarded message ---------- Date: Sun, 13 Mar 2005 21:58:09 +1100 From: oscar ng <advancetravel@aapt.net.au> To: 'Danny Yoo' <dyoo@hkn.eecs.berkeley.edu> Subject: RE: [Tutor] Newbie in Python Hi Danny, Thanks for the reply..i wasn't sure how this works so I am glad there is someone that might be able to help me. Because this is an university assignment I am not sure how much of help you can provide..but here it goes. I need to build a mail filtering system that detects sorts mail messages into appropriate categories, such as spam, job announcement and conference announcement. The assignment will be in two parts. In the first part you will try your own approaches to solving the problem, using the Natural Language Toolkit package for Python. In the second part, you will use the techniques learned in the classes on text classification, and compare the results of these and your own. What Is Given The target dataset consists of four types of documents, a list of spam mail messages and a list of messages sent to various newsgroups. The four types of documents are located in different directories. Each document is formatted as an email message with the main text and two email headers: From and Subject. All the HTML code has been removed. Below is an example of a message from the corpus: From: edward465tom@estpak.ee Subject: YOUR APPLICATION HAS BEEN APPROVED You Have Been APPROVED for 3 UNSECURED VISA and MASTERCARDS! Are you at least 18 Years of age? Have a Valid Social Security No? Income of at Least $99 p/week? YOU'RE APPROVED! Our Banks offer: INSTANT FREE ONLINE APPROVAL! Receive your cards in as little as TWO Weeks from Today! Just in Time for Summer Vacation! For more information on how you can get your Visa or Mastercards NOW, click on the link below: MailTo:creditcards4you@excite.com?Subject=creditcardinfo ******************************************************* If you are no longer interested in receiving information on Credit Cards or Financial Services, please click on the link below and you will be removed from our optin list. MailTo:creditcardsusa@excite.com?Subject=optoutfinancial The four categories are as follows: spam job announcements (now available) conference announcements (now available) other emails What your code should do for Part I, then, is to tokenise the files, classify the emails according to your own algorithm, and output the results of the classification. Your algorithm might specify, for example, that emails with greater than X% of capitalised words are spam. Your algorithm for this part can be quite simple; the main aim is to get the infrastructure built for Part II, and to get you thinking about what is involved in these sorts of systems. The output of your code might look as follows: 24 messages are SPAM (77% correct): msg-a-2 msg-a-3 ... 11 messages are JOB ANN (63% correct): ja-4 ja-6 ... 35 messages are CONF ANN (84% correct): ca-1 ca-3 msg-a-11 ... 9 messages are OTHER (22% correct): 10000 10001 ... ---I am stuck in understanding how I can go about opening the folder(directory) that contains all the files that I need to process for this assignment. As the folder contains sub folders ie and then the email files that need to be processed. Thanks for your time in reading this and hope to hear from you soon.. If you need more info there is a link http://www.comp.mq.edu.au/units/comp348/assignments/ass1.html -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Friday, 11 March 2005 6:04 AM To: oscar ng Cc: tutor@python.org Subject: Re: [Tutor] Newbie in Python On Thu, 10 Mar 2005, oscar ng wrote: > Needing help on a mail filtering system that explores the headers and > text and determines which category the email falls into. [text cut] Hi Oscar, Ok. What help do you need? You have not told us what problems you're having, so we're stuck just twiddling our thumbs. *grin* Are you already aware of projects that do this, or are you doing this for fun? The SpamBayes project has quite a bit of source code that may interest you: http://spambayes.sourceforge.net/ From dyoo at hkn.eecs.berkeley.edu Mon Mar 14 00:53:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 14 00:53:42 2005 Subject: [Tutor] Terminology WAS Whats so good about OOP ? In-Reply-To: <4767acdcc37886a8537c4091e8e851af@yahoo.fr> Message-ID: <Pine.LNX.4.44.0503131544010.5762-100000@hkn.eecs.berkeley.edu> > > <SNIP> > > Where I come from, the output of a function is determined by the input > > to the function. > > Well, actually, your being upset at that is the exact point of > functional programming languages: in functional programming, the output > of a function is determined by its input, and *only* its input. > Therefore, there are no side-effects (variables being one) calling a > function twice with the same arguments will *always* yield the same > result. > > The only time this paradigm is broken is (of course) when dealing > with I/O. Hi Max, Just as an off-topic tangent: the "of course" part might need qualification. *grin* Haskell, one of the main representatives of the functional programming languages, uses the concept of "monads" to handle I/O. Philip Wadler has a whole page dedicated to monads: http://homepages.inf.ed.ac.uk/wadler/topics/monads.html where I/O fits in cleanly with the functional programming paradigm. There appears to be a monad tutorial page here: http://www.nomaware.com/monads/html/ Best of wishes! From dyoo at hkn.eecs.berkeley.edu Mon Mar 14 00:59:46 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 14 00:59:50 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad209005031309482f03e0b6@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503131555410.5762-100000@hkn.eecs.berkeley.edu> On Sun, 13 Mar 2005, jrlen balane wrote: > what does a tab delimited filename mean? how am i going to make this? > also how does it differs from space delimited, csv, and others? Hello, As Kent mentioned, you probably mean "tab delimited file", which means a file whose lines are split up into columns. Each column is separated by a tab, which, in theory, should make it easy to parse. The main difference between a tab-delimited file and the others you mention is the "delimiter", the separator that's chosen to break columns apart. By the way, you might be interested in: http://www.faqs.org/docs/artu/ch05s02.html#id2901882 which talks a lot more about file formats in Unix and their relative strengths and weaknesses. Best of wishes to you! From nbbalane at gmail.com Mon Mar 14 01:37:35 2005 From: nbbalane at gmail.com (jrlen balane) Date: Mon Mar 14 01:37:38 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <Pine.LNX.4.44.0503131555410.5762-100000@hkn.eecs.berkeley.edu> References: <2cad209005031309482f03e0b6@mail.gmail.com> <Pine.LNX.4.44.0503131555410.5762-100000@hkn.eecs.berkeley.edu> Message-ID: <2cad209005031316374448d29d@mail.gmail.com> so for example, i am creating a text file with file.write() how am i going to make the file a tab-delimited file??? any parameters needed??? On Sun, 13 Mar 2005 15:59:46 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Sun, 13 Mar 2005, jrlen balane wrote: > > > what does a tab delimited filename mean? how am i going to make this? > > also how does it differs from space delimited, csv, and others? > > Hello, > > As Kent mentioned, you probably mean "tab delimited file", which means a > file whose lines are split up into columns. Each column is separated by a > tab, which, in theory, should make it easy to parse. > > The main difference between a tab-delimited file and the others you > mention is the "delimiter", the separator that's chosen to break columns > apart. > > By the way, you might be interested in: > > http://www.faqs.org/docs/artu/ch05s02.html#id2901882 > > which talks a lot more about file formats in Unix and their relative > strengths and weaknesses. > > Best of wishes to you! > > From nbbalane at gmail.com Mon Mar 14 01:38:50 2005 From: nbbalane at gmail.com (jrlen balane) Date: Mon Mar 14 01:38:53 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad209005031316374448d29d@mail.gmail.com> References: <2cad209005031309482f03e0b6@mail.gmail.com> <Pine.LNX.4.44.0503131555410.5762-100000@hkn.eecs.berkeley.edu> <2cad209005031316374448d29d@mail.gmail.com> Message-ID: <2cad2090050313163857d064e9@mail.gmail.com> specifically, I want to write an array in to a text file, how am i going to make the file a tab-delimited file??? On Mon, 14 Mar 2005 08:37:35 +0800, jrlen balane <nbbalane@gmail.com> wrote: > so for example, i am creating a text file with > file.write() > > how am i going to make the file a tab-delimited file??? any parameters needed??? > > > On Sun, 13 Mar 2005 15:59:46 -0800 (PST), Danny Yoo > <dyoo@hkn.eecs.berkeley.edu> wrote: > > > > > > On Sun, 13 Mar 2005, jrlen balane wrote: > > > > > what does a tab delimited filename mean? how am i going to make this? > > > also how does it differs from space delimited, csv, and others? > > > > Hello, > > > > As Kent mentioned, you probably mean "tab delimited file", which means a > > file whose lines are split up into columns. Each column is separated by a > > tab, which, in theory, should make it easy to parse. > > > > The main difference between a tab-delimited file and the others you > > mention is the "delimiter", the separator that's chosen to break columns > > apart. > > > > By the way, you might be interested in: > > > > http://www.faqs.org/docs/artu/ch05s02.html#id2901882 > > > > which talks a lot more about file formats in Unix and their relative > > strengths and weaknesses. > > > > Best of wishes to you! > > > > > From bvande at po-box.mcgill.ca Mon Mar 14 01:57:57 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Mar 14 01:58:03 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad209005031316374448d29d@mail.gmail.com> References: <2cad209005031309482f03e0b6@mail.gmail.com> <Pine.LNX.4.44.0503131555410.5762-100000@hkn.eecs.berkeley.edu> <2cad209005031316374448d29d@mail.gmail.com> Message-ID: <4234E195.5010103@po-box.mcgill.ca> jrlen balane said unto the world upon 2005-03-13 19:37: > so for example, i am creating a text file with file.write() > > how am i going to make the file a tab-delimited file??? any > parameters needed??? > >>> record1 = ['Foo', 'Bar', 'Baz'] >>> record2 = ['Ham', 'Spam', 'Eggs'] >>> records = [record1, record2] >>> lines = [] >>> for record in records: ... lines.append('\t'.join(record) + '\n') ... >>> lines ['Foo\tBar\tBaz\n', 'Ham\tSpam\tEggs\n'] >>> output_file = file('c:/output.txt', 'w') >>> output_file.writelines(lines) >>> output_file.close() >>> HTH, Brian vdB From dyoo at hkn.eecs.berkeley.edu Mon Mar 14 02:49:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 14 02:49:35 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <4234E195.5010103@po-box.mcgill.ca> Message-ID: <Pine.LNX.4.44.0503131742190.24065-100000@hkn.eecs.berkeley.edu> On Sun, 13 Mar 2005, Brian van den Broek wrote: > jrlen balane said unto the world upon 2005-03-13 19:37: > > so for example, i am creating a text file with file.write() > > > > how am i going to make the file a tab-delimited file??? any > > parameters needed??? > > > > >>> record1 = ['Foo', 'Bar', 'Baz'] > >>> record2 = ['Ham', 'Spam', 'Eggs'] > >>> records = [record1, record2] > >>> lines = [] > >>> for record in records: > ... lines.append('\t'.join(record) + '\n') > ... The 'csv' module might also be really handy here. For example, we can adapt the code from: http://www.python.org/doc/lib/node617.html Let me write Brian's example with 'csv', just to show how it works. ###### >>> record1 = ['Foo', 'Bar', 'Baz'] >>> record2 = ['Ham', 'Spam', 'Eggs'] >>> import sys >>> writer = csv.writer(sys.stdout) >>> for row in [record1, record2]: ... writer.writerow(row) ... Foo,Bar,Baz Ham,Spam,Eggs ###### By default, the 'csv' writer uses commas as separators, but we can set the 'dialect' of a csv writer to the 'excel-tab' dialect, which uses tabs as delimiters: ###### >>> writer = csv.writer(sys.stdout, dialect='excel-tab') >>> for row in [record1, record2]: ... writer.writerow(row) ... Foo Bar Baz Ham Spam Eggs ###### I hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Mar 14 03:03:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 14 03:03:48 2005 Subject: [Tutor] Newbie in Python (fwd) In-Reply-To: <Pine.LNX.4.44.0503131350460.18516-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503131751540.24065-100000@hkn.eecs.berkeley.edu> On Sun, 13 Mar 2005, Danny Yoo wrote: > Thanks for the reply..i wasn't sure how this works so I am glad there is > someone that might be able to help me. Because this is an university > assignment I am not sure how much of help you can provide..but here it > goes. [text cut] As you might understand, we won't do homework. We'll try to point you toward things that will help, but otherwise, our help will be very restricted. [homework problem statement cut] I'll pretend that I did not read that problem statement, since most of it is pretty much off-limits to us as Python-Tutors, and irrelevant to the question that you have given us. Let's get straight to your question. > ---I am stuck in understanding how I can go about opening the > folder(directory) that contains all the files that I need to process for > this assignment. As the folder contains sub folders ie and then the > email files that need to be processed. You may want to look at the 'os' module, http://www.python.org/doc/lib/module-os.html as it includes functions that deal with operating systems and directory managment. In particular, you may want to experiment with os.walk(): http://www.python.org/doc/lib/os-file-dir.html#l2h-1617 Other functions like os.chdir() or os.listdir() might also be useful to you, as well as the utility functions in os.path: http://www.python.org/doc/lib/module-os.path.html I suspect, though, that os.walk() should do the trick. If you have more questions, please feel free to ask. But don't just copy-and-paste problem statements from your homework: we will actively try to ignore those. We're much more interested in the questions that you have. From dyoo at hkn.eecs.berkeley.edu Mon Mar 14 03:14:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 14 03:15:07 2005 Subject: [Tutor] python>data>sqlite>python>data>paper In-Reply-To: <000801c52730$f79a5f90$25e7e953@D7M46F1J> Message-ID: <Pine.LNX.4.44.0503131808050.24065-100000@hkn.eecs.berkeley.edu> On Sat, 12 Mar 2005, [iso-8859-1] Jan Ekstr=F6m wrote: > I have looked through a lot of tutor documentation. But I would ask > someone to show me python code for putting som data in a sqlite database > and code showing how I get data out of such a database Hi Jan, You may want to look at: http://www.linuxjournal.com/articles/lj/0110/6650/6650l3.html SQLite is, by its name, a light SQL database, so you may find the documentation in: http://www.python.org/topics/database/ and, in particular: http://www.linuxjournal.com/article/2605 helpful in getting started with SQL databases. You might also find the Database Special Interest Group (DB-SIG) a valuable resource: http://www.python.org/sigs/db-sig/ > and finaly code for printing data on a special part of a paper. I think you might need to be more specific here. Can you give us more details about how you're trying to print, and what you mean by "special part"? Without any more details, I can only guess that you might be interested in the Reportlab PDF generator: http://www.reportlab.org/rl_toolkit.html but again, I have no clue what you mean yet. *grin* Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Mar 14 03:37:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 14 03:37:40 2005 Subject: [Tutor] help [Please use better subject lines than "help!"] In-Reply-To: <481133210861.20050313100123@columbus.rr.com> Message-ID: <Pine.LNX.4.44.0503131824040.24065-100000@hkn.eecs.berkeley.edu> On Sun, 13 Mar 2005, R. Alan Monroe wrote: > > ok i have learned that on the python shell or new window you can > > type in......>>>>print "hello world"...and the output is ..'hello > > world'.. or you can put in anything realy and it say it back to > > you.....is this a program or what > > Yep, that's a program. Just an ultra, ultra-simple one. > > > how to write better programs > > Have you learnt the "if" statement yet? If not, that's the next thing > you want to learn. Tell us if you get stuck. [meta: mailing list admin stuff] Hi Jeff, And when you tell us, please make the subject line a little bit more descriptive. Your last two messages had subject lines like "help!" or "help me!". We wouldn't be here if we didn't want to help. *grin* There's actually a very pratical reason why you should be more descriptive: Your messages are actually not getting through directly to the list because the mailing list software sees the naked word "help!" and thinks that it's an administrative request! Such messages get put on to a "moderation queue" that must be manually curated by some poor, brain-dead mailing list administrator. I would laugh at that person, except that I am that brain-dead mailing list admin. And I have to manually release messages that are caught in the moderation queue from time to time, which sometime explains why it looks like it takes a while for you messages to get to the list. So if you can, please make my life easier: try to make your subject headers more descriptive, like: "Is this a program?" A descriptive subject line should avoid manual moderation from the mailing list software. We're also trying to encourage good mailing list habits because all the messages on the list are archived: http://mail.python.org/pipermail/tutor/ and it is much easier for people to learn and find information from the archives if messages have useful titles. Best of wishes to you! From gopinathv at hcltech.com Mon Mar 14 04:44:18 2005 From: gopinathv at hcltech.com (Gopinath V, ASDC Chennai) Date: Mon Mar 14 04:44:19 2005 Subject: [Tutor] command for clearing user screen input Message-ID: <A125AF3F419E97458A237BE2484C3C8B1B92C478@pluto.asdc.hcltech.com> HI all, I'm trying a series of inputs ...i need to get the screen cleared after every 5 inputs...can any 1 tell me how do I do it -----Original Message----- From: tutor-request@python.org [mailto:tutor-request@python.org] Sent: Sunday, March 13, 2005 4:31 PM To: tutor@python.org Subject: Tutor Digest, Vol 13, Issue 36 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request@python.org You can reach the person managing the list at tutor-owner@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Code example (Alan Gauld) 2. Re: Whats so good about OOP ? (Alan Gauld) 3. Re: Whats so good about OOP ? (Sean Perry) 4. Re: Whats so good about OOP ? (Sean Perry) 5. help (Jeff420harris00@wmconnect.com) ---------------------------------------------------------------------- Message: 1 Date: Sun, 13 Mar 2005 00:27:42 -0000 From: "Alan Gauld" <alan.gauld@freenet.co.uk> Subject: Re: [Tutor] Code example To: "Mike Wagman" <mwagman@charter.net>, <tutor@python.org> Message-ID: <002301c52763$790a4950$1ade8751@xp> Content-Type: text/plain; charset="Windows-1252" > Can someone please show me an example of two programs - you run one in > console one - then when you run one in console two - it talks to the > first program = sending a specific string instructing the first one to > close. Look at the socket examples in the Python web pages. The sender and receiver programs are exactly what you want. If you don't understand them come back with more specific questions HTH, Alan G. ------------------------------ Message: 2 Date: Sun, 13 Mar 2005 00:34:58 -0000 From: "Alan Gauld" <alan.gauld@freenet.co.uk> Subject: Re: [Tutor] Whats so good about OOP ? To: "Mark Kels" <mark.kels@gmail.com>, <tutor@python.org> Message-ID: <002801c52764$7cfb1610$1ade8751@xp> Content-Type: text/plain; charset="iso-8859-1" > Can anyone give me an example for a task that could be done only with > OOP or will be much simpler to do with it ? Anything that can be done in OOP can be done without it. But OOP makes many things easier. But OOP only really becomes useful in bigger programs. If your biggest program is less than 100 lines of code then you probably haven't hit the kinds of problems that OOP solves. Between 100 and 1000 lines you increasingly hit problems of complexity, name collisions ( two things with the same name), and writing nearly identical code lots of times. By the time you get over 1000 lines all of those problems are compounded by the fact that you can't actually keep all the details in your head anymore! Objects help bring some sanity to the procedings. Finally, once you get your head around the concept of objects being like little independant programms communicating via messages then they start to fit certain types of problem very well. THe classic case is the GUI with each window, doalog box, button, menu etc being independant objects, but with a lot of common functions and a lot of inter-communication. When you coule that to the event-driven style of most GUI toolkits then events translate easily into inter-object messages and OOP becomes a very natural way to program GUIs. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ------------------------------ Message: 3 Date: Sat, 12 Mar 2005 23:49:28 -0800 From: Sean Perry <shaleh@speakeasy.net> Subject: Re: [Tutor] Whats so good about OOP ? To: tutor@python.org Message-ID: <4233F088.4080508@speakeasy.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Brian van den Broek wrote: > > 1) Namespace issues > With procedural (or imperative -- don't know which is the right terms > for non-OOP code which employs functions) code, you can have issues > caused by namespaces. Just yesterday, someone on the main python > list/newsgroup had code something like: > procedural v. OO imperative v. functional In an imperative language you tell the computer what to do (imperative): "put 5 in X, use X in function foo, store foo's result in blah". The base component is an imperative statement. If you have not had an English grammar class recently imperative sentences are things like "You, bring me my supper". In a functional language, the base item is a function. foo(X(blah())) or for the lispy people (foo (x (blah))). You could do OO in a functional language. Haskell for instance has a concept of classes, user defined types, polymorphism, etc. The point is, these are two axes on the programming language chart. procedural, imperative -> C OO, functional -> OCaml (close enough anyways) ------------------------------ Message: 4 Date: Sat, 12 Mar 2005 23:57:50 -0800 From: Sean Perry <shaleh@speakeasy.net> Subject: Re: [Tutor] Whats so good about OOP ? To: tutor@python.org Message-ID: <4233F27E.1060907@speakeasy.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Mark Kels wrote: > Hi list ! > I want to know whats so great in OOP... > I have learned some of it, but I don't understand why everybody like > it so much... > Can anyone give me an example for a task that could be done only with > OOP or will be much simpler to do with it ? > > Thanks in advance. > Other commenters on this thread have covered OO fairly well. I have one clarification detail to add. In procedural code, you spend a lot of time micromanaging: put that there blah + quz is bar etc In OO code, you tell each object how to handle its data. Then your actual program just becomes a bunch of requests for objects to talk to each other. I know, you are thinking that is how your procedural code works today. But as you program, look at how much time you are telling the pieces what their jobs are and how much time you spend telling pieces to do their jobs. For further knowledge, read the Design Patterns book. It will seem like obvious, simple ideas you already know. It did for me. It is not until you start talking to other people that you realize what you learned. I am currently reading Holub's "On Patterns". He hammers OO ideas home pretty well. As Alan Gauld said, OO does not really start to shine until you reach a certain level of complexity. It takes most people quite a while to really get into the mindset. Take it slow, get it wrong, do it again (-: We all have. ------------------------------ Message: 5 Date: Fri, 11 Mar 2005 19:47:57 EST From: Jeff420harris00@wmconnect.com Subject: [Tutor] help To: tutor@python.org Message-ID: <13f.ef2562d.2f63963d@wmconnect.com> Content-Type: text/plain; charset="us-ascii" ok i have learned that on the python shell or new window you can type in......>>>print "hello world"...and the output is ..'hello world'.. or you can put in anything realy and it say it back to you.....is this a program or what and what is the purpose of this can you realy use this for any thing other then it just saying it back. if this is not a program please teach me what is a program and what i need to know to write them and if this is a program teach me how to write better programs i can use outside of the python shell...and i have been reading and reading web pages and they talk about languges and things but i have yet to see any languges or anything to teach me the languges....please help me....THANK YOU ALL VERY MUCH !!!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050311/dbb754f2/attachm ent.htm ------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 13, Issue 36 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050314/fcf36836/attachment.htm From jakieabraham at yahoo.com Mon Mar 14 05:51:50 2005 From: jakieabraham at yahoo.com (Jacob Abraham) Date: Mon Mar 14 05:51:54 2005 Subject: [Tutor] funny behaviour Message-ID: <20050314045150.79740.qmail@web54106.mail.yahoo.com> Dear Tutors, A class was created to extend timedelta to add and subtract months. Simple doctests that simply create an instance of the class failed. Could someone please explain this really funny behaviour. Regards, Jacob Abraham from datetime import datetime, timedelta class WeirdTimeDelta(timedelta): """Allows addition and subtraction of months. Variables are getting passed to the timedelta constructor ?? >>> delta = WeirdTimeDelta(5) >>> delta.days 0 Should'nt this work ??? >>> delta = WeirdTimeDelta(months=5) """ def __init__(self, months=0, *vals, **kwds): """Constructs a weird time delta.""" super(WeirdTimeDelta, self).__init__(*vals, **kwds) self.months = months if __name__ == "__main__": import doctest doctest.testmod() __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Mon Mar 14 05:52:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 14 05:52:38 2005 Subject: [Tutor] command for clearing user screen input In-Reply-To: <A125AF3F419E97458A237BE2484C3C8B1B92C478@pluto.asdc.hcltech.com> References: <A125AF3F419E97458A237BE2484C3C8B1B92C478@pluto.asdc.hcltech.com> Message-ID: <4235188D.7060104@tds.net> Gopinath V, ASDC Chennai wrote: > HI all, > I'm trying a series of inputs ...i need to get the screen cleared > after every 5 inputs...can any 1 tell me how do I do it Presuming you are using some kind of console window, you can do something like print '\n' * 50 Anything fancier is platform dependent so you will have to tell us what platform you are on and if it is a console window or something else. Kent From nixonron at yahoo.com Mon Mar 14 06:26:08 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Mon Mar 14 06:26:12 2005 Subject: [Tutor] re help Message-ID: <20050314052608.80320.qmail@web20321.mail.yahoo.com> The following program takes text data like this: Jimi Hendrix 2100 South Ave Seattle, WA 55408 and changes it to this Jimi Hendrix, 2100 South Ave,Seattle,WA,55488 and writes it to a file. The problem I'm running into is that it only writes this first address to a file and there are several others in the file. I believe it has something to do with using re.search instead of re.findall. But re.findall returns a error when I try using it. Suggestions? Thanks in advance. Here is the script: import re f = open('reformat.txt').read() pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*) ([^\r\n]*) ([^\r\n]*)") x=re.search(pat,f) name = x.group(1) address = x.group(2) citystate = x.group(3)+x.group(4) zipcd = x.group(5) o= open('reformat1.txt','w') o.write("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) o.close() print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From smichr at hotmail.com Mon Mar 14 06:48:07 2005 From: smichr at hotmail.com (C Smith) Date: Mon Mar 14 06:49:17 2005 Subject: [Tutor] help In-Reply-To: <20050313110111.C36D31E4043@bag.python.org> Message-ID: <BAY101-DAV4B728931BA9486E1E8DCEC1560@phx.gbl> On Sunday, Mar 13, 2005, at 05:01 America/Chicago, tutor-request@python.org wrote: > if this is not a program please teach me what is a > program and what i need to know to write them and if this is a program > teach me > how to write better programs i can use outside of the python shell... OK, how about this for starters: http://www.ibiblio.org/obp/thinkCS/python/english/ This is an introductory html text that can act as a teacher for you. (There are some other resources at that address, too.) It is the text that I used in an introductory programming class that I taught. As you go through this you sill start to learn the answers to your questions. As to your desire to write programs you can use outside the shell...well that will come after you have an idea of what you would like to do and learn how to "say it" with a language. But at this point I think your main task will be to learn how to "say things" in general. Python is a nice language to work with in this regard. /c From hameed.u.khan at gmail.com Mon Mar 14 08:12:29 2005 From: hameed.u.khan at gmail.com (Hameed U. Khan) Date: Mon Mar 14 09:12:50 2005 Subject: [Tutor] re help In-Reply-To: <20050314052608.80320.qmail@web20321.mail.yahoo.com> References: <20050314052608.80320.qmail@web20321.mail.yahoo.com> Message-ID: <70576bd2050313231246b34385@mail.gmail.com> Hi, Ron! I am also a newbie in programming. But after reading your problem i decided to solve it as a homework :). But there are few things you didn't mentioned. Does all the addresses in first file have same format. What seperates those addresses in the file. Assuming that all address are on 3 lines seperated by a blank line (The address file should have a blank line after the last address otherwise it will not read the last address). i have made the following program. #!/usr/bin/python # format.py import re f = open("reformat.txt").read() pat = re.compile(r"((?:.*\n)+?\n)",re.M) res = pat.findall(f) out = open("reformat1.txt","w") for addy in res: addy = ", ".join(addy[:-2].split("\n")) out.write(addy + "\n") out.close() # End This program works fine on my Linux box. And hopefully it will work too on Windows. I would also ask other experienced programmers that is there any other better way we can do it :). Happy Programming. On Sun, 13 Mar 2005 21:26:08 -0800 (PST), Ron Nixon <nixonron@yahoo.com> wrote: > The following program takes text data like this: > Jimi Hendrix > 2100 South Ave > Seattle, WA 55408 > > and changes it to this > > Jimi Hendrix, 2100 South Ave,Seattle,WA,55488 > > and writes it to a file. The problem I'm running into > is that it only writes this first address to a file > and there are several others in the file. I believe it > has something to do with using re.search instead of > re.findall. But re.findall returns a error when I try > using it. Suggestions? Thanks in advance. > Here is the script: > > import re > f = open('reformat.txt').read() > pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*) > ([^\r\n]*) ([^\r\n]*)") > x=re.search(pat,f) > name = x.group(1) > address = x.group(2) > citystate = x.group(3)+x.group(4) > zipcd = x.group(5) > o= open('reformat1.txt','w') > o.write("%s,%s,%s,%s\n" % (name, address, > citystate,zipcd)) > o.close() > print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) > > > __________________________________ > Do you Yahoo!? > Yahoo! Small Business - Try our new resources site! > http://smallbusiness.yahoo.com/resources/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Hameed U. Khan Registered Linux User #: 354374 - *Computer without Linux is just like the world without computer.* From kent37 at tds.net Mon Mar 14 11:58:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 14 11:58:18 2005 Subject: [Tutor] funny behaviour In-Reply-To: <20050314045150.79740.qmail@web54106.mail.yahoo.com> References: <20050314045150.79740.qmail@web54106.mail.yahoo.com> Message-ID: <42356E44.6010406@tds.net> Jacob Abraham wrote: > Dear Tutors, > > A class was created to extend timedelta to add and > subtract months. Simple doctests that simply create an > instance of the class failed. Could someone please > explain this really funny behaviour. timedelta is an immutable class (its instances have fixed values that can't be changed). When you subclass an immutable class you have to override __new__ instead of __init__. See this link for details and examples: http://www.python.org/2.2.3/descrintro.html#__new__ Kent > > Regards, > Jacob Abraham > > from datetime import datetime, timedelta > > class WeirdTimeDelta(timedelta): > """Allows addition and subtraction of months. > > Variables are getting passed to the timedelta > constructor ?? > > >>> delta = WeirdTimeDelta(5) > >>> delta.days > 0 > > Should'nt this work ??? > > >>> delta = WeirdTimeDelta(months=5) > > """ > > def __init__(self, months=0, *vals, **kwds): > """Constructs a weird time delta.""" > super(WeirdTimeDelta, self).__init__(*vals, > **kwds) > self.months = months > > if __name__ == "__main__": > import doctest > doctest.testmod() > > __________________________________________________ > 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 > From kent37 at tds.net Mon Mar 14 12:11:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 14 12:11:11 2005 Subject: [Tutor] re help In-Reply-To: <20050314052608.80320.qmail@web20321.mail.yahoo.com> References: <20050314052608.80320.qmail@web20321.mail.yahoo.com> Message-ID: <42357149.1020405@tds.net> Ron Nixon wrote: > The following program takes text data like this: > Jimi Hendrix > 2100 South Ave > Seattle, WA 55408 > > and changes it to this > > Jimi Hendrix, 2100 South Ave,Seattle,WA,55488 > > and writes it to a file. Hameed has shown you one solution. I would like to point out that if you plan to read this data back in to a program, the format you have chosen is problematic. You can't count on the number of commas being fixed. For example, the address John Doe, Sr. 2100 South Ave Seattle WA 55408 would become John Doe, Sr.,2100 South Ave,Seattle WA,55408 If you try to split this at the commas you will not get the correct result. One solution is to use the csv module which will quote the strings containing commas. Kent The problem I'm running into > is that it only writes this first address to a file > and there are several others in the file. I believe it > has something to do with using re.search instead of > re.findall. But re.findall returns a error when I try > using it. Suggestions? Thanks in advance. > Here is the script: > > import re > f = open('reformat.txt').read() > pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*) > ([^\r\n]*) ([^\r\n]*)") > x=re.search(pat,f) > name = x.group(1) > address = x.group(2) > citystate = x.group(3)+x.group(4) > zipcd = x.group(5) > o= open('reformat1.txt','w') > o.write("%s,%s,%s,%s\n" % (name, address, > citystate,zipcd)) > o.close() > print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) > > > > __________________________________ > Do you Yahoo!? > Yahoo! Small Business - Try our new resources site! > http://smallbusiness.yahoo.com/resources/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Mar 14 14:04:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 14 14:04:14 2005 Subject: [Tutor] CGI authentication Message-ID: <42358BCA.1030700@tds.net> There was a question on this list recently about how to authenticate users of a web server from a simple CGI script. I just came across a module that might help: http://www.voidspace.org.uk/python/logintools.html Kent From jannee at brikks.com Mon Mar 14 18:45:40 2005 From: jannee at brikks.com (=?utf-8?Q?Jan_Ekstr=C3=B6m?=) Date: Mon Mar 14 18:45:44 2005 Subject: [Tutor] python>data>sqlite>python>data>paper References: <Pine.LNX.4.44.0503131808050.24065-100000@hkn.eecs.berkeley.edu> Message-ID: <000d01c528bd$a3b38b70$25e7e953@D7M46F1J> For example a balance report for a company. Regards Jan ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Jan Ekstr?m" <jannee@brikks.com> Cc: <tutor@python.org> Sent: Monday, March 14, 2005 3:14 AM Subject: Re: [Tutor] python>data>sqlite>python>data>paper On Sat, 12 Mar 2005, [iso-8859-1] Jan Ekstrm wrote: > I have looked through a lot of tutor documentation. But I would ask > someone to show me python code for putting som data in a sqlite database > and code showing how I get data out of such a database From keridee at jayco.net Mon Mar 14 23:04:33 2005 From: keridee at jayco.net (Jacob S.) Date: Mon Mar 14 23:04:11 2005 Subject: [Tutor] re help References: <20050314052608.80320.qmail@web20321.mail.yahoo.com> Message-ID: <001c01c528e1$e07ce000$265428cf@JSLAPTOP> And I wouldn't mind mentioning that re is slightly over kill for the examples given. Try this. ####################################### old_group_delimiter = "\n\n" old_line_delimiter = "\n" new_group_delimiter = "\n" new_line_delimiter = ", " fi = raw_input("Input file to use? ") fi = open(fi,"r") stuff = fi.read() fi.close() addressgroups = stuff.split(old_group_delimiter) addressgroups = [x.split(old_line_delimiter) for x in addressgroups] addressgroups = [new_line_delimiter.join(x) for x in addressgroups] newtext = new_group_delimiter.join(addressgroups) fi = raw_input("Output file to use? ") fi = open(fi,"w") fi.write(newtext) fi.close() ####################################### But your probably using re to study it, though. Just an alternative option. I'm trying to keep all the different ways in my head you know... Jacob S. > The following program takes text data like this: > Jimi Hendrix > 2100 South Ave > Seattle, WA 55408 > > and changes it to this > > Jimi Hendrix, 2100 South Ave,Seattle,WA,55488 > > and writes it to a file. The problem I'm running into > is that it only writes this first address to a file > and there are several others in the file. I believe it > has something to do with using re.search instead of > re.findall. But re.findall returns a error when I try > using it. Suggestions? Thanks in advance. > Here is the script: > > import re > f = open('reformat.txt').read() > pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*) > ([^\r\n]*) ([^\r\n]*)") > x=re.search(pat,f) > name = x.group(1) > address = x.group(2) > citystate = x.group(3)+x.group(4) > zipcd = x.group(5) > o= open('reformat1.txt','w') > o.write("%s,%s,%s,%s\n" % (name, address, > citystate,zipcd)) > o.close() > print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) > > > > __________________________________ > Do you Yahoo!? > Yahoo! Small Business - Try our new resources site! > http://smallbusiness.yahoo.com/resources/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From phthenry at iglou.com Tue Mar 15 00:05:00 2005 From: phthenry at iglou.com (Paul Tremblay) Date: Tue Mar 15 00:03:14 2005 Subject: [Tutor] CGI authentication In-Reply-To: <42358BCA.1030700@tds.net> References: <42358BCA.1030700@tds.net> Message-ID: <20050314230500.GA4764@localhost.localdomain> On Mon, Mar 14, 2005 at 08:04:10AM -0500, Kent Johnson wrote: > Date: Mon, 14 Mar 2005 08:04:10 -0500 > From: Kent Johnson <kent37@tds.net> > User-Agent: Mozilla Thunderbird 1.0 (Windows/20041206) > To: Python Tutor <tutor@python.org> > Subject: [Tutor] CGI authentication > > There was a question on this list recently about how to authenticate users > of a web server from a simple CGI script. I just came across a module that > might help: > http://www.voidspace.org.uk/python/logintools.html > > Kent > That would be for me! This looks pretty nice. On problem I have with the python url2lib is the dfficulty of determining the realm. For example, bot lynx and curl (command line url tools) don't need a realm to work. This seems to mean that lynx and curl provide more flexibility. Paul -- ************************ *Paul Tremblay * *phthenry@iglou.com * ************************ From nbbalane at gmail.com Tue Mar 15 00:29:25 2005 From: nbbalane at gmail.com (jrlen balane) Date: Tue Mar 15 00:29:28 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> Message-ID: <2cad20900503141529f3414ab@mail.gmail.com> say i have the code that reads decimal value from a text file: import sys data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') data = data_file.readlines() def process(list_of_lines): data_points = [] for line in list_of_lines: data_points.append(int(line)) return data_points print process(data) ==================== what if, on the text file, a user has encoded values other than decimal, how would i add a code that would act like an Exception, or would tell the user that there is an invalid entry in the text file, like a "letter or other character other than number" ? On Thu, 17 Feb 2005 01:44:19 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > > >> Traceback (most recent call last): > > >> File "C:\Python23\practices\opentxt", line 12, in -toplevel- > > >> process(data) > > >> File "C:\Python23\practices\opentxt", line 6, in process > > >> data_points.append(int(line)) > > >> ValueError: invalid literal for int(): > > Hi Brian, > > Ah, think about empty lines. > > Let's look at the error message again: > > ValueError: invalid literal for int(): > ^^^^^^^ > > There's nothing visible there after the colon, and that's our hint. > Notice what happens when we pass int() some wacky strings: > > ### > >>> int("foobar") > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): foobar > ### > > So whatever is being passed to int() should show up in the error message. > This is exactly why getting literal error messages is so wonderful. > *grin* > > Since we don't see anything here: > > > >> File "C:\Python23\practices\opentxt", line 12, in -toplevel- > > >> process(data) > > >> File "C:\Python23\practices\opentxt", line 6, in process > > >> data_points.append(int(line)) > > >> ValueError: invalid literal for int(): > > my best guess is that there's an empty line in the file, since we get the > same kind of error if we do this: > > ### > >>> int("") > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): > ### > > Best of wishes to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Tue Mar 15 00:52:49 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 15 00:52:55 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad20900503141529f3414ab@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> Message-ID: <f2ff2d0503141552f34c4bc@mail.gmail.com> Well, a string "12345" when called through int() will come back as 12345. But, a string "foo", called through int(), will raise a TypeError. So.... > import sys > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > data = data_file.readlines() > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > data_points.append(int(line)) > return data_points > > print process(data) You could do this def process(list_of_lines): data_points=[] for line in list_of_lines: try: tempLine = int(line) except TypeError: print "Non numeric character in line", line continue #Breaks, and starts with next line data_points.append(tempLine) That's one way, but there's probably a better way. 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. From cyresse at gmail.com Tue Mar 15 00:53:26 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 15 00:53:32 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <f2ff2d0503141552f34c4bc@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> Message-ID: <f2ff2d05031415534e7ba0b0@mail.gmail.com> Oops, and I meant try: tempLine = int(line) Silly indent error. On Tue, 15 Mar 2005 12:52:49 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Well, a string "12345" when called through int() will come back as 12345. > > But, a string "foo", called through int(), will raise a TypeError. > > So.... > > > import sys > > > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > > data = data_file.readlines() > > > > def process(list_of_lines): > > data_points = [] > > for line in list_of_lines: > > data_points.append(int(line)) > > return data_points > > > > print process(data) > > You could do this > > def process(list_of_lines): > data_points=[] > for line in list_of_lines: > try: > tempLine = int(line) > except TypeError: > print "Non numeric character in line", line > continue #Breaks, and starts with next line > data_points.append(tempLine) > > That's one way, but there's probably a better way. > > 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. > -- '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. From Jeff420harris00 at wmconnect.com Tue Mar 15 01:28:06 2005 From: Jeff420harris00 at wmconnect.com (Jeff420harris00@wmconnect.com) Date: Tue Mar 15 01:28:13 2005 Subject: [Tutor] How do you use pydoc? Message-ID: <8b.2336cf31.2f678616@wmconnect.com> I have read but don't under stand how to use pydoc. here what i read can't figer out how to use it..... 5.1 pydoc -- Documentation generator and online help system New in version 2.1. The pydoc module automatically generates documentation from Python modules. The documentation can be presented as pages of text on the console, served to a Web browser, or saved to HTML files. The built-in function help() invokes the online help system in the interactive interpreter, which uses pydoc to generate its documentation as text on the console. The same text documentation can also be viewed from outside the Python interpreter by running pydoc as a script at the operating system's command prompt. For example, running pydoc sys at a shell prompt will display documentation on the <A HREF="mk:@MSITStore:C:%5CPython24%5CDoc%5CPython24.chm::/lib/module-sys.html">sys</A> module, in a style similar to the manual pages shown by the Unix man command. The argument to pydoc can be the name of a function, module, or package, or a dotted reference to a class, method, or function within a module or module in a package. If the argument to pydoc looks like a path (that is, it contains the path separator for your operating system, such as a slash in Unix), and refers to an existing Python source file, then documentation is produced for that file. Specifying a -w flag before the argument will cause HTML documentation to be written out to a file in the current directory, instead of displaying text on the console. Specifying a -k flag before the argument will search the synopsis lines of all available modules for the keyword given as the argument, again in a manner similar to the Unix man command. The synopsis line of a module is the first line of its documentation string. You can also use pydoc to start an HTTP server on the local machine that will serve documentation to visiting Web browsers. pydoc -p 1234 will start a HTTP server on port 1234, allowing you to browse the documentation at http://localhost:1234/ in your preferred Web browser. pydoc -g will start the server and additionally bring up a small <A HREF="mk:@MSITStore:C:%5CPython24%5CDoc%5CPython24.chm::/lib/module-Tkinter.html">Tkinter</A>-based graphical interface to help you search for documentation pages. When pydoc generates documentation, it uses the current environment and path to locate modules. Thus, invoking pydoc spam documents precisely the version of the module you would get if you started the Python interpreter and typed "import spam". Module docs for core modules are assumed to reside in <A HREF="http://www.python.org/doc/current/lib/"> http://www.python.org/doc/current/lib/</A>. This can be overridden by setting the PYTHONDOCS environment variable to a different URL or to a local directory containing the Library Reference Manual pages. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050314/ec35f1cd/attachment.html From nbbalane at gmail.com Tue Mar 15 01:36:10 2005 From: nbbalane at gmail.com (jrlen balane) Date: Tue Mar 15 01:36:14 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <f2ff2d05031415534e7ba0b0@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> Message-ID: <2cad2090050314163613e34ee@mail.gmail.com> this is what i get after running this on IDLE: import sys data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') data = data_file.readlines() def process(list_of_lines): data_points = [] for line in list_of_lines: try: tempLine = int(line) except TypeError: print "Non numeric character in line", line continue #Breaks, and starts with next line data_points.append(tempLine) return data_points print process(data) ================= [1000] ============== but this is what i have written on the text file: 1000 890 900 abc 500 650 850 1200 1100 On Tue, 15 Mar 2005 12:53:26 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Oops, and I meant > > try: > tempLine = int(line) > > Silly indent error. > > > On Tue, 15 Mar 2005 12:52:49 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > Well, a string "12345" when called through int() will come back as 12345. > > > > But, a string "foo", called through int(), will raise a TypeError. > > > > So.... > > > > > import sys > > > > > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > > > data = data_file.readlines() > > > > > > def process(list_of_lines): > > > data_points = [] > > > for line in list_of_lines: > > > data_points.append(int(line)) > > > return data_points > > > > > > print process(data) > > > > You could do this > > > > def process(list_of_lines): > > data_points=[] > > for line in list_of_lines: > > try: > > tempLine = int(line) > > except TypeError: > > print "Non numeric character in line", line > > continue #Breaks, and starts with next line > > data_points.append(tempLine) > > > > That's one way, but there's probably a better way. > > > > 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. > > > > -- > '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. > > From maxnoel_fr at yahoo.fr Tue Mar 15 01:37:37 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 15 01:37:40 2005 Subject: [Tutor] How do you use pydoc? In-Reply-To: <8b.2336cf31.2f678616@wmconnect.com> References: <8b.2336cf31.2f678616@wmconnect.com> Message-ID: <d2cece2a7e9d2a91f7ccc1303d952524@yahoo.fr> On Mar 15, 2005, at 00:28, Jeff420harris00@wmconnect.com wrote: > > ??I have read but don't under stand how to use pydoc. here what i > read can't figer out how to use it..... pydoc is more or less a help browser. Think of it as "man for Python". If you need documentation on a module, just type "pydoc [module name]" at a command prompt. For example, if you want to know how the os module works, just type "pydoc os". Even better: if the modules you're writing use docstrings, then calling pydoc on your module will work automagically. -- 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?" From Jeff420harris00 at wmconnect.com Tue Mar 15 01:55:32 2005 From: Jeff420harris00 at wmconnect.com (Jeff420harris00@wmconnect.com) Date: Tue Mar 15 01:55:41 2005 Subject: [Tutor] what is the "path browser" used for? Message-ID: <25.5b383bb5.2f678c84@wmconnect.com> What is the path browser for and all the sys.path's for? are these for copying and pasteing to help you on your program? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050314/af4fb73f/attachment.htm From kent37 at tds.net Tue Mar 15 01:57:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 01:57:34 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad2090050314163613e34ee@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> Message-ID: <423632F6.8020304@tds.net> jrlen balane wrote: > this is what i get after running this on IDLE: > > import sys > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > data = data_file.readlines() > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > try: > tempLine = int(line) > except TypeError: > print "Non numeric character in line", line > continue #Breaks, and starts with next line > > data_points.append(tempLine) > return data_points This line ^^^ is indented four spaces too much - you are returning after the first time through the loop. Indent it the same as the for statement and it will work correctly. Kent > > print process(data) > > ================= > [1000] > > ============== > but this is what i have written on the text file: > > 1000 > 890 > 900 From nbbalane at gmail.com Tue Mar 15 02:06:05 2005 From: nbbalane at gmail.com (jrlen balane) Date: Tue Mar 15 02:06:09 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <423632F6.8020304@tds.net> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> Message-ID: <2cad209005031417065fe92874@mail.gmail.com> import sys data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') data = data_file.readlines() def process(list_of_lines): data_points = [] for line in list_of_lines: try: tempLine = int(line) except TypeError: print "Non numeric character in line", line continue #Breaks, and starts with next line data_points.append(tempLine) return data_points print process(data) ============== >>> [1000] >>> ============== same result :( any other suggestion??? On Mon, 14 Mar 2005 19:57:26 -0500, Kent Johnson <kent37@tds.net> wrote: > jrlen balane wrote: > > this is what i get after running this on IDLE: > > > > import sys > > > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > > data = data_file.readlines() > > > > def process(list_of_lines): > > data_points = [] > > for line in list_of_lines: > > try: > > tempLine = int(line) > > except TypeError: > > print "Non numeric character in line", line > > continue #Breaks, and starts with next line > > > > data_points.append(tempLine) > > return data_points > This line ^^^ is indented four spaces too much - you are returning after the first time through the > loop. Indent it the same as the for statement and it will work correctly. > > Kent > > > > print process(data) > > > > ================= > > [1000] > > > > ============== > > but this is what i have written on the text file: > > > > 1000 > > 890 > > 900 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Mar 15 02:22:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 02:22:36 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad209005031417065fe92874@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> Message-ID: <423638D5.5050500@tds.net> jrlen balane wrote: > import sys > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > data = data_file.readlines() > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > try: > tempLine = int(line) > except TypeError: > print "Non numeric character in line", line > continue #Breaks, and starts with next line > > data_points.append(tempLine) > return data_points > > print process(data) > > ============== > > [1000] > > ============== > same result :( any other suggestion??? It doesn't look to me like you changed the 'return datapoints' line at all? Indentation is significant in Python; by indenting the 'return' past the 'for', you make the return part of the loop. The effect of this is to break out of the loop after the first line, which is what you are seeing. Try this: import sys data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') data = data_file.readlines() def process(list_of_lines): data_points = [] for line in list_of_lines: try: tempLine = int(line) except TypeError: print "Non numeric character in line", line continue #Breaks, and starts with next line data_points.append(tempLine) return data_points #### This line was moved left four spaces #### now it is not part of the loop print process(data) Kent > > On Mon, 14 Mar 2005 19:57:26 -0500, Kent Johnson <kent37@tds.net> wrote: > >>jrlen balane wrote: >> >>>this is what i get after running this on IDLE: >>> >>>import sys >>> >>>data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') >>>data = data_file.readlines() >>> >>>def process(list_of_lines): >>> data_points = [] >>> for line in list_of_lines: >>> try: >>> tempLine = int(line) >>> except TypeError: >>> print "Non numeric character in line", line >>> continue #Breaks, and starts with next line >>> >>> data_points.append(tempLine) >>> return data_points >> >>This line ^^^ is indented four spaces too much - you are returning after the first time through the >>loop. Indent it the same as the for statement and it will work correctly. >> >>Kent >> >>>print process(data) >>> >>>================= >>>[1000] >>> >>>============== >>>but this is what i have written on the text file: >>> >>>1000 >>>890 >>>900 >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > From maxnoel_fr at yahoo.fr Tue Mar 15 02:28:31 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 15 02:28:35 2005 Subject: [Tutor] what is the "path browser" used for? In-Reply-To: <25.5b383bb5.2f678c84@wmconnect.com> References: <25.5b383bb5.2f678c84@wmconnect.com> Message-ID: <5496c6557e3bcff5f626e6354c194c09@yahoo.fr> On Mar 15, 2005, at 00:55, Jeff420harris00@wmconnect.com wrote: > What is the path browser for and all the sys.path's for? > are these for copying and pasteing to help you on your program? No, sys.path (as explained by pydoc sys ;) ) is the module search path; that is, the list of the folders into which Python looks for a module when you try to import it. Oh, and on an unrelated topic, could you please turn off HTML in your e-mails? Blue text on green background is not very comfortable to read... Thanks! -- 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?" From nbbalane at gmail.com Tue Mar 15 02:38:45 2005 From: nbbalane at gmail.com (jrlen balane) Date: Tue Mar 15 02:38:48 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <423638D5.5050500@tds.net> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> Message-ID: <2cad209005031417381018f2b4@mail.gmail.com> ok, i've done what sir Kent just said, my fault... but an error still occurs: Traceback (most recent call last): File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- print process(data) File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process tempLine = int(line) ValueError: invalid literal for int(): abc isn't this the job of : except TypeError: print "Non numeric character in line", line continue #Breaks, and starts with next line On Mon, 14 Mar 2005 20:22:29 -0500, Kent Johnson <kent37@tds.net> wrote: > jrlen balane wrote: > > import sys > > > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > > data = data_file.readlines() > > > > def process(list_of_lines): > > data_points = [] > > for line in list_of_lines: > > try: > > tempLine = int(line) > > except TypeError: > > print "Non numeric character in line", line > > continue #Breaks, and starts with next line > > > > data_points.append(tempLine) > > return data_points > > > > print process(data) > > > > ============== > > > > [1000] > > > > ============== > > same result :( any other suggestion??? > > It doesn't look to me like you changed the 'return datapoints' line at all? Indentation is > significant in Python; by indenting the 'return' past the 'for', you make the return part of the > loop. The effect of this is to break out of the loop after the first line, which is what you are seeing. > > Try this: > > import sys > > data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > data = data_file.readlines() > > def process(list_of_lines): > data_points = [] > for line in list_of_lines: > try: > tempLine = int(line) > except TypeError: > print "Non numeric character in line", line > continue #Breaks, and starts with next line > > data_points.append(tempLine) > return data_points #### This line was moved left four spaces > #### now it is not part of the loop > > print process(data) > > Kent > > > > On Mon, 14 Mar 2005 19:57:26 -0500, Kent Johnson <kent37@tds.net> wrote: > > > >>jrlen balane wrote: > >> > >>>this is what i get after running this on IDLE: > >>> > >>>import sys > >>> > >>>data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r') > >>>data = data_file.readlines() > >>> > >>>def process(list_of_lines): > >>> data_points = [] > >>> for line in list_of_lines: > >>> try: > >>> tempLine = int(line) > >>> except TypeError: > >>> print "Non numeric character in line", line > >>> continue #Breaks, and starts with next line > >>> > >>> data_points.append(tempLine) > >>> return data_points > >> > >>This line ^^^ is indented four spaces too much - you are returning after the first time through the > >>loop. Indent it the same as the for statement and it will work correctly. > >> > >>Kent > >> > >>>print process(data) > >>> > >>>================= > >>>[1000] > >>> > >>>============== > >>>but this is what i have written on the text file: > >>> > >>>1000 > >>>890 > >>>900 > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Mar 15 03:05:44 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 03:05:51 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad209005031417381018f2b4@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <Pine.LNX.4.44.0502170139230.22520-100000@hkn.eecs.berkeley.edu> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> Message-ID: <423642F8.3090909@tds.net> jrlen balane wrote: > ok, i've done what sir Kent just said, my fault... > > but an error still occurs: > Traceback (most recent call last): > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > print process(data) > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > tempLine = int(line) > ValueError: invalid literal for int(): abc > > isn't this the job of : > > except TypeError: > print "Non numeric character in line", line > continue #Breaks, and starts with next line Yes, only it should be ValueError instead of TypeError. You can check this interactively: >>> int('foo') Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for int(): foo Kent From nbbalane at gmail.com Tue Mar 15 04:35:02 2005 From: nbbalane at gmail.com (jrlen balane) Date: Tue Mar 15 04:35:04 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <Pine.LNX.4.44.0503131742190.24065-100000@hkn.eecs.berkeley.edu> References: <4234E195.5010103@po-box.mcgill.ca> <Pine.LNX.4.44.0503131742190.24065-100000@hkn.eecs.berkeley.edu> Message-ID: <2cad209005031419353fc949ed@mail.gmail.com> so for example, i have 5 arrays, i can do this (is this correct): data1[1,2,3,4,5 (and so on)] data2[1,2,3,4,5 (and so on)] data3[1,2,3,4,5 (and so on)] data4[1,2,3,4,5 (and so on)] data5[1,2,3,4,5 (and so on)] datas = [data1, data2, data3, data4, data5] for data in datas: lines.append('\t'.join(data) + '\n') ================================= (supposed to be output) 1 2 3 4 5 ... 1 2 3 4 5 ... 1 2 3 4 5 ... ... (but i want this output) 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 ... ... ... ... ... ================================= output_file = file('c:/output.txt', 'w') output_file.writelines(lines) output_file.close() ================================= how am i going to change the filename automaticaly? for example: #every 5 minutes, i am going to create a file based on the data above for i in range(100) output_file = file('c:/output' +.join(i) +'.txt', 'w') #guess this won't work output_file.writelines(lines) output_file.close() From cyresse at gmail.com Tue Mar 15 05:05:46 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 15 05:07:22 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <423642F8.3090909@tds.net> References: <4214615F.8020008@po-box.mcgill.ca> <2cad20900503141529f3414ab@mail.gmail.com> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> Message-ID: <f2ff2d050314200533b13392@mail.gmail.com> Whoops, golden rule - "Never post untested code" Sorry. On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > jrlen balane wrote: > > ok, i've done what sir Kent just said, my fault... > > > > but an error still occurs: > > Traceback (most recent call last): > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > print process(data) > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > tempLine = int(line) > > ValueError: invalid literal for int(): abc > > > > isn't this the job of : > > > > except TypeError: > > print "Non numeric character in line", line > > continue #Breaks, and starts with next line > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > >>> int('foo') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ValueError: invalid literal for int(): foo > > Kent > > _______________________________________________ > 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. From bvande at po-box.mcgill.ca Tue Mar 15 05:17:03 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 15 05:20:04 2005 Subject: [Tutor] How do you use pydoc? In-Reply-To: <8b.2336cf31.2f678616@wmconnect.com> References: <8b.2336cf31.2f678616@wmconnect.com> Message-ID: <423661BF.6010302@po-box.mcgill.ca> Jeff420harris00@wmconnect.com said unto the world upon 2005-03-14 19:28: > I have read but don't under stand how to use pydoc. here what i > read can't figer out how to use it..... > Hi, try this: Fire up IDLE and your web browser of choice. In IDLE's shell, type: import HTMLParser There is nothing special about the HTMLParser module other than that it is a pure Python module -- I just wanted to pick a concrete case for the discussion here. Now type: help(HTMLParser) There. You are now using pydoc :-) It is displaying the documentation for the module HTMLParser. Now try typing help(HTMLParser.HTMLParser) That's the documentation for one class in the module. help(HTMLParser.HTMLParser.close) The documentation for one method of that class. Now, in the Start Menu entries for Python, find the icon for Module Docs. Click it, and then click open browser. Scroll down until you see HTMLParser, and click on it. Your web browser should give you the same info as you got from help(HTMLParser), but in a nicer format. That's pydoc at work, too. In IDLE's editor, open HTMLParser.py (mine's at C:\Python24\Lib\HTMLParser.py). Now, look at the file HTMLParser.py and compare that to the outputs that you got above. See if you can see where the help() command got its output from. The parts of the output that come from text in triple quotes are docstrings. Put them in your own modules and functions, and you can use help or Module Docs to remind you of what you own code does. Save a backup copy of HTMLParser.py, and try adding docstrings to methods like HTMLParser.HTMLParser.handle_comment, and see if you can see how and why the '#' lines ended up in the help() and Module Docs output. (Don't forget to save your changes before trying to view them in your web browser with Module Docs -- and don't forget to restore the backup when you are done! This is easier to do with Module Docs than in the IDLE shell as in the shell pydoc won't know about your changes unless you reload the module.) Best, Brian vdB From maxnoel_fr at yahoo.fr Tue Mar 15 05:20:48 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 15 05:20:58 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad209005031419353fc949ed@mail.gmail.com> References: <4234E195.5010103@po-box.mcgill.ca> <Pine.LNX.4.44.0503131742190.24065-100000@hkn.eecs.berkeley.edu> <2cad209005031419353fc949ed@mail.gmail.com> Message-ID: <8a1be4151a5e9c48e2b585b254fcf9e3@yahoo.fr> On Mar 15, 2005, at 03:35, jrlen balane wrote: > how am i going to change the filename automaticaly? > for example: > #every 5 minutes, i am going to create a file based on the > data above > for i in range(100) > output_file = file('c:/output' +.join(i) +'.txt', 'w') > #guess this won't work > output_file.writelines(lines) > output_file.close() I'm not going to give you a complete solution because that'd spoil the fun, but you need to use the os.path.exists function (in the os module), which tells you if a file exists or not (no need to open it -- actually, your loop is dangerous: opening a file with "w" as the mode erases it). As for generating the file name, you've almost got it. Just remove that bizarre call to "join", cause that won't work, and replace your for loop with a while loop, so that you can break out of it when you've found the correct file name, not before or after. -- 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?" From y2kbug at ms25.hinet.net Tue Mar 15 08:06:06 2005 From: y2kbug at ms25.hinet.net (Robert Storey) Date: Tue Mar 15 08:03:59 2005 Subject: [Tutor] big numbers Message-ID: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> Dear all, I'm new to Python, and using Sam's Teach Yourself Python in 24 Hours. The book introduces big numbers, saying that I should expect the following problem: >>> 1 + 999999999999999999 OverflowError: integer literal too large The "problem" is that this doesn't happen. When I execute this command, Python seems to automatically convert the result into a big number: >>> 1 + 999999999999999999 1000000000000000000L This book is a few years old and was written for Python version 1.5, and of course I'm using version 2.3, so I'm just wondering if this whole issue of big numbers is now being handled automatically? This is my first post - sorry to be asking such a basic question. TIA, Robert From ewald.ertl at hartter.com Tue Mar 15 09:53:46 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 15 09:53:51 2005 Subject: [Tutor] big numbers In-Reply-To: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> References: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> Message-ID: <20050315095346.000064ef@sunray1> Hi! As far as I can remember, there was a change between some version's of python of 2.x. Now there is an automatic conversion from int to long, when it is necessary. Regards, Ewald on Tue, 15 Mar 2005 15:06:06 +0800 Robert Storey <y2kbug@ms25.hinet.net> wrote : --------------------------------------------------------------------------------------------- Robert Storey > Dear all, Robert Storey > Robert Storey > I'm new to Python, and using Sam's Teach Yourself Python in 24 Hours. Robert Storey > The book introduces big numbers, saying that I should expect the Robert Storey > following problem: Robert Storey > Robert Storey > >>> 1 + 999999999999999999 Robert Storey > OverflowError: integer literal too large Robert Storey > Robert Storey > The "problem" is that this doesn't happen. When I execute this command, Robert Storey > Python seems to automatically convert the result into a big number: Robert Storey > Robert Storey > >>> 1 + 999999999999999999 Robert Storey > 1000000000000000000L Robert Storey > Robert Storey > This book is a few years old and was written for Python version 1.5, and Robert Storey > of course I'm using version 2.3, so I'm just wondering if this whole Robert Storey > issue of big numbers is now being handled automatically? Robert Storey > Robert Storey > This is my first post - sorry to be asking such a basic question. Robert Storey > Robert Storey > TIA, Robert Storey > Robert Robert Storey > _______________________________________________ Robert Storey > Tutor maillist - Tutor@python.org Robert Storey > http://mail.python.org/mailman/listinfo/tutor Robert Storey > ------------------- end ---------------------- -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl@trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl@hartter.com From work at infomaniak.ch Tue Mar 15 10:53:20 2005 From: work at infomaniak.ch (BRINER Cedric) Date: Tue Mar 15 10:53:30 2005 Subject: [Tutor] unicode type on cgi script Message-ID: <1110880400.20487.49.camel@obslin15.unige.ch> python-2.3 apache2 hi, I'm trying to use unicode function into a cgi script with no success. #-------- cedric.py--- #!/usr/bin/python import os,sys import cgi import cgitb; cgitb.enable() print "Content-Type: text/html\ "+os.linesep+"\ "+os.linesep+"<TITLE>hipo'potame</TITLE>" sys.stdout.flush() content = u'c\xe9dric' print content #--------------------- when I invoke it from my xterm, I get: > python cedric.py Content-Type: text/html <TITLE>hipo'potame</TITLE> c?dric but the same does not work on apache: /home/system/briner/obsadminwww/cedric.py 6 "+os.linesep+"\ 7 "+os.linesep+"<TITLE>hipo'potame</TITLE>" 8 sys.stdout.flush() 9 content = u'c\xe9dric' 10 print content content = u'c\xe9dric' UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128) args = ('ascii', u'c\xe9dric', 1, 2, 'ordinal not in range(128)') encoding = 'ascii' end = 2 object = u'c\xe9dric' reason = 'ordinal not in range(128)' start = 1 As if the stdout as to pbe in ascii?? any idea on how to do this Cedric BRINER From python at kapitalisten.no Tue Mar 15 10:56:36 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue Mar 15 10:56:42 2005 Subject: [Tutor] Port 43 whois.ripe.net Message-ID: <8137.193.71.38.142.1110880596.squirrel@mail.sporck.net> Hello. I need to query the whois at Ripe.net. It tells me to connect to port 43. I have found a description how to connect with .Net. http://www.aspheute.com/english/20000825.asp I am not very familiar with network protocols, but assume this will be no big problem with Python. Can someone point me in the right direction to what modules I would use in Python to connect to the whois-server. I would also appriciate if someone had a link to a 'dummies' tutorial/manual/faq for the networking theory I need, or any hints about the direction I should look... Thanks in advance.... -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Tue Mar 15 12:02:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 12:02:17 2005 Subject: [Tutor] big numbers In-Reply-To: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> References: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> Message-ID: <4236C0B3.1040708@tds.net> Robert Storey wrote: > This book is a few years old and was written for Python version 1.5, and > of course I'm using version 2.3, so I'm just wondering if this whole > issue of big numbers is now being handled automatically? Yes, it is. There have been many changes to Python since 1.5; when you are comfortable with the basic language you might want to look at amk's "What's New" documents available here: http://www.amk.ca/python/ Kent From kent37 at tds.net Tue Mar 15 12:21:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 12:21:09 2005 Subject: [Tutor] How do you use pydoc? In-Reply-To: <8b.2336cf31.2f678616@wmconnect.com> References: <8b.2336cf31.2f678616@wmconnect.com> Message-ID: <4236C520.40106@tds.net> Jeff420harris00@wmconnect.com wrote: > * > I have read but don't under stand how to use pydoc. here what i read > can't figer out how to use it..... One way to use pydoc is to start up a mini web server that delivers module documentation. On Windows, start the server with Start / Programs / Python / Module Docs. Click the Open browser button and you can browse the docstrings for all installed modules. Kent From kent37 at tds.net Tue Mar 15 12:29:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 12:29:43 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad209005031419353fc949ed@mail.gmail.com> References: <4234E195.5010103@po-box.mcgill.ca> <Pine.LNX.4.44.0503131742190.24065-100000@hkn.eecs.berkeley.edu> <2cad209005031419353fc949ed@mail.gmail.com> Message-ID: <4236C720.8050308@tds.net> jrlen balane wrote: > so for example, i have 5 arrays, i can do this (is this correct): > > data1[1,2,3,4,5 (and so on)] > data2[1,2,3,4,5 (and so on)] > data3[1,2,3,4,5 (and so on)] > data4[1,2,3,4,5 (and so on)] > data5[1,2,3,4,5 (and so on)] > datas = [data1, data2, data3, data4, data5] > > for data in datas: > lines.append('\t'.join(data) + '\n') > > ================================= > (supposed to be output) > 1 2 3 4 5 ... > 1 2 3 4 5 ... > 1 2 3 4 5 ... > ... > > (but i want this output) > 1 1 1 1 1 > 2 2 2 2 2 > 3 3 3 3 3 > ... ... ... ... ... > ================================= You need to reformat your data. zip() is handy for this. Given multiple lists as arguments, zip() creates tuples from the first element of each list, the second element of each list, etc: >>> a=[1,2,3] >>> b=[11,22,33] >>> zip(a, b) [(1, 11), (2, 22), (3, 33)] When all the source lists are themselves in a list, you can use the *args form of argument passing: >>> c=[a, b] >>> c [[1, 2, 3], [11, 22, 33]] >>> zip(*c) [(1, 11), (2, 22), (3, 33)] So in your case this will do what you want: for data in zip(*datas): lines.append('\t'.join(data) + '\n') If datas is large you might want to use itertools.izip() instead. zip() creates an intermediate list while izip() creates an iterator over the new tuples, so it is more memory-efficient. > > output_file = file('c:/output.txt', 'w') > output_file.writelines(lines) > output_file.close() > ================================= > > how am i going to change the filename automaticaly? > for example: > #every 5 minutes, i am going to create a file based on the data above > for i in range(100) > output_file = file('c:/output' +.join(i) +'.txt', 'w') > #guess this won't work > output_file.writelines(lines) > output_file.close() Two ways to do this: >>> for i in range(5): ... print 'c:/output' + str(i) + '.txt' ... print 'c:/output%d.txt' % i ... c:/output0.txt c:/output0.txt c:/output1.txt c:/output1.txt ... Kent From kent37 at tds.net Tue Mar 15 14:01:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 14:01:58 2005 Subject: [Tutor] unicode type on cgi script In-Reply-To: <1110880400.20487.49.camel@obslin15.unige.ch> References: <1110880400.20487.49.camel@obslin15.unige.ch> Message-ID: <4236DCC3.6020301@tds.net> BRINER Cedric wrote: > python-2.3 apache2 > hi, > > I'm trying to use unicode function into a cgi script with no success. > #-------- cedric.py--- > #!/usr/bin/python > import os,sys > import cgi > import cgitb; cgitb.enable() > print "Content-Type: text/html\ > "+os.linesep+"\ > "+os.linesep+"<TITLE>hipo'potame</TITLE>" > sys.stdout.flush() > content = u'c\xe9dric' > print content print uses sys.stdout.encoding to encode unicode strings. You can check what this is in your cgi with import sys print sys.stdout.encoding I think it will work to explicitly encode the unicode string in the encoding you want for the web page. Try print content.encode(xxx) where xxx is the encoding you want, for example 'utf-8' or 'latin-1'. Also I think you should use an explicit '\r\n' instead of os.linesep, HTTP specifies an explicit CRLF. Finally, you might want to put a charset tag in your Content-Type header, e.g. print "Content-Type: text/html;charset=utf-8\ or whatever. Obviously the charset you specify here should match what you use in the encode(). Kent > #--------------------- > > when I invoke it from my xterm, I get: > >>python cedric.py > > Content-Type: text/html > > <TITLE>hipo'potame</TITLE> > c?dric > > but the same does not work on apache: > > > /home/system/briner/obsadminwww/cedric.py > 6 "+os.linesep+"\ > > 7 "+os.linesep+"<TITLE>hipo'potame</TITLE>" > > 8 sys.stdout.flush() > > 9 content = u'c\xe9dric' > > 10 print content > > content = u'c\xe9dric' > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 1: ordinal not in range(128) > args = ('ascii', u'c\xe9dric', 1, 2, 'ordinal not in range(128)') > encoding = 'ascii' > end = 2 > object = u'c\xe9dric' > reason = 'ordinal not in range(128)' > start = 1 > > As if the stdout as to pbe in ascii?? > > any idea on how to do this > > Cedric BRINER > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Mar 15 14:11:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 14:11:05 2005 Subject: [Tutor] Port 43 whois.ripe.net In-Reply-To: <8137.193.71.38.142.1110880596.squirrel@mail.sporck.net> References: <8137.193.71.38.142.1110880596.squirrel@mail.sporck.net> Message-ID: <4236DEE7.6040708@tds.net> ?yvind wrote: > Hello. > > I need to query the whois at Ripe.net. It tells me to connect to port 43. > I have found a description how to connect with .Net. > http://www.aspheute.com/english/20000825.asp I am not very familiar with > network protocols, but assume this will be no big problem with Python. Can > someone point me in the right direction to what modules I would use in > Python to connect to the whois-server. The socket module is for low-level TCP connections. I would also appriciate if someone > had a link to a 'dummies' tutorial/manual/faq for the networking theory I > need, or any hints about the direction I should look... There is a socket programming HOW-TO here: http://www.amk.ca/python/howto/sockets/ Google finds a couple of existing implementations of whois in Python: http://www.dotfunk.com/projects/whois/ http://midori.callisia.com/~jonan/software/rwhois/ Kent From python at kapitalisten.no Tue Mar 15 15:30:39 2005 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Tue Mar 15 15:30:40 2005 Subject: [Tutor] FTP retrieve Message-ID: <58645.193.71.38.142.1110897039.squirrel@mail.sporck.net> I have opened an FTP connection, and use the following to download a logfile: f = open('c:///web.log','w') ftp.retrlines('RETR ex050202.log', f.write) I have also tried with f.writelines. It works, but not as well as I would like. All the \n's are removed. How can I download an exact copy, so that each line actually ends up being on a separate line? Thanks in advance... -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From kent37 at tds.net Tue Mar 15 15:45:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 15:45:12 2005 Subject: [Tutor] FTP retrieve In-Reply-To: <58645.193.71.38.142.1110897039.squirrel@mail.sporck.net> References: <58645.193.71.38.142.1110897039.squirrel@mail.sporck.net> Message-ID: <4236F4F3.4050006@tds.net> ?yvind wrote: > I have opened an FTP connection, and use the following to download a logfile: > > f = open('c:///web.log','w') > ftp.retrlines('RETR ex050202.log', f.write) > > I have also tried with f.writelines. > > It works, but not as well as I would like. All the \n's are removed. How > can I download an exact copy, so that each line actually ends up being on > a separate line? Define your own callback that inserts the missing \n: f = open('c:///web.log','w') def cb(line): f.write(line) f.write('\n') ftp.retrlines('RETR ex050202.log', cb) Note that this callback relies on f being accessible as a global. Kent From ewald.ertl at hartter.com Tue Mar 15 15:48:43 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Tue Mar 15 15:48:47 2005 Subject: [Tutor] FTP retrieve In-Reply-To: <58645.193.71.38.142.1110897039.squirrel@mail.sporck.net> References: <58645.193.71.38.142.1110897039.squirrel@mail.sporck.net> Message-ID: <20050315154843.00002cbd@sunray1> Hi! Looking up the ftplib-Module on my Solaris-Box >>> print sys.version 2.3.3 (#1, Mar 10 2004, 06:25:19) [GCC 3.3.2] I get the following doc for retrlines of the FTP-class: >>> print myFTP.retrlines.__doc__ Retrieve data in line mode. The argument is a RETR or LIST command. The callback function (2nd argument) is called for each line, with trailing CRLF stripped. This creates a new port for you. print_line() is the default callback. Here is stated, that CRLF is stripped for each line. I've done something similar and opended the targetfile in "binary"-mode. 'wb' instead of 'w', so that there will be no conversion of data during the write. The data is retrieved with the following command: myFTP.retrbinary( "RETR " + dat, open( dat, "wb" ).write ) Ewald on Tue, 15 Mar 2005 15:30:39 +0100 (CET) ?yvind <python@kapitalisten.no> wrote : --------------------------------------------------------------------------------------------- ?yvind > I have opened an FTP connection, and use the following to download a logfile: ?yvind > ?yvind > f = open('c:///web.log','w') ?yvind > ftp.retrlines('RETR ex050202.log', f.write) ?yvind > ?yvind > I have also tried with f.writelines. ?yvind > ?yvind > It works, but not as well as I would like. All the \n's are removed. How ?yvind > can I download an exact copy, so that each line actually ends up being on ?yvind > a separate line? ?yvind > ?yvind > Thanks in advance... ?yvind > ?yvind > ?yvind > ------------------- end ---------------------- -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement & Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Stra?e 41 mailto:ewald.ertl@trinomic.com A-7400 Oberwart http://www.trinomic.com mailto:ewald.ertl@hartter.com From kent37 at tds.net Tue Mar 15 15:49:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 15:49:47 2005 Subject: [Tutor] unicode type on cgi script In-Reply-To: <1110896910.20487.55.camel@obslin15.unige.ch> References: <1110880400.20487.49.camel@obslin15.unige.ch> <4236DCC3.6020301@tds.net> <1110896910.20487.55.camel@obslin15.unige.ch> Message-ID: <4236F607.6020407@tds.net> BRINER Cedric wrote: >>print uses sys.stdout.encoding to encode unicode strings. You can check what this is in your cgi with >>import sys >>print sys.stdout.encoding > > didn't know > >>I think it will work to explicitly encode the unicode string in the encoding you want for the web >>page. Try >>print content.encode(xxx) > > did and worked ! > >>where xxx is the encoding you want, for example 'utf-8' or 'latin-1'. > > perfect. > the funny thing is that now , it perfeclty works on the cgi side but not > anymore on my uxterm. What encoding did you use in the cgi? Is it the same as sys.stdout.encoding in uxterm? Kent From smichr at hotmail.com Tue Mar 15 16:41:35 2005 From: smichr at hotmail.com (C Smith) Date: Tue Mar 15 16:42:44 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <20050315110147.85C581E4006@bag.python.org> Message-ID: <BAY101-DAV182899FEA0776801A9491AC1570@phx.gbl> On Tuesday, Mar 15, 2005, at 05:01 America/Chicago, tutor-request@python.org wrote: > how am i going to change the filename automaticaly? > for example: > #every 5 minutes, i am going to create a file based on the > data above > for i in range(100) > output_file = file('c:/output' +.join(i) +'.txt', 'w') > #guess this won't work > output_file.writelines(lines) > output_file.close() > When faced with this problem, one of the tings that I liked to do was use a date stamp for the files. The time module has a function called strftime which allows you to use a template to create a string from the current time. (See the documentation of python module 'time' for more details.) e.g. ### >>> import time >>> time.strftime('%Y%m%d%H%M') '200503150934' ### This string can be added to your 'c:/output' rather than a generic number like i. Just to be safe you might want to check that the file doesn't already exist. The nice thing is that there should be few files that have this number added to them so the loop to get a valid name is going to succeed quickly. /c From nbbalane at gmail.com Tue Mar 15 16:52:22 2005 From: nbbalane at gmail.com (jrlen balane) Date: Tue Mar 15 16:52:45 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <BAY101-DAV182899FEA0776801A9491AC1570@phx.gbl> References: <20050315110147.85C581E4006@bag.python.org> <BAY101-DAV182899FEA0776801A9491AC1570@phx.gbl> Message-ID: <2cad20900503150752610dab05@mail.gmail.com> that is exactly what i am looking for, but how would i add this to my filename??? should i use this: output_file = open(os.path.join(self.Save_Session.GetValue(), time.strftime('%Y%m%d%H%M')), 'w') the self.Save_Session.GetValue() is generated by a dirdialog On Tue, 15 Mar 2005 09:41:35 -0600, C Smith <smichr@hotmail.com> wrote: > > On Tuesday, Mar 15, 2005, at 05:01 America/Chicago, > tutor-request@python.org wrote: > > > how am i going to change the filename automaticaly? > > for example: > > #every 5 minutes, i am going to create a file based on the > > data above > > for i in range(100) > > output_file = file('c:/output' +.join(i) +'.txt', 'w') > > #guess this won't work > > output_file.writelines(lines) > > output_file.close() > > > > When faced with this problem, one of the tings that I liked to do was > use a date stamp for the files. The time module has a function called > strftime which allows you to use a template to create a string from the > current time. (See the documentation of python module 'time' for more > details.) e.g. > > ### > >>> import time > >>> time.strftime('%Y%m%d%H%M') > '200503150934' > ### > > This string can be added to your 'c:/output' rather than a generic > number like i. Just to be safe you might want to check that the file > doesn't already exist. The nice thing is that there should be few files > that have this number added to them so the loop to get a valid name is > going to succeed quickly. > > /c > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nixonron at yahoo.com Tue Mar 15 17:11:32 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Tue Mar 15 17:11:35 2005 Subject: [Tutor] re.findall vs. re.search and re.match Message-ID: <20050315161132.15530.qmail@web20326.mail.yahoo.com> Thanks to all who replied to my post earlier on re's. I'm still preplexed by why re.search and re.match works in the code below, but not re.findall. re.findall is suppose to return all non-voerlapping occurances of the pattern that matches in this example, but it returns errors. Looking through the docs and from what I can see it should work. Can anyone provide advice. import re f = open('reformat.txt').read() pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*) ([^\r\n]*) ([^\r\n]*)") x=re.search(pat,f) name = x.group(1) address = x.group(2) citystate = x.group(3)+x.group(4) zipcd = x.group(5) o= open('reformat1.txt','w') o.write("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) o.close() print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From kent37 at tds.net Tue Mar 15 17:31:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 17:31:25 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <20050315161132.15530.qmail@web20326.mail.yahoo.com> References: <20050315161132.15530.qmail@web20326.mail.yahoo.com> Message-ID: <42370DD9.8060907@tds.net> Ron Nixon wrote: > Thanks to all who replied to my post earlier on re's. > I'm still preplexed by why re.search and re.match > works in the code below, but not re.findall. > re.findall is suppose to return all non-voerlapping > occurances of the pattern that matches in this > example, but it returns errors. Looking through the > docs and from what I can see it should work. Can > anyone provide advice. Please show the code that uses re.findall() and the error you receive when you run it. Kent From nixonron at yahoo.com Tue Mar 15 17:44:45 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Tue Mar 15 17:44:48 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: 6667 Message-ID: <20050315164445.58459.qmail@web20325.mail.yahoo.com> Kent: The code is below. Here's the error message. Traceback (most recent call last): File "C:/Python24/reformat.py", line 5, in -toplevel- name = x.group(1) AttributeError: 'list' object has no attribute 'group' import re f = open('reformat.txt').read() pat = re.compile(r"([^\r\n]+)\n([^\r\n]*)\n([^\r\n]*) ([^\r\n]*) ([^\r\n]*)") x=re.findall(pat,f) name = x.group(1) address = x.group(2) citystate = x.group(3)+x.group(4) zipcd = x.group(5) o= open('reformat1.txt','w') o.write("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) o.close() print("%s,%s,%s,%s\n" % (name, address, citystate,zipcd)) --- Kent Johnson <kent37@tds.net> wrote: > Ron Nixon wrote: > > Thanks to all who replied to my post earlier on > re's. > > I'm still preplexed by why re.search and re.match > > works in the code below, but not re.findall. > > re.findall is suppose to return all > non-voerlapping > > occurances of the pattern that matches in this > > example, but it returns errors. Looking through > the > > docs and from what I can see it should work. Can > > anyone provide advice. > > Please show the code that uses re.findall() and the > error you receive when you run it. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From maxnoel_fr at yahoo.fr Tue Mar 15 18:09:50 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 15 18:09:55 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <20050315164445.58459.qmail@web20325.mail.yahoo.com> References: <20050315164445.58459.qmail@web20325.mail.yahoo.com> Message-ID: <fc3f49a693b7a1d86231cff61a1dbf46@yahoo.fr> On Mar 15, 2005, at 16:44, Ron Nixon wrote: > Kent: > > The code is below. Here's the error message. > > Traceback (most recent call last): > File "C:/Python24/reformat.py", line 5, in > -toplevel- > name = x.group(1) > AttributeError: 'list' object has no attribute 'group' re.findall returns a list object (as the error message says). Use name = x[1] instead. (and be careful, numbering starts from 0, so this code may contain a Kenobi error). -- 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?" From ernieball_slinky at yahoo.fr Tue Mar 15 18:24:55 2005 From: ernieball_slinky at yahoo.fr (Lolo) Date: Tue Mar 15 18:24:59 2005 Subject: [Tutor] unicode type on cgi script In-Reply-To: 6667 Message-ID: <20050315172455.75344.qmail@web51701.mail.yahoo.com> Hi, Try this solution. Create a script named sitecustomize.py into your python lib directory (i.e /usr/lib/python2.3) and add the following code : #-----------sitecustomize.py--- import sys sys.setdefaultencoding('latin-1') See u, Lja --- BRINER Cedric <work@infomaniak.ch> wrote: > python-2.3 apache2 > hi, > > I'm trying to use unicode function into a cgi script > with no success. > #-------- cedric.py--- > #!/usr/bin/python > import os,sys > import cgi > import cgitb; cgitb.enable() > print "Content-Type: text/html\ > "+os.linesep+"\ > "+os.linesep+"<TITLE>hipo'potame</TITLE>" > sys.stdout.flush() > content = u'c\xe9dric' > print content > #--------------------- > > when I invoke it from my xterm, I get: > > python cedric.py > Content-Type: text/html > > <TITLE>hipo'potame</TITLE> > c?dric > > but the same does not work on apache: > > > /home/system/briner/obsadminwww/cedric.py > 6 "+os.linesep+"\ > > 7 "+os.linesep+"<TITLE>hipo'potame</TITLE>" > > 8 sys.stdout.flush() > > 9 content = u'c\xe9dric' > > 10 print content > > content = u'c\xe9dric' > > UnicodeEncodeError: 'ascii' codec can't encode > character u'\xe9' in > position 1: ordinal not in range(128) > args = ('ascii', u'c\xe9dric', 1, 2, 'ordinal > not in range(128)') > encoding = 'ascii' > end = 2 > object = u'c\xe9dric' > reason = 'ordinal not in range(128)' > start = 1 > > As if the stdout as to pbe in ascii?? > > any idea on how to do this > > Cedric BRINER > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > D?couvrez nos promotions exclusives "destination de la Tunisie, du Maroc, des Bal?ares et la R?p. Dominicaine sur Yahoo! Voyages : http://fr.travel.yahoo.com/promotions/mar14.html From bvande at po-box.mcgill.ca Tue Mar 15 18:18:39 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 15 18:30:14 2005 Subject: [Tutor] How do you use pydoc? In-Reply-To: <19c.2f283967.2f6801dd@wmconnect.com> References: <19c.2f283967.2f6801dd@wmconnect.com> Message-ID: <423718EF.9070300@po-box.mcgill.ca> Jeff420harris00@wmconnect.com said unto the world upon 2005-03-15 04:16: > ok thanks for the help but i did what you said and heres what i got don't > know exactly what i got but here lol <SNIP pages worth of help() output> > will you help me figer what i got out and the module docs dose not work whem > i go to the browser in opens a window saying > > > > 580 Server Error > > > > This Web page could not be opened. A connection to the page could not be > made. Please click the Reload or Refresh button to try again. > > thanks agin Hi, 1) *PLEASE* reply to all. This is particularly important in cases like the present one, where I personally have no idea what the trouble is, and thus don't have the ability to help. 2) Sending the results of help(HTMLParser), etc. isn't useful -- it makes for a giant email the contents of which we all can get by typing help(HTMLParser) in our own python shells :-) It is better to send just the unexpected things. As for the problem: For me, the 580 Server Error is unexpected, indeed. And, I'm afraid it takes us past my competency and knowledge level. Though I do wonder if you are running a firewall such as ZoneAlaram -- that could interfere with Module Docs attempts to serve up documentation. But that's just a guess: *I* can't help further. Best, Brian vdB From maxnoel_fr at yahoo.fr Tue Mar 15 19:13:09 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 15 19:13:11 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <20050315174154.68219.qmail@web20325.mail.yahoo.com> References: <20050315174154.68219.qmail@web20325.mail.yahoo.com> Message-ID: <d5fea0934b15145ba6a6e7f956dab016@yahoo.fr> On Mar 15, 2005, at 17:41, Ron Nixon wrote: > Max: > > Thanks that seem to do the trick. One question though, > how do you write a tuple out as a list to a new file > like the example I have in my code > > Ron You mean, all the members of the list, separated by commas, with a new line at the end? Well, this may help you: >>> foo = map(str, range(10)) >>> foo ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> print ",".join(foo) + "\n" 0,1,2,3,4,5,6,7,8,9 >>> -- 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?" From tpc at csua.berkeley.edu Tue Mar 15 20:57:55 2005 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Mar 15 20:54:46 2005 Subject: [Tutor] strange hotshot error Message-ID: <20050315115352.V58835-100000@localhost.name> hi everyone, to anyone who has profiled their Python code using hotshot; I designed a test case using hotshot that is basically a stripped down version of the example code found here: http://www.python.org/doc/current/lib/hotshot-example.html So I tried using the example code verbatim to see if I get the same error messages, and I do! When I try "import hotshot.stats" I get: >>> import hotshot.stats Traceback (most recent call last): File "<pyshell#1>", line 1, in -toplevel- import hotshot.stats File "/usr/lib/python2.3/hotshot/stats.py", line 3, in -toplevel- import profile ImportError: No module named profile When I try "import hotshot.stats" again I get no error message, so I assume the import on the second try has found the module. Everything seems honky dory until I try "stats = hotshot.stats.load("stones.prof")": >>> stats = hotshot.stats.load("stones.prof") Traceback (most recent call last): File "<pyshell#13>", line 1, in -toplevel- stats = hotshot.stats.load("stones.prof") AttributeError: 'module' object has no attribute 'load' I've confirmed the stones.prof file exists and that I am in the same directory where the file is, so I am in a situation where IDLE is telling me hotshot.stats has no attribute 'load'. I've confirmed hotshot.stats does indeed have attribute 'load' from: http://www.python.org/doc/current/lib/module-hotshot.stats.html so now I am at my wit's end as to what the problem is. I can't use hotshot since I can't load the profile data. Am I doing something wrong ? From dyoo at hkn.eecs.berkeley.edu Tue Mar 15 22:21:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 15 22:21:06 2005 Subject: [Tutor] strange hotshot error In-Reply-To: <20050315115352.V58835-100000@localhost.name> Message-ID: <Pine.LNX.4.44.0503151307110.10920-100000@hkn.eecs.berkeley.edu> On Tue, 15 Mar 2005 tpc@csua.berkeley.edu wrote: > So I tried using the example code verbatim to see if I get the same > error messages, and I do! When I try "import hotshot.stats" I get: > > >>> import hotshot.stats > > Traceback (most recent call last): > File "<pyshell#1>", line 1, in -toplevel- > import hotshot.stats > File "/usr/lib/python2.3/hotshot/stats.py", line 3, in -toplevel- > import profile > ImportError: No module named profile Hi Tpc, This is highly unusual! This should have worked without any error messages, as both the 'profile' and 'hotshot' modules are part of the Standard Library, and should work out of the box. > When I try "import hotshot.stats" again I get no error message, so I > assume the import on the second try has found the module. No, at this point, I get the impression that the Python module system is confused. Something funky is going on with module lookup. Let's double check a few things. Can you run the following, and show us your output? ###### import sys import distutils.sysconfig print "version is", sys.version print "python lib is", print distutils.sysconfig.get_python_lib(standard_lib=True) print "System path is:", sys.path ###### I want to see where Python thinks the Standard Library lives. I also want to watch what order it starts looking for modules. The code snippet above will give us the diagnostic information we need to trace down the weirdness you're seeing. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Tue Mar 15 22:34:12 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 15 22:34:17 2005 Subject: [Tutor] strange hotshot error In-Reply-To: <Pine.LNX.4.44.0503151307110.10920-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503151326240.10920-100000@hkn.eecs.berkeley.edu> > This is highly unusual! This should have worked without any error > messages, as both the 'profile' and 'hotshot' modules are part of the > Standard Library, and should work out of the box. Hi Tpc, Oh, wait. The above statement is usually true, unless we're running something from a Linux distribution like Debian testing. Let me make that assumption for the moment, until I see your 'sys.version' string. Debian, which does its own packaging of Python, often tears apart the Standard Library into individual packages due to licensing issues. In particular, Debian separates the profiling stuff into a separate Debian package called 'python-profiler': http://packages.debian.org/testing/python/python-profiler If you are running Debian's testing distribution, you will need to do an 'apt-get python-profiler' first. Of course, this is only a wild guess that depends on the core assumption that you are running Debian Testing. So, if you aren't, ignore everything I said. *grin* Hope this helps! From tpc at csua.berkeley.edu Tue Mar 15 22:53:32 2005 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Mar 15 22:50:24 2005 Subject: [Tutor] strange hotshot error In-Reply-To: <Pine.LNX.4.44.0503151326240.10920-100000@hkn.eecs.berkeley.edu> Message-ID: <20050315134930.T58835-100000@localhost.name> hi Danny, I had no idea Debian split its profiler into a separate package in the testing distro. That would explain it, except I am using Debian unstable with Debian stable for security packages, as my "more /etc/apt/sources.list" output is: nike:# more /etc/apt/sources.list #deb file:///cdrom/ sarge main deb http://ftp.us.debian.org/debian/ unstable main deb-src http://ftp.us.debian.org/debian/ unstable main deb http://security.debian.org/ stable/updates main The following is the output from the steps you suggested: >>> print "version is", sys.version version is 2.3.5 (#2, Feb 9 2005, 00:38:15) [GCC 3.3.5 (Debian 1:3.3.5-8)] >>> print "python lib is", python lib is >>> print distutils.sysconfig.get_python_lib(standard_lib=True) /usr/lib/python2.3 >>> print "System path is:", sys.path System path is: ['/home/tpc', '/usr/bin', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/Numeric', '/usr/lib/python2.3/site-packages/gtk-2.0'] On Tue, 15 Mar 2005, Danny Yoo wrote: > > This is highly unusual! This should have worked without any error > > messages, as both the 'profile' and 'hotshot' modules are part of the > > Standard Library, and should work out of the box. > > Hi Tpc, > > > Oh, wait. The above statement is usually true, unless we're running > something from a Linux distribution like Debian testing. Let me make that > assumption for the moment, until I see your 'sys.version' string. > > Debian, which does its own packaging of Python, often tears apart the > Standard Library into individual packages due to licensing issues. In > particular, Debian separates the profiling stuff into a separate Debian > package called 'python-profiler': > > http://packages.debian.org/testing/python/python-profiler > > If you are running Debian's testing distribution, you will need to do an > 'apt-get python-profiler' first. > > > Of course, this is only a wild guess that depends on the core assumption > that you are running Debian Testing. So, if you aren't, ignore everything > I said. *grin* > > > Hope this helps! > > From cyresse at gmail.com Tue Mar 15 22:59:54 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 15 23:00:01 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <fc3f49a693b7a1d86231cff61a1dbf46@yahoo.fr> References: <20050315164445.58459.qmail@web20325.mail.yahoo.com> <fc3f49a693b7a1d86231cff61a1dbf46@yahoo.fr> Message-ID: <f2ff2d050315135914ea3b25@mail.gmail.com> On Tue, 15 Mar 2005 17:09:50 +0000, Max Noel <maxnoel_fr@yahoo.fr> wrote: > > re.findall returns a list object (as the error message says). Use name > = x[1] instead. (and be careful, numbering starts from 0, so this code > may contain a Kenobi error). > Kenobi as in Obi Wan? -- '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. From kent37 at tds.net Tue Mar 15 23:22:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 15 23:22:07 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <f2ff2d050315135914ea3b25@mail.gmail.com> References: <20050315164445.58459.qmail@web20325.mail.yahoo.com> <fc3f49a693b7a1d86231cff61a1dbf46@yahoo.fr> <f2ff2d050315135914ea3b25@mail.gmail.com> Message-ID: <4237600A.7020505@tds.net> Liam Clarke wrote: > On Tue, 15 Mar 2005 17:09:50 +0000, Max Noel <maxnoel_fr@yahoo.fr> wrote: > > >> re.findall returns a list object (as the error message says). Use name >>= x[1] instead. (and be careful, numbering starts from 0, so this code >>may contain a Kenobi error). >> > > > Kenobi as in Obi Wan? or maybe his brother Offby One Kenobi? Kent From maxnoel_fr at yahoo.fr Tue Mar 15 23:24:53 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Mar 15 23:25:12 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <f2ff2d050315135914ea3b25@mail.gmail.com> References: <20050315164445.58459.qmail@web20325.mail.yahoo.com> <fc3f49a693b7a1d86231cff61a1dbf46@yahoo.fr> <f2ff2d050315135914ea3b25@mail.gmail.com> Message-ID: <ef0d65a3809648390ba523177f4a4ccb@yahoo.fr> On Mar 15, 2005, at 21:59, Liam Clarke wrote: > On Tue, 15 Mar 2005 17:09:50 +0000, Max Noel <maxnoel_fr@yahoo.fr> > wrote: >> > >> re.findall returns a list object (as the error message says). >> Use name >> = x[1] instead. (and be careful, numbering starts from 0, so this code >> may contain a Kenobi error). >> > > Kenobi as in Obi Wan? As in Off By One (O.B.1), to be more precise. :D -- 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?" From cyresse at gmail.com Tue Mar 15 23:34:46 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 15 23:34:49 2005 Subject: [Tutor] re.findall vs. re.search and re.match In-Reply-To: <ef0d65a3809648390ba523177f4a4ccb@yahoo.fr> References: <20050315164445.58459.qmail@web20325.mail.yahoo.com> <fc3f49a693b7a1d86231cff61a1dbf46@yahoo.fr> <f2ff2d050315135914ea3b25@mail.gmail.com> <ef0d65a3809648390ba523177f4a4ccb@yahoo.fr> Message-ID: <f2ff2d0503151434e0d3eba@mail.gmail.com> Sheesh. Star wars/programming humour. Better not be any Star Trek humour, that'll go over my head even further. On Tue, 15 Mar 2005 22:24:53 +0000, Max Noel <maxnoel_fr@yahoo.fr> wrote: > > On Mar 15, 2005, at 21:59, Liam Clarke wrote: > > > On Tue, 15 Mar 2005 17:09:50 +0000, Max Noel <maxnoel_fr@yahoo.fr> > > wrote: > >> > > > >> re.findall returns a list object (as the error message says). > >> Use name > >> = x[1] instead. (and be careful, numbering starts from 0, so this code > >> may contain a Kenobi error). > >> > > > > Kenobi as in Obi Wan? > > As in Off By One (O.B.1), to be more precise. :D > > -- 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?" > > -- '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. From dyoo at hkn.eecs.berkeley.edu Tue Mar 15 23:58:11 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 15 23:58:15 2005 Subject: [Tutor] strange hotshot error In-Reply-To: <20050315134930.T58835-100000@localhost.name> Message-ID: <Pine.LNX.4.44.0503151450490.3468-100000@hkn.eecs.berkeley.edu> On Tue, 15 Mar 2005 tpc@csua.berkeley.edu wrote: > hi Danny, I had no idea Debian split its profiler into a separate > package in the testing distro. That would explain it, except I am using > Debian unstable with Debian stable for security packages, as my "more > /etc/apt/sources.list" output is: Hi Tpc, This is starting to turn more into a Debian question than a Python one. *grin* I would talk with other debian folks about your sources.list: I don't think that the security package set is very effective when you're running unstable... Because Debian "unstable" is even more unstable than Debian "testing", I wouldn't be surprised that it, too, has the profiler separate from the main Python package: http://packages.debian.org/unstable/python/python2.3-profiler Hotshot requires that the profiler be installed, so apt-get it, and see if things start to work again. > The following is the output from the steps you suggested: > > >>> print "version is", sys.version > version is 2.3.5 (#2, Feb 9 2005, 00:38:15) > [GCC 3.3.5 (Debian 1:3.3.5-8)] > >>> print "python lib is", > python lib is > >>> print distutils.sysconfig.get_python_lib(standard_lib=True) > /usr/lib/python2.3 > >>> print "System path is:", sys.path > System path is: ['/home/tpc', '/usr/bin', '/usr/lib/python23.zip', > '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', > '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', > '/usr/local/lib/python2.3/site-packages', > '/usr/lib/python2.3/site-packages', > '/usr/lib/python2.3/site-packages/Numeric', > '/usr/lib/python2.3/site-packages/gtk-2.0'] Yes, all of that looks normal. I'm pretty sure that the error message that you're getting is ultimately due to Debian's package policy. Best of wishes to you! From keridee at jayco.net Wed Mar 16 01:45:31 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Mar 16 01:45:08 2005 Subject: [Tutor] creating a tab delimited filename References: <20050315110147.85C581E4006@bag.python.org><BAY101-DAV182899FEA0776801A9491AC1570@phx.gbl> <2cad20900503150752610dab05@mail.gmail.com> Message-ID: <000e01c529c1$7e99e910$995328cf@JSLAPTOP> > that is exactly what i am looking for, but how would i add this to my > filename??? > should i use this: > > output_file = open(os.path.join(self.Save_Session.GetValue(), > time.strftime('%Y%m%d%H%M')), 'w') > > the self.Save_Session.GetValue() is generated by a dirdialog > Uck,uck, uck, no... That's what Kent's post was for... This will do the trick. filename = "%s%s.txt" % (self.Save_Session.GetValue(),time.strftime("%Y%m%d%H%M")) output_file = open(filename,"a") This uses string formatting, are you familiar with that? If not -- see here http://docs.python.org/lib/typesseq-strings.html#l2h-211 remember, if you don't understand--not that you wouldn't--you can always ask here. HTH, Jacob From ianamartin at snet.net Wed Mar 16 03:02:19 2005 From: ianamartin at snet.net (Ian Martin) Date: Wed Mar 16 03:02:23 2005 Subject: [Tutor] new Message-ID: <20050316020219.43160.qmail@web80010.mail.yahoo.com> Hey I am new at python and i am trying to learn about it. I was wondering if you could tell me how to write a range to 100. such as 1+2+3+4+5 ect. without writing it out. From maxnoel_fr at yahoo.fr Wed Mar 16 03:07:25 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Mar 16 03:07:29 2005 Subject: [Tutor] new In-Reply-To: <20050316020219.43160.qmail@web80010.mail.yahoo.com> References: <20050316020219.43160.qmail@web80010.mail.yahoo.com> Message-ID: <f90e489f2f898c08a94eed4e9be5bcfe@yahoo.fr> On Mar 16, 2005, at 02:02, Ian Martin wrote: > Hey I am new at python and i am trying to learn about > it. I was wondering if you could tell me how to write > a range to 100. such as 1+2+3+4+5 ect. without > writing it out. Well, I'm not going to give you the full solution (that'd spoil the fun), but the range() function will generate a sequence of integers depending on the parameters you pass to it (for example, range(start=20, stop=100, step=10) will return [20, 30, 40, 50, 60, 70, 80, 90]). Then, you could use the sum() function. -- 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?" From tameyer at ihug.co.nz Wed Mar 16 03:12:30 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Wed Mar 16 03:12:39 2005 Subject: [Tutor] new In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8025E0ECC@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFF9B@its-xchg4.massey.ac.nz> > Hey I am new at python and i am trying to learn about > it. I was wondering if you could tell me how to write > a range to 100. such as 1+2+3+4+5 ect. without > writing it out. Do you want a container with a range in it, like the list [1,2,3,4,5,...,100]: >>> range(100) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] Or do you want the sum of a range 1+2+3+4+...+100?: >>> sum(range(100)) 4950 I highly recommend working through the Python tutorial that's included in the documentation. It is a great help in figuring out the way things work. (You can still ask questions here, of course!). =Tony.Meyer From tameyer at ihug.co.nz Wed Mar 16 03:15:23 2005 From: tameyer at ihug.co.nz (Tony Meyer) Date: Wed Mar 16 03:15:31 2005 Subject: [Tutor] new In-Reply-To: <ECBA357DDED63B4995F5C1F5CBE5B1E8025E0ED7@its-xchg4.massey.ac.nz> Message-ID: <ECBA357DDED63B4995F5C1F5CBE5B1E801DAFF9C@its-xchg4.massey.ac.nz> > Do you want a container with a range in it, like the list > [1,2,3,4,5,...,100]: > > >>> range(100) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, [...] > 92, 93, 94, 95, 96, 97, 98, 99] Opps. Notice that I did the range 0-99, of course. But it's still the function that you want. [...] > >>> sum(range(100)) > 4950 And again... =Tony.Meyer From keridee at jayco.net Wed Mar 16 04:49:41 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Mar 16 04:48:58 2005 Subject: [Tutor] Convert doesn't work... I'm stumped Message-ID: <000b01c529db$36979e90$c65428cf@JSLAPTOP> Okay, not a very descriptive subject, but here goes... This is the code ########################################### from decimal import Decimal as D """Everything is first converted to meters, and then converted to the unit you want to extend usage. dic[unit] = (unittometers,meterstounit) """ dic = {## Metric ## 'm':(lambda x:x,lambda x:x), 'km':(lambda x:1000*x,lambda x:x/1000), 'cm':(lambda x:x/100,lambda x:100*x), 'mm':(lambda x:x/1000,lambda x:1000*x), ## English ## 'in':(lambda x:127*x/5000,lambda x:5000/(127*x)), 'ft':(lambda x:381*x/1250,lambda x:1250/(381*x)), 'mi':(lambda x:201168*x/125,lambda x:125/(201168*x)), 'yd':(lambda x:1143*x/1250,lambda x:1250/(1143*x)) } def convert(num,unit1,unit2): num = D(str(num)) tometer = dic[unit1][0](num) frommeter = dic[unit2][1](tometer) return frommeter #################################################### Fortunately my docstrings are getting slightly better, and you can at least tell that the function "convert" first changes the value to meters then to the second unit. This increases the number of conversions I can do to N! where N is the number of known units, I'm guessing... But, I digress--to the problem... If I call convert(3,'ft','yd'), I should get Decimal("1") instead, I get Decimal("1.195990046301080256481500617") The first lambda function returns the number converted to meters, the second lambda function converts the number to the unit you want. So, expanded -- convert is def convert(num, unit1, unit2): num = D(str(num)) tometer = dic[unit1][0] # a function that converts its argument to meters frommeter = dic[unit2][1] # a function that converts its argument from meters to the unit you want inmeters = tometer(num) in_the_units = frommeter(inmeters) return in_the_units I have checked all of the lambdas I have defined... x -ft- 12 -in- 2.54 -cm- m def dic['ft'][0](x) = ---- X -------- X ----------- X ------- = 12*2.54*x/100 = 12*254*x/10000 = 381*x/1250 -ft- -in- 100 -cm- Like that of above... I just don't get where it goes from *okay* to 0.195990046301... margin error. Can anyone help? Jacob From nbbalane at gmail.com Wed Mar 16 04:54:34 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed Mar 16 04:54:37 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <000e01c529c1$7e99e910$995328cf@JSLAPTOP> References: <20050315110147.85C581E4006@bag.python.org> <BAY101-DAV182899FEA0776801A9491AC1570@phx.gbl> <2cad20900503150752610dab05@mail.gmail.com> <000e01c529c1$7e99e910$995328cf@JSLAPTOP> Message-ID: <2cad2090050315195466c369e6@mail.gmail.com> how would i make this the correct path: filename = "%s%s.txt" %('C:\Documents and Settings\nyer\My Documents\Info',time.strftime("%Y%m%d%H%M")) table_file = open(os.path.normpath(filename),"a") running on IDLE, i get the following error: Traceback (most recent call last): File "C:/Python23/practices/serialnewesttes3.py", line 65, in -toplevel- table_file = open(os.path.normpath(filename),"a") IOError: [Errno 2] No such file or directory: 'C:\\Documents and Settings\nyer\\My Documents\\Info200503161153.txt' it seems that it adds "\". On Tue, 15 Mar 2005 19:45:31 -0500, Jacob S. <keridee@jayco.net> wrote: > > > > that is exactly what i am looking for, but how would i add this to my > > filename??? > > should i use this: > > > > output_file = open(os.path.join(self.Save_Session.GetValue(), > > time.strftime('%Y%m%d%H%M')), 'w') > > > > the self.Save_Session.GetValue() is generated by a dirdialog > > > > Uck,uck, uck, no... > > That's what Kent's post was for... > This will do the trick. > > filename = "%s%s.txt" % > (self.Save_Session.GetValue(),time.strftime("%Y%m%d%H%M")) > output_file = open(filename,"a") > > This uses string formatting, are you familiar with that? > > If not -- see here http://docs.python.org/lib/typesseq-strings.html#l2h-211 > remember, if you don't understand--not that you wouldn't--you can always ask > here. > > HTH, > Jacob > > From maxnoel_fr at yahoo.fr Wed Mar 16 05:01:59 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Mar 16 05:05:52 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <2cad2090050315195466c369e6@mail.gmail.com> References: <20050315110147.85C581E4006@bag.python.org> <BAY101-DAV182899FEA0776801A9491AC1570@phx.gbl> <2cad20900503150752610dab05@mail.gmail.com> <000e01c529c1$7e99e910$995328cf@JSLAPTOP> <2cad2090050315195466c369e6@mail.gmail.com> Message-ID: <7bf26b58fc1bbaf8f2ae30966b1c2667@yahoo.fr> On Mar 16, 2005, at 03:54, jrlen balane wrote: > how would i make this the correct path: > filename = "%s%s.txt" %('C:\Documents and Settings\nyer\My > Documents\Info',time.strftime("%Y%m%d%H%M")) > table_file = open(os.path.normpath(filename),"a") > > running on IDLE, i get the following error: > > Traceback (most recent call last): > File "C:/Python23/practices/serialnewesttes3.py", line 65, in > -toplevel- > table_file = open(os.path.normpath(filename),"a") > IOError: [Errno 2] No such file or directory: 'C:\\Documents and > Settings\nyer\\My Documents\\Info200503161153.txt' > > it seems that it adds "\". The "\n" of "\nyer" is escaped as a new line. That's a Bad Thing. In fact, relying on backslashes being automatically escaped thanks to the following character not having a special meaning in escape context is a Bad Thing. Either way, it's better to use forward slashes (or os.sep if you're going for overkill and/or obscure, non-POSIX platforms), with which such problems just don't happen. -- 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?" From jfouhy at paradise.net.nz Wed Mar 16 05:12:33 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Wed Mar 16 05:12:37 2005 Subject: [Tutor] Convert doesn't work... I'm stumped In-Reply-To: <000b01c529db$36979e90$c65428cf@JSLAPTOP> References: <000b01c529db$36979e90$c65428cf@JSLAPTOP> Message-ID: <1110946353.4237b231c80ab@www.paradise.net.nz> Quoting "Jacob S." <keridee@jayco.net>: > But, I digress--to the problem... > If I call convert(3,'ft','yd'), I should get Decimal("1") > instead, I get Decimal("1.195990046301080256481500617") At the risk of being blindingly obvious --- ft[0] is lambda x:381*x/1250 yd[1] is lambda x:1250/(1143*x) ft[0](3) is 3*381/1250 which is .9144 (according to bc) yd[1](.9144) is 1240/(1143*.9144) which is 1.19599... I think you need to check your conversion equations, rather than your code... > x -ft- 12 -in- 2.54 -cm- m > def dic['ft'][0](x) = ---- X -------- X ----------- X ------- = > 12*2.54*x/100 = 12*254*x/10000 = 381*x/1250 > -ft- -in- > 100 -cm- I guess this is meant to be some algebra. Unfortunately, I can't make sense of it --- do you use a proportional font? Anyway: yd(x) := 1250/(1143*x) ft(x) := 381*x/1250 You are computing yd(ft(x)), which is: 1250/(1143*(381*x/1250)) which works out as: yd(ft(x)) := 1250**2/(1143*381*x) HTH. -- John. From javier at ruere.com.ar Wed Mar 16 05:27:01 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Wed Mar 16 05:22:46 2005 Subject: [Tutor] Re: Convert doesn't work... I'm stumped In-Reply-To: <000b01c529db$36979e90$c65428cf@JSLAPTOP> References: <000b01c529db$36979e90$c65428cf@JSLAPTOP> Message-ID: <d18c7j$4i4$1@sea.gmane.org> Jacob S. wrote: > Okay, not a very descriptive subject, but here goes... > > This is the code > > ########################################### > from decimal import Decimal as D Oh come on! > """Everything is first converted to meters, and then converted to the unit > you want to extend usage. > > dic[unit] = (unittometers,meterstounit) > """ > > dic = {## Metric ## > 'm':(lambda x:x,lambda x:x), > 'km':(lambda x:1000*x,lambda x:x/1000), > 'cm':(lambda x:x/100,lambda x:100*x), > 'mm':(lambda x:x/1000,lambda x:1000*x), > > ## English ## > 'in':(lambda x:127*x/5000,lambda x:5000/(127*x)), > 'ft':(lambda x:381*x/1250,lambda x:1250/(381*x)), > 'mi':(lambda x:201168*x/125,lambda x:125/(201168*x)), > 'yd':(lambda x:1143*x/1250,lambda x:1250/(1143*x)) > } > > def convert(num,unit1,unit2): > num = D(str(num)) > tometer = dic[unit1][0](num) > frommeter = dic[unit2][1](tometer) > return frommeter > #################################################### > > Fortunately my docstrings are getting slightly better, and you can at > least tell that > the function "convert" first changes the value to meters then to the > second unit. The function has no docstring. You could place this description in the docstring with a description of the parameters and their spected type. > But, I digress--to the problem... > If I call convert(3,'ft','yd'), I should get Decimal("1") > instead, I get Decimal("1.195990046301080256481500617") Let's see. First you convert to meters with 381*x/1250 so we get... Decimal("0.9144")! OK, then you convert to "yd" using 1250/(1143*x) so we get... Decimal("1.195990046301080256481500617"). Mmmmm... OK let's Google: 3 feet = 0.9144 meters. All right! 1 yard = 0.9144 meters. Aha! It should be x/0.9144 or 1250*x/1143 instead! Javier PS: Sorry if this was shown further ahead but I'm too lazy to read any more. PPS: This may be a good oportunity to start using some sort of unit test. From pythonlists at hardcorr.net Wed Mar 16 07:38:15 2005 From: pythonlists at hardcorr.net (Colin Corr) Date: Wed Mar 16 07:38:13 2005 Subject: [Tutor] Help with unnamed arguments in a merge function Message-ID: <1110955096.5190.47.camel@pythondev.hardcorr.net> Greetings Tutors, I am having some difficulties with the concept of functions which can accept an unnamed number of arguments. Specifically, when trying to write a function that deals with an unnamed number of dictionaries. I want to be able to merge any number of dictionaries, while preserving the values (ie. cannot use update()). ~I would appreciate any help that can point in me in the right direction, without directly providing me the answer.~ I understand how to accomplish this task with named arguments: def mergedicts(firstdict, seconddict): '''merges two dictionaries into a single dictionary, and converts duplicate key values to a list''' newdict = firstdict.copy() for key in seconddict.keys(): if key in firstdict.keys(): newdict[key] = firstdict[key], seconddict[key] newdict[key] = list(newdict[key]) else: newdict[key] = seconddict[key] return newdict dict1 = {'1':'a','2':'b','3':'c'} dict2 = {'4':'d','5':'e','6':'f','1':'g'} somedicts1 = mergedicts(dict1,dict2) print somedicts1 #returns: {'1': ['a', 'g'], '3': 'c', '2': 'b', '5': 'e', '4': 'd', '6': 'f'} I also think I understand how to use unnamed arguments to merge lists: def mergelists(*somelists): '''merges multiple lists into a single list and consolidates lists elements''' mergedict = {} for element in somelists: for unique in element: mergedict[unique] = 1 combolist = mergedict.keys() return combolist Where I am getting hung up is that, if I do this with unnamed arguments for dictionaries: def mergedicts(*somedicts): I get an: AttributeError: 'tuple' object has no attribute 'keys' However, I run into the same problem when trying with one named, and unnamed. def mergedicts2(firstdict,*somedicts): '''merges any number of dictionaries into a single dictionary, and converts duplicate key values to a list''' merged = firstdict.copy() for key in somedicts.keys(): if key in merged.keys(): merged[key] = merged[key], somedicts[key] merged[key] = list(merged[key]) else: merged[key] = somedicts[key] return merged Based on my understanding of how unnamed arguments work in functions: I think the dictionaries are being converted into a tuple of all of the dictionary values, and I cannot make a working copy of the first dictionary passed to the function, with the named example. Should I then unpack the resulting tuple into corresponding first,second,third... dictionaries for further processing? I am also wondering if this is even the right approach? Can this be done with only unnamed arguments, or do I at least need to name the first argument for the first reference dictionary, and then use an *unnamed for each additional dictionary? Thanks for any pointers, Colin -- "f u cn rd ths, u cn gt a gd jb n cmptr prgrmmng." - Anonymous From bvande at po-box.mcgill.ca Wed Mar 16 08:45:56 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Mar 16 08:46:16 2005 Subject: [Tutor] Help with unnamed arguments in a merge function In-Reply-To: <1110955096.5190.47.camel@pythondev.hardcorr.net> References: <1110955096.5190.47.camel@pythondev.hardcorr.net> Message-ID: <4237E434.9030304@po-box.mcgill.ca> Colin Corr said unto the world upon 2005-03-16 01:38: > Greetings Tutors, > > I am having some difficulties with the concept of functions which can > accept an unnamed number of arguments. Specifically, when trying to > write a function that deals with an unnamed number of dictionaries. I > want to be able to merge any number of dictionaries, while preserving > the values (ie. cannot use update()). > > ~I would appreciate any help that can point in me in the right > direction, without directly providing me the answer.~ > > I understand how to accomplish this task with named arguments: > > def mergedicts(firstdict, seconddict): > '''merges two dictionaries into a single dictionary, and converts > duplicate key values to a list''' > newdict = firstdict.copy() > for key in seconddict.keys(): > if key in firstdict.keys(): > newdict[key] = firstdict[key], seconddict[key] > newdict[key] = list(newdict[key]) > else: > newdict[key] = seconddict[key] > > return newdict > > > dict1 = {'1':'a','2':'b','3':'c'} > dict2 = {'4':'d','5':'e','6':'f','1':'g'} > somedicts1 = mergedicts(dict1,dict2) > print somedicts1 > > #returns: {'1': ['a', 'g'], '3': 'c', '2': 'b', '5': 'e', '4': 'd', '6': > 'f'} > > I also think I understand how to use unnamed arguments to merge lists: > > def mergelists(*somelists): > '''merges multiple lists into a single list and consolidates lists > elements''' > mergedict = {} > for element in somelists: > for unique in element: > mergedict[unique] = 1 > combolist = mergedict.keys() > > return combolist > > Where I am getting hung up is that, if I do this with unnamed arguments > for dictionaries: > > def mergedicts(*somedicts): > > I get an: AttributeError: 'tuple' object has no attribute 'keys' > > > However, I run into the same problem when trying with one named, and > unnamed. > > def mergedicts2(firstdict,*somedicts): > '''merges any number of dictionaries into a single dictionary, and > converts duplicate key values to a list''' > merged = firstdict.copy() > for key in somedicts.keys(): > if key in merged.keys(): > merged[key] = merged[key], somedicts[key] > merged[key] = list(merged[key]) > else: > merged[key] = somedicts[key] > > return merged > > Based on my understanding of how unnamed arguments work in functions: I > think the dictionaries are being converted into a tuple of all of the > dictionary values, and I cannot make a working copy of the first > dictionary passed to the function, with the named example. Should I then > unpack the resulting tuple into corresponding first,second,third... > dictionaries for further processing? > > I am also wondering if this is even the right approach? Can this be done > with only unnamed arguments, or do I at least need to name the first > argument for the first reference dictionary, and then use an *unnamed > for each additional dictionary? > > > Thanks for any pointers, > > Colin Hi Colin, The problem is that somedicts is indeed a tuple -- having *args in a function def collects non-positional, non-keyword arguments into a tuple. So, in your function body, somedicts is a tuple of dicts. (It's not that each dict is somehow tuplized.) See if this helps: >>> def print_values(*some_dicts): ... for a_dict in some_dicts: ... for key in a_dict: ... print a_dict[key] ... >>> d1 = {1:2, 3:4} >>> d2 = {1:42, 2:84} >>> print_values(d1, d2) 2 4 42 84 Best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Wed Mar 16 09:32:50 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 16 09:32:55 2005 Subject: [Tutor] Convert doesn't work... I'm stumped In-Reply-To: <000b01c529db$36979e90$c65428cf@JSLAPTOP> Message-ID: <Pine.LNX.4.44.0503152340480.7883-100000@hkn.eecs.berkeley.edu> On Tue, 15 Mar 2005, Jacob S. wrote: > Okay, not a very descriptive subject, but here goes... > > This is the code Hi Jacob, > from decimal import Decimal as D Ok, I think I see why you're using this, but you have to be aware that the decimal module itself is susceptible to imprecision: http://www.python.org/doc/lib/decimal-notes.html so, even with the decimal module, we still run the potential for roundoff errors. I think you may be looking for something like a "rational" module. There's an unofficial one that comes with the Python source code, in the Demo/classes directory as 'rat.py'. Let me see if I can get a link to it... ok, here it is: http://cvs.sourceforge.net/viewcvs.py/*checkout*/python/python/dist/src/Demo/classes/Rat.py You may find this module more useful. I really hope something like this migrates into the Standard Library some day... *grin* Let's take a look at some other parts of the code. > dic = {## Metric ## > 'm':(lambda x:x,lambda x:x), > 'km':(lambda x:1000*x,lambda x:x/1000), > 'cm':(lambda x:x/100,lambda x:100*x), > 'mm':(lambda x:x/1000,lambda x:1000*x), The lambdas might be slightly scary to some folks. I'm usually for lambdas, but this seems a bit too much. *grin* Another way you can write this is just to store the constants. And, although the 'dic' above stores pairs of ratios, you might be able to live with just one of them. A table that stores a similar amount of information might be something like this: ### meterRatios = { 'm' : D(1), ## 1 meter == 1 meter 'km' : D(1000), ## 1000 meters == 1 kilometer 'cm' : D(1)/D(100), ## .001 meters == 1 centimeter 'mm' : D(1)/D(1000), ## .0001 meters == 1 millimeter } ### The reason this stores equivalent data is because it stores the ratio of one meter to the unit in question. I'm being perhaps a little too paranoid in building decimals by calling D() n both the numerator and denominator, but oh well. *grin* We can also do it without explicitely defining 'from meter' stuff, because the ratios that define going "to meters" and going "from meters" are inverses of each other. That is, from the table above, we can see that since there's one meter to a thousanth of a millimeter, we can go the other way and say that one thousand millimeters is one meter. (1/x) Here's one way to write a fromMeterToUnit function: ### def inverse(number): """Returns 1 / number.""" return D(1) / number def fromMeterToUnit(meters, unit): """Converts meters to a specific unit.""" return meters * inverse(meterRatios[unit]) ### Let's just double check to see that this works: ### >>> fromMeterToUnit(10, 'm') Decimal("10") >>> fromMeterToUnit(10, 'km') Decimal("0.010") >>> fromMeterToUnit(10, 'cm') Decimal("1.0E+3") >>> fromMeterToUnit(10, 'mm') Decimal("1.0E+4") ### Ok, looks good so far. And a similar definition for a 'fromUnitToMeter' isn't too much more work, and can reuse the same numbers in the table. (By the way, several other posters have mentioned that "unit tests" would be a really good idea to have. Do you know about them already? I'm sure many of us on the list can show examples and help you learn them if you'd like.) The big win here is that we don't have to repeat the same numbers: we want to avoid the chance of accidently mistyping a ratio --- we want to reduce redundancy in data if we can. And if we have to correct some numbers later on, it's nice if we can correct it just once, and not in several places. I think that Javier Ruere found the bug in one of the ratios, but I wanted to comment on the code's style, so that the main ideas of the converter stand out clearly. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Wed Mar 16 09:40:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 16 09:40:56 2005 Subject: [Tutor] Convert doesn't work... I'm stumped In-Reply-To: <Pine.LNX.4.44.0503152340480.7883-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503160036530.7883-100000@hkn.eecs.berkeley.edu> > > A table that stores a similar amount of information might be something > like this: > > ### > meterRatios = { 'm' : D(1), ## 1 meter == 1 meter > 'km' : D(1000), ## 1000 meters == 1 kilometer > 'cm' : D(1)/D(100), ## .001 meters == 1 centimeter > 'mm' : D(1)/D(1000), ## .0001 meters == 1 millimeter > } > ### > [some text cut] > > That is, from the table above, we can see that since there's one meter > to a thousanth of a millimeter, we can go the other way and say that one > thousand millimeters is one meter. (1/x) Oh good grief, did I really write that? I'm sorry, I meant to say: """[...] since there's one-thousandth of a meter in a millimeter, we can go the other way and say that there are one thousand millimeters in one meter. """ I can debug code with some fluency, but I have to do better to debug my English. *grin* From shitizb at yahoo.com Wed Mar 16 11:08:52 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 16 11:08:55 2005 Subject: [Tutor] How to delete a class instance Message-ID: <20050316100852.25893.qmail@web53808.mail.yahoo.com> Hi, How do i delete a class instance in a function running within itself? All the instances of the class are stored in a list, and they need to be deleted after executing their function. However since the list is dynamic, there is no way to know the exact position of the instance within the list. I tried del self to no avail. Shitiz __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From kent37 at tds.net Wed Mar 16 12:06:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 16 12:06:19 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: <20050316100852.25893.qmail@web53808.mail.yahoo.com> References: <20050316100852.25893.qmail@web53808.mail.yahoo.com> Message-ID: <42381326.9000808@tds.net> Shitiz Bansal wrote: > Hi, > How do i delete a class instance in a function running > within itself? > All the instances of the class are stored in a list, > and they need to be deleted after executing their > function. > However since the list is dynamic, there is no way to > know the exact position of the instance within the > list. You have to do this from the caller, in code that has access to the list. There is no general way for an object to find out how it is being referenced in external code. Can you show some of the code that creates and uses the list? Does the code that calls the class know where the class is in the list? Is this the linked list you asked about before that is modified from two threads? > > I tried del self to no avail. del self just removes the link between the name 'self' and the object it references. Kent From maxnoel_fr at yahoo.fr Wed Mar 16 12:09:55 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Mar 16 12:10:00 2005 Subject: Fwd: [Tutor] creating a tab delimited filename Message-ID: <cbc154dd77c2a6be6afdb9a3d04d2a14@yahoo.fr> Forwarding to the list -- please use Reply to All. Begin forwarded message: > From: jrlen balane <nbbalane@gmail.com> > Date: March 16, 2005 04:13:40 GMT > To: Max Noel <maxnoel_fr@yahoo.fr> > Subject: Re: [Tutor] creating a tab delimited filename > Reply-To: jrlen balane <nbbalane@gmail.com> > > why is this not working, what i am trying to do is create a table like > file based on 6 arrays. i 've used the forward slashes so i assume > that the text file was created, but to no avail, there were no text > file.: > > > for k in range (rx_len-9): > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & > 0xff == 0: > temp1.append(byte[k+3]) > temp2.append(byte[k+4]) > pyra1.append(byte[k+5]) > pyra2.append(byte[k+6]) > voltage.append(byte[k+7]) > current.append(byte[k+8]) > print temp1[i], temp2[i], pyra1[i], pyra2[i], voltage[i], > current[i] > > if i==1000: > i = 0 > else: > i = i+1 > ser.flushInput() > filename = "%s%s.txt" %('C:/Documents and Settings/nyer/My > Documents/Info',time.strftime("%Y%m%d%H%M")) > table_file = open(filename,"a") > lendata = len(temp1) > > for ii in xrange(lendata): > table_file.write('%i\t'%temp1[ii]) > table_file.write('%i\t'%temp2[ii]) > table_file.write('%i\t'%pyra1[ii]) > table_file.write('%i\t'%pyra2[ii]) > table_file.write('%i\t'%voltage[ii]) > table_file.write('%i\t'%current[ii]) > table_file.write('\n') > > > =========================== > it is printing the array so i assume that that the problem is in this > table_file... > > please, i need help > > -- 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?" From kent37 at tds.net Wed Mar 16 13:37:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 16 13:37:47 2005 Subject: Fwd: [Tutor] creating a tab delimited filename In-Reply-To: <cbc154dd77c2a6be6afdb9a3d04d2a14@yahoo.fr> References: <cbc154dd77c2a6be6afdb9a3d04d2a14@yahoo.fr> Message-ID: <42382899.4020501@tds.net> Max Noel wrote: > Forwarding to the list -- please use Reply to All. > > Begin forwarded message: > >> From: jrlen balane <nbbalane@gmail.com> >> Date: March 16, 2005 04:13:40 GMT >> To: Max Noel <maxnoel_fr@yahoo.fr> >> Subject: Re: [Tutor] creating a tab delimited filename >> Reply-To: jrlen balane <nbbalane@gmail.com> >> >> why is this not working, what i am trying to do is create a table like >> file based on 6 arrays. i 've used the forward slashes so i assume >> that the text file was created, but to no avail, there were no text >> file.: >> >> >> for k in range (rx_len-9): >> if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & >> 0xff == 0: >> temp1.append(byte[k+3]) >> temp2.append(byte[k+4]) >> pyra1.append(byte[k+5]) >> pyra2.append(byte[k+6]) >> voltage.append(byte[k+7]) >> current.append(byte[k+8]) >> print temp1[i], temp2[i], pyra1[i], pyra2[i], voltage[i], >> current[i] >> >> if i==1000: >> i = 0 >> else: >> i = i+1 >> ser.flushInput() >> filename = "%s%s.txt" %('C:/Documents and Settings/nyer/My >> Documents/Info',time.strftime("%Y%m%d%H%M")) print filename might be helpful here >> table_file = open(filename,"a") >> lendata = len(temp1) >> >> for ii in xrange(lendata): >> table_file.write('%i\t'%temp1[ii]) >> table_file.write('%i\t'%temp2[ii]) >> table_file.write('%i\t'%pyra1[ii]) >> table_file.write('%i\t'%pyra2[ii]) >> table_file.write('%i\t'%voltage[ii]) >> table_file.write('%i\t'%current[ii]) >> table_file.write('\n') table_file.close() might help...do you get any error messages or just no file written? Kent >> >> >> =========================== >> it is printing the array so i assume that that the problem is in this >> table_file... >> >> please, i need help >> >> From shitizb at yahoo.com Wed Mar 16 17:00:30 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 16 17:00:34 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: 6667 Message-ID: <20050316160030.65175.qmail@web53810.mail.yahoo.com> No, this list is not a linked list. Since mu original code is rather huge, I am presenting the relevant snippet. queue=[] def genpassenger(num,destination,queue=queue): for i in range(num): newpass=passenger(destination) queue.append(newpass) newpass.start() class passenger(threading.Thread): def __init__ <snip> def run: #do something delete itself genpassengers is called interactively by the user .Also there can be multiple instances of genpassengers running at the same time. Now my questions are: 1) Generically , how do i accomplish the delete itself part 2) If i used a linked list, does automatic memory handling by python entail that delete itself is automatically accomplished once i have readjusted the pointers, since no further reference to the instance remains.(Of course, if it doesnt i can get a reference in the external code(in case of a doubly linked list)). 3) How about making a destructor function (on lines of c++) and deleting all the variables of the class.Does it free all my memory or is there still some memory being used, though the instance has no variables stored. Shitiz --- Kent Johnson <kent37@tds.net> wrote: > Shitiz Bansal wrote: > > Hi, > > How do i delete a class instance in a function > running > > within itself? > > All the instances of the class are stored in a > list, > > and they need to be deleted after executing their > > function. > > However since the list is dynamic, there is no way > to > > know the exact position of the instance within the > > list. > > You have to do this from the caller, in code that > has access to the list. There is no general way > for an object to find out how it is being referenced > in external code. Can you show some of the code > that creates and uses the list? Does the code that > calls the class know where the class is in the list? > > Is this the linked list you asked about before that > is modified from two threads? > > > > > I tried del self to no avail. > > del self just removes the link between the name > 'self' and the object it references. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From dyoo at hkn.eecs.berkeley.edu Wed Mar 16 18:01:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 16 18:01:09 2005 Subject: [Tutor] Newbie in Python (fwd) Message-ID: <Pine.LNX.4.44.0503160858490.20587-100000@hkn.eecs.berkeley.edu> [Forwarding to tutor@python.org. Oscar, when you reply next time, please use your email client's Reply-to-all feature. Otherwise, no one else will see the message.] ---------- Forwarded message ---------- Date: Wed, 16 Mar 2005 23:03:13 +1100 From: oscar ng <oscar2@aapt.net.au> To: 'Danny Yoo' <dyoo@hkn.eecs.berkeley.edu> Subject: RE: [Tutor] Newbie in Python (fwd) Hi Danny, Thanks for the reference. I managed to read all the folders and am able to open all the files in the directory using a for loop Here is the code: def getFiles(parent): #used to get the parent directory for the files to process mainFolder = os.listdir(parent) for a in mainFolder: if os.path.isdir(parent + "/" + a): subfolders = [a] ##set the subfolders to the its ##categories print subfolders getFiles(parent + "/" + a) else: fileName = [parent + "/" + a] listFile = a #listFile is a list that holds the name of #files #print listFile, #listFile[a] +=1 #print listFile words=[] for b in fileName: inputFile = open(b) #inputFile holds the #individual/basic files to be #processed listText = inputFile.read() #listText holds entire texts of #all the files from parent #directory print listText I need now to ask how I can process the headers "subject" of each individual email/file as the content of the "subject" determines the appropriate category I need to place them into. As listtext only prints all the emails in the folder. Also is there a way I can count the number of files ie listFile[a] +=1 as this keeps giving errors when running it. Thanks heaps Oscar From dyoo at hkn.eecs.berkeley.edu Wed Mar 16 18:10:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 16 18:11:02 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: <20050316160030.65175.qmail@web53810.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0503160905590.20587-100000@hkn.eecs.berkeley.edu> On Wed, 16 Mar 2005, Shitiz Bansal wrote: > No, this list is not a linked list. > Since mu original code is rather huge, I am presenting > the relevant snippet. > queue=[] > def genpassenger(num,destination,queue=queue): > for i in range(num): > newpass=passenger(destination) > queue.append(newpass) > newpass.start() > class passenger(threading.Thread): > def __init__ > <snip> > def run: > #do something > delete itself > > genpassengers is called interactively by the user Ok, this makes sense. Each passenger thread needs to know about the queue, because that's the place you want the passenger to drop out of. Lists support a 'remove()' method, so you may be able to use it. > 2) If i used a linked list, does automatic memory handling by python > entail that delete itself is automatically accomplished once i have > readjusted the pointers, since no further reference to the instance > remains. Yes. > 3) How about making a destructor function (on lines of c++) and > deleting all the variables of the class. This is usually unnecessary, as the same garbage collection that recycles the class does the same to attributes of the class. If you have more questions, please feel free to ask! From kent37 at tds.net Wed Mar 16 18:27:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 16 18:27:20 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: <20050316160030.65175.qmail@web53810.mail.yahoo.com> References: <20050316160030.65175.qmail@web53810.mail.yahoo.com> Message-ID: <42386C75.6090202@tds.net> Shitiz Bansal wrote: > No, this list is not a linked list. > Since mu original code is rather huge, I am presenting > the relevant snippet. > queue=[] > def genpassenger(num,destination,queue=queue): > for i in range(num): > newpass=passenger(destination) > queue.append(newpass) > newpass.start() > class passenger(threading.Thread): > def __init__ > <snip> > def run: > #do something > delete itself > > genpassengers is called interactively by the user > .Also there can be multiple instances of genpassengers > running at the same time. > Now my questions are: > 1) Generically , how do i accomplish the delete itself > part In the code you have shown, I don't see any need for the queue. Just create the thread and start it. I don't think you have to keep a reference to it. I'm not sure, but I think the thread will be garbage collected when it completes. (Can anyone else confirm this?) > 2) If i used a linked list, does automatic memory > handling by python entail that delete itself is > automatically accomplished once i have readjusted the > pointers, since no further reference to the instance > remains.(Of course, if it doesnt i can get a reference > in the external code(in case of a doubly linked > list)). Yes. When there is no remaining reference to an item it is garbage collected. > 3) How about making a destructor function (on lines > of c++) and deleting all the variables of the > class.Does it free all my memory or is there still > some memory being used, though the instance has no > variables stored. This is not needed. When a class is GCed then everything it references will also be GCed, unless something else still retains a reference to it. Kent From shitizb at yahoo.com Wed Mar 16 19:52:23 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 16 19:52:28 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: 6667 Message-ID: <20050316185224.491.qmail@web53803.mail.yahoo.com> --- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > Ok, this makes sense. Each passenger thread needs > to know about the > queue, because that's the place you want the > passenger to drop out of. > > Lists support a 'remove()' method, so you may be > able to use it. Does it operate like queue.remove(self) ? Because the instance has no way of knowing its position in the queue. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From shitizb at yahoo.com Wed Mar 16 19:55:05 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Wed Mar 16 19:55:08 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: 6667 Message-ID: <20050316185505.32129.qmail@web53810.mail.yahoo.com> > In the code you have shown, I don't see any need for > the queue. Just create the thread and start it. > I don't think you have to keep a reference to it. > I'm not sure, but I think the thread will be > garbage collected when it completes. (Can anyone > else confirm this?) This does make sense,but how can we confirm that the instance is not garbage collected before it ends?is this the default behyaviour? Shitiz __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Wed Mar 16 20:18:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 16 20:18:34 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: <20050316185224.491.qmail@web53803.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0503161114190.15718-100000@hkn.eecs.berkeley.edu> > --- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > Ok, this makes sense. Each passenger thread needs to know about the > > queue, because that's the place you want the passenger to drop out of. > > > > Lists support a 'remove()' method, so you may be able to use it. > > Does it operate like queue.remove(self) ? Because the instance has no > way of knowing its position in the queue. Hello, True, but if I have a bag of marbles, and I want to pick out a blue marble, I don't have to know the exact position of the marble. *grin* ### >>> class Marble: ... def __init__(self, color): ... self.color = color ... def __repr__(self): ... return "Marble(%s)" % self.color ... >>> bagOfMarbles = [Marble("red"), Marble("yellow"), Marble("blue"), ... Marble("green")] >>> blueMarble = bagOfMarbles[2] >>> >>> bagOfMarbles.insert(0, Marble("black")) >>> >>> bagOfMarbles [Marble(black), Marble(red), Marble(yellow), Marble(blue), Marble(green)] >>> bagOfMarbles.remove(blueMarble) >>> >>> bagOfMarbles [Marble(black), Marble(red), Marble(yellow), Marble(green)] ### Hope this helps! From kent37 at tds.net Wed Mar 16 20:44:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 16 20:44:05 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: <20050316185505.32129.qmail@web53810.mail.yahoo.com> References: <20050316185505.32129.qmail@web53810.mail.yahoo.com> Message-ID: <42388C81.70107@tds.net> Shitiz Bansal wrote: > >>In the code you have shown, I don't see any need for >>the queue. Just create the thread and start it. >>I don't think you have to keep a reference to it. >>I'm not sure, but I think the thread will be >>garbage collected when it completes. (Can anyone >>else confirm this?) > > > This does make sense,but how can we confirm that the > instance is not garbage collected before it ends?is > this the default behyaviour? I just asked on comp.lang.python, we'll see what the experts say. Kent From john.ertl at fnmoc.navy.mil Wed Mar 16 21:04:48 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Mar 16 21:02:31 2005 Subject: [Tutor] Image manipulation Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C595@lanexc107p.fnmoc.navy.mil> All, I have an image with a bunch of white space that I need to crop. I would like to automate the process using python and I was wondering what is the best module for image manipulation? I have seen PIL and Python magic what is recommended? John Ertl From michael.hall at critterpixstudios.com Wed Mar 16 21:12:32 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 16 21:12:47 2005 Subject: [Tutor] stopping greedy matches Message-ID: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> I'm having trouble getting re to stop matching after it's consumed what I want it to. Using this string as an example, the goal is to match "CAPS": >>> s = "only the word in CAPS should be matched" So let's say I want to specify when to begin my pattern by using a lookbehind: >>> x = re.compile(r"(?<=\bin)") #this will simply match the spot in front of "in" So that's straight forward, but let's say I don't want to use a lookahead to specify the end of my pattern, I simply want it to stop after it has combed over the word following "in". I would expect this to work, but it doesn't: >>> x=re.compile(r"(?<=\bin).+\b") #this will consume everything past "in" all the way to the end of the string In the above example I would think that the word boundary flag "\b" would indicate a stopping point. Is ".+\b" not saying, "keep matching characters until a word boundary has been reached"? Even stranger are the results I get from: >>> x=re.compile(r"(?<=\bin).+\s") #keep matching characters until a whitespace has been reached(?) >>> r = x.sub("!@!", s) >>> print r only the word in!@!matched For some reason there it's decided to consume three words instead of one. My question is simply this: after specifying a start point, how do I make a match stop after it has found one word, and one word only? As always, all help is appreciated. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1962 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050316/493b95ce/attachment.bin From cyresse at gmail.com Wed Mar 16 22:50:41 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 16 22:50:45 2005 Subject: [Tutor] Newbie in Python (fwd) In-Reply-To: <Pine.LNX.4.44.0503160858490.20587-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503160858490.20587-100000@hkn.eecs.berkeley.edu> Message-ID: <f2ff2d050316135022805bf7@mail.gmail.com> Hi Oscar, processing emails... you want to use the email module. I believe, you'd go like this (and this is rough, and untested, docs are http://docs.python.org/lib/node565.html) >>>import email >>>parser = email.HeaderParser() >>> msgFile = file('email.txt','r') >>> msgObj = parser.parse(msgFile) >>> print msgObj['subject'] Try that out, it should do it for you... might have to tweak it, as I don't the intepreter here. Regards, Liam Clarke On Wed, 16 Mar 2005 09:01:05 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > [Forwarding to tutor@python.org. Oscar, when you reply next time, please > use your email client's Reply-to-all feature. Otherwise, no one else will > see the message.] > > > ---------- Forwarded message ---------- > Date: Wed, 16 Mar 2005 23:03:13 +1100 > From: oscar ng <oscar2@aapt.net.au> > To: 'Danny Yoo' <dyoo@hkn.eecs.berkeley.edu> > Subject: RE: [Tutor] Newbie in Python (fwd) > > Hi Danny, > > Thanks for the reference. I managed to read all the folders and am able > to open all the files in the directory using a for loop > Here is the code: > > def getFiles(parent): > #used to get the parent directory for the files to process > > mainFolder = os.listdir(parent) > > for a in mainFolder: > if os.path.isdir(parent + "/" + a): > subfolders = [a] ##set the subfolders to the its > ##categories > print subfolders > getFiles(parent + "/" + a) > > else: > > fileName = [parent + "/" + a] > > listFile = a #listFile is a list that holds the name > of #files > > #print listFile, > > #listFile[a] +=1 > #print listFile > > words=[] > for b in fileName: > inputFile = open(b) #inputFile holds the > #individual/basic files to be > #processed > listText = inputFile.read() #listText holds entire texts > of #all the files > from parent > #directory > > print listText > > I need now to ask how I can process the headers "subject" of each > individual email/file as the content of the "subject" determines the > appropriate category I need to place them into. As listtext only prints > all the emails in the folder. > > Also is there a way I can count the number of files ie listFile[a] +=1 > as this keeps giving errors when running it. > > Thanks heaps > > Oscar > > > _______________________________________________ > 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. From cyresse at gmail.com Wed Mar 16 23:31:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 16 23:31:10 2005 Subject: [Tutor] Newbie in Python (fwd) In-Reply-To: <f2ff2d050316135022805bf7@mail.gmail.com> References: <Pine.LNX.4.44.0503160858490.20587-100000@hkn.eecs.berkeley.edu> <f2ff2d050316135022805bf7@mail.gmail.com> Message-ID: <f2ff2d0503161431137d0f52@mail.gmail.com> Oh and > listFile = a #listFile is a list that holds the name >of #files #print listFile, I don't know what errors you're getting but considering this - #listFile[a] +=1 I can see what you're trying to do. So, we have this code: for a in mainFolder: #do some stuff listFile = a listFile[a] += 1 First off, this isn't a list, yet. listFile = [] for a in mainFolder: #do some stuff listFile = a listFile[a] += 1 listFile is now a list, but we're still going to get errors. listFile = a changes listFile from a list to the value of a, it looks like you want to add a to the list, and then add a new value of a at each pass over the loop which is this line. listFile[a] +=1 Now that will fail, because an index for a list must be an integer, i.e. >>>x=['a','b','c'] >>> print x[1] b >>> print x[b] KeyError What you want is the list method append. >>> x = ['a','b'] >>> x.append('c') >>>print x ['a','b','c'] So, we can rewrite this - for a in mainFolder: #do some stuff listFile = a listFile[a] += 1 as listFile = [] for a in mainFolder: #do some stuff listFile.append(a) and it should work fine. On Thu, 17 Mar 2005 10:50:41 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Hi Oscar, > > processing emails... you want to use the email module. > > I believe, you'd go like this (and this is rough, and untested, docs are > http://docs.python.org/lib/node565.html) > > >>>import email > >>>parser = email.HeaderParser() > >>> msgFile = file('email.txt','r') > >>> msgObj = parser.parse(msgFile) > >>> print msgObj['subject'] > > Try that out, it should do it for you... might have to tweak it, as I > don't the intepreter here. > > Regards, > > Liam Clarke > > > On Wed, 16 Mar 2005 09:01:05 -0800 (PST), Danny Yoo > <dyoo@hkn.eecs.berkeley.edu> wrote: > > > > [Forwarding to tutor@python.org. Oscar, when you reply next time, please > > use your email client's Reply-to-all feature. Otherwise, no one else will > > see the message.] > > > > > > ---------- Forwarded message ---------- > > Date: Wed, 16 Mar 2005 23:03:13 +1100 > > From: oscar ng <oscar2@aapt.net.au> > > To: 'Danny Yoo' <dyoo@hkn.eecs.berkeley.edu> > > Subject: RE: [Tutor] Newbie in Python (fwd) > > > > Hi Danny, > > > > Thanks for the reference. I managed to read all the folders and am able > > to open all the files in the directory using a for loop > > Here is the code: > > > > def getFiles(parent): > > #used to get the parent directory for the files to process > > > > mainFolder = os.listdir(parent) > > > > for a in mainFolder: > > if os.path.isdir(parent + "/" + a): > > subfolders = [a] ##set the subfolders to the its > > ##categories > > print subfolders > > getFiles(parent + "/" + a) > > > > else: > > > > fileName = [parent + "/" + a] > > > > listFile = a #listFile is a list that holds the name > > of #files > > > > #print listFile, > > > > #listFile[a] +=1 > > #print listFile > > > > words=[] > > for b in fileName: > > inputFile = open(b) #inputFile holds the > > #individual/basic files to be > > #processed > > listText = inputFile.read() #listText holds entire texts > > of #all the files > > from parent > > #directory > > > > print listText > > > > I need now to ask how I can process the headers "subject" of each > > individual email/file as the content of the "subject" determines the > > appropriate category I need to place them into. As listtext only prints > > all the emails in the folder. > > > > Also is there a way I can count the number of files ie listFile[a] +=1 > > as this keeps giving errors when running it. > > > > Thanks heaps > > > > Oscar > > > > > > _______________________________________________ > > 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. > -- '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. From cyresse at gmail.com Wed Mar 16 23:36:05 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 16 23:36:08 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> Message-ID: <f2ff2d05031614365d173568@mail.gmail.com> > >>> x=re.compile(r"(?<=\bin).+\b") Try >>> x = re.compile("in (.*?)\b") .*? is a non-greedy matcher I believe. Are you using python24/tools/scripts/redemo.py? Use that to test regexes. Regards, Liam Clarke On Wed, 16 Mar 2005 12:12:32 -0800, Mike Hall <michael.hall@critterpixstudios.com> wrote: > I'm having trouble getting re to stop matching after it's consumed what > I want it to. Using this string as an example, the goal is to match > "CAPS": > > >>> s = "only the word in CAPS should be matched" > > So let's say I want to specify when to begin my pattern by using a > lookbehind: > > >>> x = re.compile(r"(?<=\bin)") #this will simply match the spot in > front of "in" > > So that's straight forward, but let's say I don't want to use a > lookahead to specify the end of my pattern, I simply want it to stop > after it has combed over the word following "in". I would expect this > to work, but it doesn't: > > >>> x=re.compile(r"(?<=\bin).+\b") #this will consume everything past > "in" all the way to the end of the string > > In the above example I would think that the word boundary flag "\b" > would indicate a stopping point. Is ".+\b" not saying, "keep matching > characters until a word boundary has been reached"? > > Even stranger are the results I get from: > > >>> x=re.compile(r"(?<=\bin).+\s") #keep matching characters until a > whitespace has been reached(?) > >>> r = x.sub("!@!", s) > >>> print r > only the word in!@!matched > > For some reason there it's decided to consume three words instead of > one. > > My question is simply this: after specifying a start point, how do I > make a match stop after it has found one word, and one word only? As > always, all help is appreciated. > > > _______________________________________________ > 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. From michael.hall at critterpixstudios.com Thu Mar 17 01:21:27 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu Mar 17 01:21:44 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <f2ff2d05031614365d173568@mail.gmail.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> Message-ID: <81a243c654094043833a55e295cfffd7@critterpixstudios.com> Liam, "re.compile("in (.*?)\b")" will not find any match in the example string I provided. I have had little luck with these non-greedy matchers. I don't appear to have redemo.py on my system (on OSX), as an import returns an error. I will look into finding this module, thanks for pointing me towards it :) On Mar 16, 2005, at 2:36 PM, Liam Clarke wrote: >>>>> x=re.compile(r"(?<=\bin).+\b") > > Try > >>>> x = re.compile("in (.*?)\b") > > .*? is a non-greedy matcher I believe. > > Are you using python24/tools/scripts/redemo.py? Use that to test > regexes. > > Regards, > > Liam Clarke > > On Wed, 16 Mar 2005 12:12:32 -0800, Mike Hall > <michael.hall@critterpixstudios.com> wrote: >> I'm having trouble getting re to stop matching after it's consumed >> what >> I want it to. Using this string as an example, the goal is to match >> "CAPS": >> >>>>> s = "only the word in CAPS should be matched" >> >> So let's say I want to specify when to begin my pattern by using a >> lookbehind: >> >>>>> x = re.compile(r"(?<=\bin)") #this will simply match the spot in >> front of "in" >> >> So that's straight forward, but let's say I don't want to use a >> lookahead to specify the end of my pattern, I simply want it to stop >> after it has combed over the word following "in". I would expect this >> to work, but it doesn't: >> >>>>> x=re.compile(r"(?<=\bin).+\b") #this will consume everything past >> "in" all the way to the end of the string >> >> In the above example I would think that the word boundary flag "\b" >> would indicate a stopping point. Is ".+\b" not saying, "keep matching >> characters until a word boundary has been reached"? >> >> Even stranger are the results I get from: >> >>>>> x=re.compile(r"(?<=\bin).+\s") #keep matching characters until a >> whitespace has been reached(?) >>>>> r = x.sub("!@!", s) >>>>> print r >> only the word in!@!matched >> >> For some reason there it's decided to consume three words instead of >> one. >> >> My question is simply this: after specifying a start point, how do I >> make a match stop after it has found one word, and one word only? As >> always, all help is appreciated. >> >> >> _______________________________________________ >> 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. > From michael.hall at critterpixstudios.com Thu Mar 17 02:45:48 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu Mar 17 02:45:56 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <4238DE41.9080107@speakeasy.net> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <4238DE41.9080107@speakeasy.net> Message-ID: <186bedf8e4ccb10f3afb21538f517edb@critterpixstudios.com> On Mar 16, 2005, at 5:32 PM, Sean Perry wrote: > I know this does not directly help, but I have never successfully used > \b in my regexs. I always end up writing something like foo\s+bar or > something more intense. I've had luck with the boundary flag in relation to lookbehinds. For example, if I wanted to only match after "int" (and not "print") (?<=\bint) seems to work fine. I'm a bit frustrated at not being able to find a simple way to have a search stop after eating up one word. You'd think the \b would do it, but nope. From keridee at jayco.net Thu Mar 17 02:47:45 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Mar 17 02:47:40 2005 Subject: [Tutor] Convert doesn't work... I'm stumped References: <Pine.LNX.4.44.0503160036530.7883-100000@hkn.eecs.berkeley.edu> Message-ID: <000a01c52a93$5bfa3310$855328cf@JSLAPTOP> Oh, god!! I found my problem... I was using the inverses incorrectly -- in Advanced Calculus and I can't even do algebra correctly. To make a long story short, in the second functions I was putting the x in the denominator when it needs to be in the numerator... But! Your post is not in vain, Danny. I like the idea of storing the value instead of two functions. As for the rational module--I didn't know it existed, so I have written my own. I was going to post it some time this week to flaunt my newest cool thing, but this caught my attention... Thanks! Jacob > > >> A table that stores a similar amount of information might be something >> like this: >> >> ### >> meterRatios = { 'm' : D(1), ## 1 meter == 1 meter >> 'km' : D(1000), ## 1000 meters == 1 kilometer >> 'cm' : D(1)/D(100), ## .001 meters == 1 centimeter >> 'mm' : D(1)/D(1000), ## .0001 meters == 1 millimeter >> } >> ### >> > [some text cut] >> >> That is, from the table above, we can see that since there's one meter >> to a thousanth of a millimeter, we can go the other way and say that one >> thousand millimeters is one meter. (1/x) > > > Oh good grief, did I really write that? I'm sorry, I meant to say: > > """[...] since there's one-thousandth of a meter in a millimeter, we can > go the other way and say that there are one thousand millimeters in one > meter. """ > > I can debug code with some fluency, but I have to do better to debug my > English. *grin* > > > From keridee at jayco.net Thu Mar 17 02:51:14 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Mar 17 02:50:27 2005 Subject: [Tutor] Re: Convert doesn't work... I'm stumped References: <000b01c529db$36979e90$c65428cf@JSLAPTOP> <d18c7j$4i4$1@sea.gmane.org> Message-ID: <000f01c52a93$d3a37070$855328cf@JSLAPTOP> Ahh... I found that out today. A little more rest, I guess. As for unit testing, I've seen it used, but I've never implemented it. I've tried doc string testing with doctest, but I find I can do better just using the interactive interpreter. (I don't know why. Impatience I guess. Maybe I just want to see the answer pop up as I type it I guess...) Thanks, Jacob From csw at k12hq.com Thu Mar 17 05:00:29 2005 From: csw at k12hq.com (Christopher Weimann) Date: Thu Mar 17 05:01:19 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> Message-ID: <20050317040029.GE35825@tektite.k12usa.internal> On 03/16/2005-12:12PM, Mike Hall wrote: > I'm having trouble getting re to stop matching after it's consumed > what I want it to. Using this string as an example, the goal is to > match "CAPS": > > >>> s = "only the word in CAPS should be matched" > jet% python Python 2.4 (#2, Jan 5 2005, 15:59:52) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> s = "only the word in CAPS should be matched" >>> x=re.compile(r"\bin ([^\s]+)") >>> x.findall(s) ['CAPS'] >>> From kent37 at tds.net Thu Mar 17 05:17:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 05:17:14 2005 Subject: [Tutor] Re: Convert doesn't work... I'm stumped In-Reply-To: <000f01c52a93$d3a37070$855328cf@JSLAPTOP> References: <000b01c529db$36979e90$c65428cf@JSLAPTOP> <d18c7j$4i4$1@sea.gmane.org> <000f01c52a93$d3a37070$855328cf@JSLAPTOP> Message-ID: <423904C4.8050400@tds.net> Jacob S. wrote: > Ahh... I found that out today. A little more rest, I guess. > > As for unit testing, I've seen it used, but I've never implemented it. > I've tried doc string testing with doctest, but I find I can do better just > using the interactive interpreter. I think one way to use doctest is to copy and paste from the interactive interpreter. So your ad hoc tests are preserved as documentation and unit tests. I have never tried this myself, though; I'm a fan of unittest. Kent From kent37 at tds.net Thu Mar 17 05:32:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 05:32:10 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <81a243c654094043833a55e295cfffd7@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> Message-ID: <42390844.5030600@tds.net> Mike Hall wrote: > Liam, "re.compile("in (.*?)\b")" will not find any match in the example > string I provided. I have had little luck with these non-greedy matchers. "in (.*?)\b" will match against "in " because you use .* which will match an empty string. Try "in (.+?)\b" (or "(?<=\bin)..+?\b" )to require one character after the space. The non-greedy match is very useful, if you can't get it to work ask for help. > I don't appear to have redemo.py on my system (on OSX), as an import > returns an error. I will look into finding this module, thanks for > pointing me towards it :) You can't import it, you have to run it from the command line. I don't know if it is installed under Mac OSX though. You might be interested in RegexPlor: http://python.net/~gherman/RegexPlor.html Kent From javier at ruere.com.ar Thu Mar 17 06:14:35 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Thu Mar 17 06:10:07 2005 Subject: [Tutor] Re: Convert doesn't work... I'm stumped In-Reply-To: <000f01c52a93$d3a37070$855328cf@JSLAPTOP> References: <000b01c529db$36979e90$c65428cf@JSLAPTOP> <d18c7j$4i4$1@sea.gmane.org> <000f01c52a93$d3a37070$855328cf@JSLAPTOP> Message-ID: <d1b3c6$s9c$1@sea.gmane.org> Jacob S. wrote: > I've tried doc string testing with doctest, but I find I can do better just > using the interactive interpreter. Do better? With doctest you protect yourself from future bugs. How can you do better just using the interpreter? Mr. Johnson has already pointed out how to make doctests. > (I don't know why. Impatience I guess. > Maybe I just want to see the answer pop up as I type it I guess...) Using the interpreter for testing and exploring is great IMO but don't throw away your tests!! Javier From smichr at hotmail.com Thu Mar 17 06:45:40 2005 From: smichr at hotmail.com (C Smith) Date: Thu Mar 17 06:46:50 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <20050316074621.0EE481E401C@bag.python.org> Message-ID: <BAY101-DAV6462CE0A3EC7971ACF43AC1490@phx.gbl> Hi Jacob, Watch out with your code, ### if i==1000: i=0 else: i=i+1 ### Since this test is done after you have stored your data you are actually going to store 1001 pieces of data. i starts at 0 you store 0 you do your test and i is incremented {that's set 1} i is 1 you store 1 you do your test and i is incremented {that's set 2} ... i is 1000 you store 1000 you do your test and i is set to 0 {that's set 10001} Also, it looks like you have that i-incrementing happening at the same level as the if-test. If so, it is possible that the i's that are used to store the data will not increase by 1 each time since they are being incremented for every k and not only when the data is being stored. If you only want it incremented when something is stored, put it inside the if-block. Also, consider using the modulo operator to keep track of i: replace your test with ### i = (i+1)%1000 ### i starts and 0 and will be incremented until it is 999 and then when this calculation is then performed you will calculate (999+1)%1000 which is 1000%1000 which is 0--just what you wanted. Here's an example that cycles through 3 number, 0, 1, and 2: ### >>> j=0 >>> for i in range(10): .. print j .. j = (j+1)%3 .. 0 1 2 0 1 2 0 1 2 0 ### /c From misha.dunn at gmail.com Thu Mar 17 10:31:03 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Thu Mar 17 10:31:05 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <42390844.5030600@tds.net> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <42390844.5030600@tds.net> Message-ID: <e95c92e0050317013144b75513@mail.gmail.com> As Kent said, redemo.py is a script that you run (e.g. from the command line), rather than something to import into the python interpretor. On my OSX machine it's located in the directory: /Applications/MacPython-2.3/Extras/Tools/scripts Cheers, Michael From kent37 at tds.net Thu Mar 17 12:05:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 12:05:46 2005 Subject: [Tutor] creating a tab delimited filename In-Reply-To: <BAY101-DAV6462CE0A3EC7971ACF43AC1490@phx.gbl> References: <BAY101-DAV6462CE0A3EC7971ACF43AC1490@phx.gbl> Message-ID: <42396485.3010205@tds.net> C Smith wrote: > Here's an example that > cycles through 3 number, 0, 1, and 2: > > ### > >>> j=0 > >>> for i in range(10): > .. print j > .. j = (j+1)%3 > .. > 0 > 1 > 2 > 0 > 1 > 2 > 0 > 1 > 2 > 0 > ### A nice way to do this is with itertools.cycle(): >>> import itertools >>> cyc = itertools.cycle(range(3)) >>> for i in range(10): ... print cyc.next() ... 0 1 2 0 1 2 0 1 2 0 Kent From kent37 at tds.net Thu Mar 17 14:44:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 14:45:31 2005 Subject: [Tutor] cyclically rotate a seq In-Reply-To: <06a00814fb84905368897eb9cfbc837a@mac.com> References: <20050310110107.02CD51E4014@bag.python.org> <06a00814fb84905368897eb9cfbc837a@mac.com> Message-ID: <423989D4.6000709@tds.net> kevin parks wrote: > Hi folks, > > I am trying to cyclically rotate a seq until it reached the beginning > stage again. > I would like to be able BTW collections.deque supports most list methods and rotate(): http://docs.python.org/lib/module-collections.html Kent From kent37 at tds.net Thu Mar 17 15:26:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 15:26:41 2005 Subject: [Tutor] How to delete a class instance In-Reply-To: <42388C81.70107@tds.net> References: <20050316185505.32129.qmail@web53810.mail.yahoo.com> <42388C81.70107@tds.net> Message-ID: <4239939D.60700@tds.net> Kent Johnson wrote: > Shitiz Bansal wrote: > >> >>> In the code you have shown, I don't see any need for >>> the queue. Just create the thread and start it. I don't think you >>> have to keep a reference to it. >>> I'm not sure, but I think the thread will be garbage collected when >>> it completes. (Can anyone >>> else confirm this?) >> >> >> >> This does make sense,but how can we confirm that the >> instance is not garbage collected before it ends?is >> this the default behyaviour? > > > I just asked on comp.lang.python, we'll see what the experts say. You can see my question and Martin v. L?wis' answer here: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1ae7b20b397c4a7e/8d458a7dfaec1d42?tvc=2 He clearly says that the thread will not be GCed until after it completes, so you don't have to save a reference to it. Kent From mark.kels at gmail.com Thu Mar 17 17:13:12 2005 From: mark.kels at gmail.com (Mark Kels) Date: Thu Mar 17 17:13:16 2005 Subject: [Tutor] Unreadable code explanation Message-ID: <c225925305031708136c9993d5@mail.gmail.com> Hi list. I have downloaded some code from useless python that was writen buy a guy named Sammy Mannaert. The code should show that python can be unreadable, and it really is... Can anyone explain to me how does this thing works ?? Here is the code (it prints "python readable ?"): f=lambda x="8<:477\02092020162\020\037",y="01001000110100101":reduce(lambda x,y:x+y,map(lambda y,x:chr(ord(y)*2+x),x,map(int,y)));print f(); (it all should be in one line) Hope you can help :) Thanks in advance. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From kent37 at tds.net Thu Mar 17 18:14:24 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 18:14:31 2005 Subject: [Tutor] Unreadable code explanation In-Reply-To: <c225925305031708136c9993d5@mail.gmail.com> References: <c225925305031708136c9993d5@mail.gmail.com> Message-ID: <4239BAF0.4040005@tds.net> Mark Kels wrote: > Hi list. > I have downloaded some code from useless python that was writen buy a > guy named Sammy Mannaert. The code should show that python can be > unreadable, and it really is... > Can anyone explain to me how does this thing works ?? > Here is the code (it prints "python readable ?"): > f=lambda x="8<:477\02092020162\020\037",y="01001000110100101":reduce(lambda > x,y:x+y,map(lambda y,x:chr(ord(y)*2+x),x,map(int,y)));print f(); > (it all should be in one line) Maybe this helps, I just pulled it apart from the inside: # The original f=lambda x="8<:477\02092020162\020\037",y="01001000110100101":reduce(lambda x,y:x+y,map(lambda y,x:chr(ord(y)*2+x),x,map(int,y))) print f() # A silly function to combine a number and a character making a new character def makeChar(y, x): return chr(ord(y)*2+x) f=lambda x="8<:477\02092020162\020\037",y="01001000110100101":reduce(lambda x,y:x+y,map(makeChar,x,map(int,y))) print f() # Pull out x and y x="8<:477\02092020162\020\037" y="01001000110100101" yInts = map(int,y) # This turns y into a list of ints print 'yInts:', yInts f=lambda:reduce(lambda x,y:x+y,map(makeChar,x,yInts)) print f() # Pull out the last lambda - this is the step that combines x and y into a list of chars chars = map(makeChar,x,yInts) print 'chars:', chars f=lambda:reduce(lambda x,y:x+y,chars) # This is just an obscure way to join the list into a string print f() f = ''.join(chars) print f Kent From eduff23 at yahoo.com Thu Mar 17 19:13:23 2005 From: eduff23 at yahoo.com (Edie Duff) Date: Thu Mar 17 19:13:26 2005 Subject: [Tutor] Can Python work like SAS Data Step Message-ID: <20050317181323.44349.qmail@web51308.mail.yahoo.com> Can Python work like the SAS (Data Step), where you read in external data (sequential, ms access, sql) define file layout to Python and be able to write code where you produce a customize report with title and columns headings, subtotals and totals and write that report out has a file? And if it can, where can I find examples/documentation on how to do it? Thanks E Duff __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050317/5730d8ea/attachment.html From michael.hall at critterpixstudios.com Thu Mar 17 19:15:18 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu Mar 17 19:15:40 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <20050317040029.GE35825@tektite.k12usa.internal> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <20050317040029.GE35825@tektite.k12usa.internal> Message-ID: <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> <applause> Very nice sir. I'm interested in what you're doing here with the caret metacharacter. For one thing, why enclose it and the whitespace flag within a character class? Does this not traditionally mean you want to strip a metacharacter of it's special meaning? On Mar 16, 2005, at 8:00 PM, Christopher Weimann wrote: > On 03/16/2005-12:12PM, Mike Hall wrote: >> I'm having trouble getting re to stop matching after it's consumed >> what I want it to. Using this string as an example, the goal is to >> match "CAPS": >> >>>>> s = "only the word in CAPS should be matched" >> > > jet% python > Python 2.4 (#2, Jan 5 2005, 15:59:52) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. >>>> import re >>>> s = "only the word in CAPS should be matched" >>>> x=re.compile(r"\bin ([^\s]+)") >>>> x.findall(s) > ['CAPS'] >>>> > From michael.hall at critterpixstudios.com Thu Mar 17 19:36:24 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu Mar 17 19:36:41 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <42390844.5030600@tds.net> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <42390844.5030600@tds.net> Message-ID: <2881c57ebcddf19d672c3013203743eb@critterpixstudios.com> On Mar 16, 2005, at 8:32 PM, Kent Johnson wrote: > "in (.*?)\b" will match against "in " because you use .* which will > match an empty string. Try "in (.+?)\b" (or "(?<=\bin)..+?\b" )to > require one character after the space. >> Another working example, excellent. I'm not too clear on why the back to back ".." in "(?<=\bin)..+?\b" )" makes the regex work, but it does. > > You can't import it, you have to run it from the command line. I don't > know if it is installed under Mac OSX though. You might be interested > in RegexPlor: > http://python.net/~gherman/RegexPlor.html > RegexPlor looks fantastic, will be downloading. Thanks. From michael.hall at critterpixstudios.com Thu Mar 17 20:01:19 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu Mar 17 20:01:31 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <e95c92e0050317013144b75513@mail.gmail.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <42390844.5030600@tds.net> <e95c92e0050317013144b75513@mail.gmail.com> Message-ID: <8a83d6f70ea1bd1cf3fa02b7c2e589f2@critterpixstudios.com> I don't have that script on my system, but I may put pythoncard on here and run it through that: http://pythoncard.sourceforge.net/samples/redemo.html Although regexPlor looks like it has the same functionality, so I may just go with that. Thanks. On Mar 17, 2005, at 1:31 AM, Michael Dunn wrote: > As Kent said, redemo.py is a script that you run (e.g. from the > command line), rather than something to import into the python > interpretor. On my OSX machine it's located in the directory: > > /Applications/MacPython-2.3/Extras/Tools/scripts > > Cheers, Michael > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Mar 17 20:11:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 20:11:16 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <2881c57ebcddf19d672c3013203743eb@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <42390844.5030600@tds.net> <2881c57ebcddf19d672c3013203743eb@critterpixstudios.com> Message-ID: <4239D650.7050900@tds.net> Mike Hall wrote: > On Mar 16, 2005, at 8:32 PM, Kent Johnson wrote: > >> "in (.*?)\b" will match against "in " because you use .* which will >> match an empty string. Try "in (.+?)\b" (or "(?<=\bin)..+?\b" )to >> require one character after the space. >> >>> > Another working example, excellent. I'm not too clear on why the back to > back ".." in "(?<=\bin)..+?\b" )" makes the regex work, but it does. The first one matches the space after 'in'. Without it the .+? will match the single space, then \b matches the *start* of the next word. Kent From michael.hall at critterpixstudios.com Thu Mar 17 20:47:54 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Thu Mar 17 20:48:13 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <4239D650.7050900@tds.net> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <42390844.5030600@tds.net> <2881c57ebcddf19d672c3013203743eb@critterpixstudios.com> <4239D650.7050900@tds.net> Message-ID: <51290251eef348fb4033dc97af00933c@critterpixstudios.com> On Mar 17, 2005, at 11:11 AM, Kent Johnson wrote: > The first one matches the space after 'in'. Without it the .+? will > match the single space, then \b matches the *start* of the next word. I think I understand. Basically the first dot advances the pattern forward in order to perform a non-greedy match on the following word.(?) Very nice. From kent37 at tds.net Thu Mar 17 21:18:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 17 21:18:43 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <51290251eef348fb4033dc97af00933c@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <f2ff2d05031614365d173568@mail.gmail.com> <81a243c654094043833a55e295cfffd7@critterpixstudios.com> <42390844.5030600@tds.net> <2881c57ebcddf19d672c3013203743eb@critterpixstudios.com> <4239D650.7050900@tds.net> <51290251eef348fb4033dc97af00933c@critterpixstudios.com> Message-ID: <4239E61F.7000306@tds.net> Mike Hall wrote: > > On Mar 17, 2005, at 11:11 AM, Kent Johnson wrote: > >> The first one matches the space after 'in'. Without it the .+? will >> match the single space, then \b matches the *start* of the next word. > > > I think I understand. Basically the first dot advances the pattern > forward in order to perform a non-greedy match on the following word.(?) > Very nice. That's right. The first dot could just as well be a space or \s or maybe even \s+ (to match any amount of white space). I actually used the dot because I thought it would be clearer than a space :-) Kent From elwis at linuxmail.org Mon Mar 14 11:51:50 2005 From: elwis at linuxmail.org (Stefan Elwesthal) Date: Thu Mar 17 22:11:06 2005 Subject: [Tutor] unicode Message-ID: <20050314105150.1749423CFD@ws5-3.us4.outblaze.com> Hello again! Well, I promise this is not a bad habit of mine. I've actually bought myself a few books about the lovely snake (did I just spend a year learning Java, why's that?). I thought I should brag a little for my fellow developer colleagues though, so i spent yetserday putting together a nice litttle Grid app using wxPython. The thing is, this little app reads records from a database using odbc.. and that's the problem. I'm swedish, our databae is full of horrible characters with strange dots on top and Python won't have none of it. it falls apart telling me that it can't decode that sort of thingy! So.. will I have to do some terrible magic storing all single values from the database in strings and run unicode methods on them before showing them in my wxGrid or is there a better way? (I'm going on bragging about how little code I need to write when I'm NOT using java.. ;) this is what I do now, i stole some example from thw web #fill the grid with data from the database for row in range(len(db.data)): for col in range(len(db.data[row])): values = db.data[row][col] self.grid_1.SetCellValue(row, col, str(values)) any help is welcome, best regards to you all Stefan Sweden -- ______________________________________________ Check out the latest SMS services @ http://www.linuxmail.org This allows you to send and receive SMS through your mailbox. Powered by Outblaze From hugonz at h-lab.net Tue Mar 15 15:39:45 2005 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu Mar 17 22:11:24 2005 Subject: [Tutor] big numbers In-Reply-To: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> References: <20050315150606.31c5fa2b.y2kbug@ms25.hinet.net> Message-ID: <4236F3B1.6070401@h-lab.net> Yes, it is: http://python.fyxm.net/peps/pep-0237.html Robert Storey wrote: > This book is a few years old and was written for Python version 1.5, and > of course I'm using version 2.3, so I'm just wondering if this whole > issue of big numbers is now being handled automatically? > > This is my first post - sorry to be asking such a basic question. I wouldn't consider it a basic question, and anyway this list allows for the most basic questions... Hope it helps, Hugo From logan at mat.uni.torun.pl Mon Mar 14 12:01:30 2005 From: logan at mat.uni.torun.pl (Przemyslaw Kisicki) Date: Thu Mar 17 22:11:37 2005 Subject: [Tutor] set(...) Message-ID: <Pine.GSO.4.58.0503141200360.17914@ultra60> I use: -------------------------------------------------------------------------------- Python 2.3.4 (#2, Aug 19 2004, 15:49:40) [GCC 3.4.1 (Mandrakelinux (Alpha 3.4.1-3mdk)] on linux2 ... IDLE 1.0.3 -------------------------------------------------------------------------------- I was trying to write: -------------------------------------------------------------------------------- >>> basket=['apple','orange','apple','pear','orange','banana'] >>> fruits=set(basket) -------------------------------------------------------------------------------- and I get: -------------------------------------------------------------------------------- Traceback (most recent call last): File "<pyshell#322>", line 1, in -toplevel- fruits=set(basket) NameError: name 'set' is not defined >>> -------------------------------------------------------------------------------- What's wrong? How to use sets? Logan From dyoo at hkn.eecs.berkeley.edu Thu Mar 17 22:26:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 17 22:26:27 2005 Subject: [Tutor] set(...) In-Reply-To: <Pine.GSO.4.58.0503141200360.17914@ultra60> Message-ID: <Pine.LNX.4.44.0503171321040.24168-100000@hkn.eecs.berkeley.edu> > I use: > -------------------------------------------------------------------------------- > Python 2.3.4 (#2, Aug 19 2004, 15:49:40) [GCC 3.4.1 (Mandrakelinux (Alpha > 3.4.1-3mdk)] on linux2 ... IDLE 1.0.3 > -------------------------------------------------------------------------------- > I was trying to write: > -------------------------------------------------------------------------------- > >>> basket=['apple','orange','apple','pear','orange','banana'] > >>> fruits=set(basket) > -------------------------------------------------------------------------------- > and I get: > -------------------------------------------------------------------------------- > Traceback (most recent call last): File "<pyshell#322>", line 1, in > -toplevel- fruits=set(basket) NameError: name 'set' is not defined > >>> > -------------------------------------------------------------------------------- > What's wrong? How to use sets? Hi Logan, Ah! I think you looking for the set() builtin, which was added in Python 2.4. But you're still using Python 2.3.4, when sets weren't "built in" yet. They're still accessible, but you have to do a module import in 2.3. You can make your example work by doing the following at the beginning: ### from sets import Set as set ### Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Thu Mar 17 22:35:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 17 22:35:33 2005 Subject: [Tutor] unicode In-Reply-To: <20050314105150.1749423CFD@ws5-3.us4.outblaze.com> Message-ID: <Pine.LNX.4.44.0503171327041.24168-100000@hkn.eecs.berkeley.edu> On Mon, 14 Mar 2005, Stefan Elwesthal wrote: > I'm swedish, our databae is full of horrible characters with strange > dots on top and Python won't have none of it. it falls apart telling me > that it can't decode that sort of thingy! > > So.. will I have to do some terrible magic storing all single values > from the database in strings and run unicode methods on them before > showing them in my wxGrid or is there a better way? (I'm going on > bragging about how little code I need to write when I'm NOT using java.. > ;) Hi Stefan, According to the wxpython-users list: http://aspn.activestate.com/ASPN/Mail/Message/wxpython-users/2514927 when you're setting the cell values, those values should be unicode strings. When you grab strings from the database, you'll probably need to take to know how they're encoded so that you can decode them properly. For example, if you know that the bytes in your database represent utf-8 characters, you probably need to do something like: ### Pseudocode decodedString = someStringInUtf8.decode("utf8") ### wxPython should handle the rest, though you probably want to talk with the wxpython-users directly to make sure. Here's a link to their mailing lists: http://www.wxpython.org/maillist.php Kent Johnson once posted an excellent set of link on Unicode basics on the tutor list. If you want to read a little more about Unicode, I'd recommend his article and the other one that he quoted. For your convenience, I'll just copy his links. *grin* http://www.pycs.net/users/0000323/stories/14.html http://www.joelonsoftware.com/articles/Unicode.html From glingl at aon.at Thu Mar 17 23:28:35 2005 From: glingl at aon.at (Gregor Lingl) Date: Thu Mar 17 23:52:35 2005 Subject: [Tutor] primes Message-ID: <423A0493.2000902@aon.at> Hi! Who knows a more concise or equally concise but more efficient expression, which returns the same result as [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] Gregor P.S.: ... or a more beautiful one ;-) From bvande at po-box.mcgill.ca Fri Mar 18 00:32:50 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Mar 18 00:39:59 2005 Subject: [Tutor] subclassing across multiple modules Message-ID: <423A13A2.8020405@po-box.mcgill.ca> Hi all, I'm uncertain of how to make use of OOP design across multiple modules. (Actually, on reflection, I'm not certain the multiple modules aspect is central.) I'm also uncertain of how to frame the question well, so please bear with me :-) A schematic of what I have (with fake names for ease of example) is a base module Toolkit.py and I want to write a module Application.py which specializes the behaviour of the Toolkit.py classes. (I'm using old-style classes, but don't feel committed to that choice.) Toolkit.py defines: class Tree class Node class Node1(Node) class Node2(Node) (other Node subclasses, too, but I'm simplifying.) The Tree class contains a parser method to parse a file. It reads the file, breaking it into chunks, and for each chunk, does the following: if some_condition_on_chunk_contents: node = Node1(chunk_contents) else: node = Node2(chunk_contents) self.nodes.append(node) Application.py will define class Tree(Toolkit.Tree) class Node(Toolkit.Node) class Node1(Node, Toolkit.Node1) class Node2(Node, Toolkit.Node2) In all cases, a few methods will be added. I had no plans to override existing methods. My problem is that I want Application.Tree.parser to create Application.Node1 and Application.Node2 instances when parsing a file. From testing around with simpler cases, it seems as though unless I override Toolkit.Tree.parser in Application.Tree, the inherited Tree.parser method will create Toolkit.Node1 and Node2 objects, which isn't what I want. Toolkit.Tree.parser is my longest Tree method, and I definitely think it would be bad to just copy and paste the method def into Application.Tree so make the node = Node1(), etc. lines create an Application.Node1, etc. object. The best I have come up with is to replace the Toolkit.Tree.parser lines of the form: node = Node1(chunk_contents) with lines like node = self.get_Node1(chunk_contents) and then have *both* Toolkit.Tree and Application.Tree define methods: def get_Node1(self, chunk_contents): return Node1(chunk_contents) (like lines and methods for Node2) This works in my test case, but still involves Copy and Paste of the identical methods get_Node1 (and get_Node2) in both modules. Smelly. :-P So, how can I make the lines like node = Node1(chunk_contents) of the Toolkit.Tree.parser method say something that means "create a Node1 instance where Node1 is as defined in the module that defines the instantiated Tree class" so that an instance of Application.Tree creates instances of Application.Node1? Is that doable? Or, is some other design indicated? Thanks for making it to the end of the question! :-) Best to all, Brian vdB From maxnoel_fr at yahoo.fr Fri Mar 18 00:42:00 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Mar 18 00:42:04 2005 Subject: [Tutor] primes In-Reply-To: <423A0493.2000902@aon.at> References: <423A0493.2000902@aon.at> Message-ID: <825597b1393ca39389029f2c0929b307@yahoo.fr> On Mar 17, 2005, at 22:28, Gregor Lingl wrote: > Hi! > Who knows a more concise or equally concise but more efficient > expression, which returns the same result as > > [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] > > Gregor > > P.S.: ... or a more beautiful one ;-) Hmm... I don't have "beautiful" or "concise", but I can offer "fast". Here goes: #!/usr/bin/env python import math def isPrime(x, primeList): limit = math.sqrt(x) for i in primeList: if x % i == 0: return False if i >= limit: break return True def listPrimes(upperLimit): listOfPrimes = [] for i in range(2, upperLimit): if isPrime(i, listOfPrimes): listOfPrimes.append(i) return listOfPrimes if __name__ == '__main__': import sys num = int(sys.argv[-1]) print listPrimes(num) That's the fastest way I can think of -- but I can't prove it, as I don't know how to use the timeit module. -- 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?" From jfouhy at paradise.net.nz Fri Mar 18 00:48:24 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Fri Mar 18 00:49:05 2005 Subject: [Tutor] primes In-Reply-To: <423A0493.2000902@aon.at> References: <423A0493.2000902@aon.at> Message-ID: <1111103304.423a1748ea6ac@www.paradise.net.nz> Quoting Gregor Lingl <glingl@aon.at>: > [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] Heh. That's quite neat. I can only offer one suggestion --- if you replace range with xrange, you get a small speed improvement. eg: On my system, it took 415 seconds to generate a list of primes < 50,000 using range, but only 386 seconds if I use the same code, but with xrange instead. -- John. From dyoo at hkn.eecs.berkeley.edu Fri Mar 18 00:54:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 18 00:54:38 2005 Subject: [Tutor] primes In-Reply-To: <423A0493.2000902@aon.at> Message-ID: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> On Thu, 17 Mar 2005, Gregor Lingl wrote: > Hi! > Who knows a more concise or equally concise but more efficient > expression, which returns the same result as > > [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] Hi Gregor, Here is one that's traduced... er... adapted from material from the classic textbook "Structure and Interpretation of Computer Programs": ###### >>> from itertools import ifilter, count >>> >>> def notDivisibleBy(n): ... def f(x): ... return x % n != 0 ... return f ... >>> def sieve(iterable): ... nextPrime = iterable.next() ... yield nextPrime ... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable)) ... for prime in restOfPrimes: ... yield prime ... >>> >>> primes = sieve(count(2)) >>> primes.next() 2 >>> primes.next() 3 >>> primes.next() 5 >>> primes.next() 7 >>> primes.next() 11 >>> primes.next() 13 >>> primes.next() 17 >>> primes.next() 19 >>> primes.next() 23 ###### The neat thing about this code is that it produces an infinite iterator of prime numbers. The original code in Scheme is itself quite concise and quite nice. It is described here: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#call_footnote_Temp_455 Best of wishes to you! From andre.roberge at gmail.com Fri Mar 18 00:59:36 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri Mar 18 01:21:50 2005 Subject: [Tutor] Re: primes In-Reply-To: <1111103304.423a1748ea6ac@www.paradise.net.nz> References: <423A0493.2000902@aon.at> <1111103304.423a1748ea6ac@www.paradise.net.nz> Message-ID: <d1d5i6$rsv$1@sea.gmane.org> jfouhy@paradise.net.nz wrote: > Quoting Gregor Lingl <glingl@aon.at>: > > >>[x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] > > > Heh. That's quite neat. > > I can only offer one suggestion --- if you replace range with xrange, you get a > small speed improvement. > > eg: On my system, it took 415 seconds to generate a list of primes < 50,000 > using range, but only 386 seconds if I use the same code, but with xrange instead. > What about using something like range(2, math.sqrt(x)) instead? From maxnoel_fr at yahoo.fr Fri Mar 18 02:17:24 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Mar 18 02:17:34 2005 Subject: [Tutor] primes In-Reply-To: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> Message-ID: <e97d8fcf71e32d5254a1e54f0d55cd23@yahoo.fr> On Mar 17, 2005, at 23:54, Danny Yoo wrote: > Hi Gregor, > > Here is one that's traduced... er... adapted from material from the > classic textbook "Structure and Interpretation of Computer Programs": > <SNIP> Ooh, nifty. Okay, I decided to learn how to use the timeit module, so I used it to compare my algorithm (which, I just noticed, is a Python implementation of the Sieve of Erastothenes) to the one Gregor originally posted (albeit slightly optimized -- the only even prime number is 2, so there's no need to test them), and a further optimized version of it (stops looping at sqrt(x)). While I was at it, I optimized my algorithm further (in both memory usage and speed): it uses xrange and doesn't bother testing even numbers. Now, I did expect my algorithm to be the fastest. What I didn't expect, though, was for the differences to be *that* massive. Letting all three functions loose on finding all the prime numbers from 2 to 50000, I got the following results (test machine: G4 867 running Python 2.3 on OS X 10.3.8): listPrimes: 0.508284091949 seconds # my algorithm primeConciseOptimized: 2.18135714531 seconds # Gregor's, optimized primeConcise: 399.251116991 seconds # Gregor's, (partially optimized) As I suspected, when increasing the range, so do the differences. listPrimes finds all prime numbers from 2 to 200000 in 2.55 seconds, primeConciseOptimized in 15.81. At that point I had dropped primeConcise, as it being O(n^3) as far as I can tell, it would have taken ages to run. However, I thought the difference between listPrimes and primeConciseOptimized would increase faster than that. So primeConciseOptimized seems like the best compromise between speed and conciseness. Here's the (final?) version of the script I used: #!/usr/bin/env python import math import timeit def primeConcise(limit): return [2] + [x for x in xrange(3, limit, 2) if not [y for y in [2] + range(3,x,2) if x%y==0]] def primeConciseOptimized(limit): return [2] + [x for x in xrange(3, limit, 2) if not [y for y in [2] + range(3,int(math.sqrt(x)), 2) if x%y==0]] def isPrime(x, primeList): limit = int(math.sqrt(x)) for i in primeList: if x % i == 0: return False if i >= limit: break return True def listPrimes(upperLimit): listOfPrimes = [2] for i in xrange(3, upperLimit, 2): if isPrime(i, listOfPrimes): listOfPrimes.append(i) return listOfPrimes if __name__ == '__main__': t1 = timeit.Timer('listPrimes(50000)', 'from __main__ import listPrimes') t2 = timeit.Timer('primeConciseOptimized(50000)', 'from __main__ import primeConciseOptimized') t3 = timeit.Timer('primeConcise(50000)', 'from __main__ import primeConcise') print t1.timeit(1) print t2.timeit(1) print t3.timeit(1) -- 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?" From python at venix.com Fri Mar 18 02:36:49 2005 From: python at venix.com (Lloyd Kvam) Date: Fri Mar 18 02:37:00 2005 Subject: [Tutor] subclassing across multiple modules Message-ID: <1111109809.3512.233.camel@laptop.venix.com> You want a method in a base class to parse input and create instances of certain derived classes. Your sample code looks like: if some_condition_on_chunk_contents: node = Node1(chunk_contents) else: node = Node2(chunk_contents) I'd suggest changing the method to use a variable to determine the class. Following your pattern of coding: #Toolkit.py class Tree: node1 = Node1 node2 = Node2 ... class Node1(Node): ... #Application.py class Tree(Toolkit.Tree): node1 = Node1 node2 = Node2 ... class Nodes(Node,Toolkit.Node1): ... if some_condition_on_chunk_contents: node = self.node1(chunk_contents) else: node = self.node2(chunk_contents) This requires that the class constructors be similar enough so that they take the same parameters. It is also a manual effort to keep the node assignments in Tree in sync with the Node classes that you write. You also face a similar issue keeping Application.py and Toolkit.py in sync. -- Lloyd Kvam Venix Corp From kent37 at tds.net Fri Mar 18 02:44:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 18 02:44:14 2005 Subject: [Tutor] subclassing across multiple modules In-Reply-To: <423A13A2.8020405@po-box.mcgill.ca> References: <423A13A2.8020405@po-box.mcgill.ca> Message-ID: <423A3269.6020602@tds.net> Brian van den Broek wrote: > A schematic of what I have (with fake names for ease of example) is a > base module Toolkit.py and I want to write a module Application.py which > specializes the behaviour of the Toolkit.py classes. (I'm using > old-style classes, but don't feel committed to that choice.) > > Toolkit.py defines: > > class Tree > class Node > class Node1(Node) > class Node2(Node) > (other Node subclasses, too, but I'm simplifying.) > > The Tree class contains a parser method to parse a file. It reads the > file, breaking it into chunks, and for each chunk, does the following: > > if some_condition_on_chunk_contents: > node = Node1(chunk_contents) > else: > node = Node2(chunk_contents) > > self.nodes.append(node) > > > Application.py will define > > class Tree(Toolkit.Tree) > class Node(Toolkit.Node) > class Node1(Node, Toolkit.Node1) > class Node2(Node, Toolkit.Node2) You're asking for trouble using the same name. Do something like class MyTree(Toolkit.Tree) class MyNode(Toolkit.Node) class MyNode1(MyNode, Toolkit.Node1) class MyNode2(MyNode, Toolkit.Node2) The multiple inheritance from MyNode and Toolkit.NodeX is a smell. I guess you do this because you want to override methods of Toolkit.Node as well as Toolkit.NodeX, or add methods to both MyNode1 and MyNode2? I would look for another way to do this, maybe using some kind of helper class to hold some common functions? > In all cases, a few methods will be added. I had no plans to override > existing methods. > > My problem is that I want Application.Tree.parser to create > Application.Node1 and Application.Node2 instances when parsing a file. > From testing around with simpler cases, it seems as though unless I > override Toolkit.Tree.parser in Application.Tree, the inherited > Tree.parser method will create Toolkit.Node1 and Node2 objects, which > isn't what I want. > > Toolkit.Tree.parser is my longest Tree method, and I definitely think it > would be bad to just copy and paste the method def into Application.Tree > so make the node = Node1(), etc. lines create an Application.Node1, etc. > object. Right, you don't want to do this. > The best I have come up with is to replace the Toolkit.Tree.parser lines > of the form: > node = Node1(chunk_contents) > with lines like > node = self.get_Node1(chunk_contents) > > and then have *both* Toolkit.Tree and Application.Tree define methods: > > def get_Node1(self, chunk_contents): > return Node1(chunk_contents) > > (like lines and methods for Node2) > > This works in my test case, but still involves Copy and Paste of the > identical methods get_Node1 (and get_Node2) in both modules. Smelly. :-P This is actually good design. It is a simple example of the Template Method pattern. Use Template Method when you have a function that defines the outline of an algorithm, but you need to specialize some part of the algorithm. You wrap the function in a class (you already have this since it is a method) and call helper methods for the parts you want to specialize. Then subclasses override the helper methods. The methods in MyTree will be different from the ones in Toolkit.Tree, they will look like def get_Node1(self, chunk_contents): return MyNode1(chunk_contents) A couple of alternatives: You could actually pass the class constructors directly to Tree.parser(). It would look like this: def parser(self, makeNode1, makeNode2): # makeNode1 & 2 are callables that return nodes # ... if some_condition_on_chunk_contents: node = makeNode1(chunk_contents) else: node = makeNode2(chunk_contents) Then at the point of call you have tree.parser(MyNode1, MyNode2) # constructors are callable There are several variations on this depending on the details of your requirements. You could pass makeNode1 and makeNode2 to the Tree constructor and save them as instance variables. You could have a separate class with makeNode1() and makeNode2() methods and pass an instance of that to parse() or Tree.__init__()... Kent From kent37 at tds.net Fri Mar 18 03:15:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 18 03:15:53 2005 Subject: [Tutor] primes In-Reply-To: <e97d8fcf71e32d5254a1e54f0d55cd23@yahoo.fr> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> <e97d8fcf71e32d5254a1e54f0d55cd23@yahoo.fr> Message-ID: <423A39D4.8070904@tds.net> Max Noel wrote: > #!/usr/bin/env python > > import math > import timeit > > def primeConcise(limit): > return [2] + [x for x in xrange(3, limit, 2) if not [y for y in [2] > + range(3,x,2) if x%y==0]] > > > def primeConciseOptimized(limit): > return [2] + [x for x in xrange(3, limit, 2) if not [y for y in [2] > + range(3,int(math.sqrt(x)), 2) if x%y==0]] Hmm, I didn't know that 9 and 15 were prime... When I'm doing timings like this I usually check the output. You can write a *very* fast algorithm if correctness does not count :-) Here is a version that gives correct results at least up to limit=50: def primeConciseOptimized(limit): return [2] + [x for x in xrange(3, limit, 2) if not [y for y in [2] + range(3,int(math.sqrt(x))+1, 2) if x%y==0]] One reason your listPrimes() function is faster is that it short-circuits the test - as soon as a divisor is found for a candidate, no further testing is done. primeConciseOptimized() always tests all the candidate divisors. In the spirit of useless optimizations of bad algorithms ;) I used itertools to make a short-circuiting version of primeConciseOptimized(): import itertools def no(seq, pred=bool): '''Returns True if pred(x) is False for every element in the iterable From the itertools recipes. ''' for elem in itertools.ifilter(pred, seq): return False return True def primeConciseOptimized2(limit): return [2] + [x for x in xrange(3, limit, 2) if no(xrange(3,int(math.sqrt(x))+1, 2), lambda y: x%y==0)] Note I don't bother testing for divisibility by 2 since the candidates are all odd. This allows using xrange() instead of range() for a significant improvement. My times: listPrimes 0.143752069048 primeConciseOptimized 0.586845814203 primeConciseOptimized2 0.391731351331 Kent > > def isPrime(x, primeList): > limit = int(math.sqrt(x)) > for i in primeList: > if x % i == 0: > return False > if i >= limit: > break > return True > > def listPrimes(upperLimit): > listOfPrimes = [2] > for i in xrange(3, upperLimit, 2): > if isPrime(i, listOfPrimes): > listOfPrimes.append(i) > return listOfPrimes > > > if __name__ == '__main__': > t1 = timeit.Timer('listPrimes(50000)', 'from __main__ import > listPrimes') > t2 = timeit.Timer('primeConciseOptimized(50000)', 'from __main__ > import primeConciseOptimized') > t3 = timeit.Timer('primeConcise(50000)', 'from __main__ import > primeConcise') > print t1.timeit(1) > print t2.timeit(1) > print t3.timeit(1) > > > > -- 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 > From bvande at po-box.mcgill.ca Fri Mar 18 05:40:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Mar 18 06:43:18 2005 Subject: [Tutor] Re: subclassing across multiple modules In-Reply-To: <1111109809.3512.233.camel@laptop.venix.com> References: <1111109809.3512.233.camel@laptop.venix.com> Message-ID: <423A5BB2.6080705@po-box.mcgill.ca> Hi all, Thanks for the reply, Lloyd. Lloyd Kvam said unto the world upon 2005-03-17 20:36: > You want a method in a base class to parse input and create instances of > certain derived classes. Not quite. One class (Tree) parses a file and creates instances of Node1 and Node2 (derived from Node). None of the Node classes inherit Tree. But I don't think that difference matters for what you suggested. :-) > Your sample code looks like: > if some_condition_on_chunk_contents: > node = Node1(chunk_contents) > else: > node = Node2(chunk_contents) > > I'd suggest changing the method to use a variable to determine the > class. Following your pattern of coding: > #Toolkit.py > class Tree: > node1 = Node1 > node2 = Node2 > ... > class Node1(Node): > ... > > #Application.py > class Tree(Toolkit.Tree): <SNIP -- same as in Tree immediately above> > if some_condition_on_chunk_contents: > node = self.node1(chunk_contents) > else: > node = self.node2(chunk_contents) > > This requires that the class constructors be similar enough so that they > take the same parameters. Happily, the interfaces are identical. :-) (I need different Node classes as the chunk_contents are in different formats, the tasks are the same, modulo differences due to format.) > It is also a manual effort to keep the node > assignments in Tree in sync with the Node classes that you write. You > also face a similar issue keeping Application.py and Toolkit.py in sync. Hmm. I think I do see some appeal to the route you suggest, but I'm feeling unhappy about the need to keep multiple things in sync. I think I will play with this and other alternatives and see what feels right. Thanks so much for the input :-) Best to all, Brian vdB From bvande at po-box.mcgill.ca Fri Mar 18 06:40:03 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Mar 18 06:43:36 2005 Subject: [Tutor] subclassing across multiple modules In-Reply-To: <423A3269.6020602@tds.net> References: <423A13A2.8020405@po-box.mcgill.ca> <423A3269.6020602@tds.net> Message-ID: <423A69B3.6000002@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-03-17 20:44: > Brian van den Broek wrote: > >> A schematic of what I have (with fake names for ease of example) is a >> base module Toolkit.py and I want to write a module Application.py >> which specializes the behaviour of the Toolkit.py classes. (I'm using >> old-style classes, but don't feel committed to that choice.) >> >> Toolkit.py defines: >> >> class Tree >> class Node >> class Node1(Node) >> class Node2(Node) >> (other Node subclasses, too, but I'm simplifying.) >> >> The Tree class contains a parser method to parse a file. It reads the >> file, breaking it into chunks, and for each chunk, does the following: >> >> if some_condition_on_chunk_contents: >> node = Node1(chunk_contents) >> else: >> node = Node2(chunk_contents) >> >> self.nodes.append(node) >> >> >> Application.py will define >> >> class Tree(Toolkit.Tree) >> class Node(Toolkit.Node) >> class Node1(Node, Toolkit.Node1) >> class Node2(Node, Toolkit.Node2) > > > You're asking for trouble using the same name. Do something like > class MyTree(Toolkit.Tree) > class MyNode(Toolkit.Node) > class MyNode1(MyNode, Toolkit.Node1) > class MyNode2(MyNode, Toolkit.Node2) Hi all, thanks for the reply, Kent. I spent a few minutes trying to recall why I had used all the same names in the first place. Then it hit me: it was because I hadn't worked out that the issue I posted about today was there -- I'd naively thought that if I used the same names, I would seamlessly get that a method of an Application.Tree instance that was inherited from Toolkit.Tree would `point' to Application.Node, etc. Oh, well. :-) > The multiple inheritance from MyNode and Toolkit.NodeX is a smell. I > guess you do this because you want to override methods of Toolkit.Node > as well as Toolkit.NodeX, or add methods to both MyNode1 and MyNode2? I > would look for another way to do this, maybe using some kind of helper > class to hold some common functions? The adding methods rationale. I never instantiate Node, instead I use it for behaviour common to Node1 and Node2. Toolkit.py gives specialized methods to both Node1 and Node2. I need MyNode1 and MyNode2 (the Application.py versions) to have all the powers of the Toolkit.Node1 and Node2 classes, plus some new powers in common, and some new powers defined separately. That is the sort of thing I had understood multiple inheritance to be for -- but my understanding is about as shaky as an addict in withdrawal :-) Are you suggesting the multiple inheritance is always a smell? I'll google, but my only grasp of the meaning of "helper class" is what comes from intuition. >> In all cases, a few methods will be added. I had no plans to override >> existing methods. >> >> My problem is that I want Application.Tree.parser to create >> Application.Node1 and Application.Node2 instances when parsing a file. >> From testing around with simpler cases, it seems as though unless I >> override Toolkit.Tree.parser in Application.Tree, the inherited >> Tree.parser method will create Toolkit.Node1 and Node2 objects, which >> isn't what I want. >> >> Toolkit.Tree.parser is my longest Tree method, and I definitely think >> it would be bad to just copy and paste the method def into >> Application.Tree so make the node = Node1(), etc. lines create an >> Application.Node1, etc. object. > > > Right, you don't want to do this. > >> The best I have come up with is to replace the Toolkit.Tree.parser >> lines of the form: >> node = Node1(chunk_contents) >> with lines like >> node = self.get_Node1(chunk_contents) >> >> and then have *both* Toolkit.Tree and Application.Tree define methods: >> >> def get_Node1(self, chunk_contents): >> return Node1(chunk_contents) >> >> (like lines and methods for Node2) >> >> This works in my test case, but still involves Copy and Paste of the >> identical methods get_Node1 (and get_Node2) in both modules. Smelly. :-P > > > This is actually good design. It is a simple example of the Template > Method pattern. Use Template Method when you have a function that > defines the outline of an algorithm, but you need to specialize some > part of the algorithm. You wrap the function in a class (you already > have this since it is a method) and call helper methods for the parts > you want to specialize. Then subclasses override the helper methods. > > The methods in MyTree will be different from the ones in Toolkit.Tree, > they will look like > def get_Node1(self, chunk_contents): > return MyNode1(chunk_contents) Bing! Since I'd had the homonymously named class in the first place, I thought this approach would be a smell. (Don't repeat yourself, because then you keep saying the same thing, and repetition is redundant in that it conveys the same information more than once and is pleonastic, as well as overly verbose. ;-) ) But the smell was elsewhere :-) > A couple of alternatives: > > You could actually pass the class constructors directly to > Tree.parser(). It would look like this: > > def parser(self, makeNode1, makeNode2): # makeNode1 & 2 are callables > that return nodes > # ... > if some_condition_on_chunk_contents: > node = makeNode1(chunk_contents) > else: > node = makeNode2(chunk_contents) > > Then at the point of call you have > tree.parser(MyNode1, MyNode2) # constructors are callable > > There are several variations on this depending on the details of your > requirements. You could pass makeNode1 and makeNode2 to the Tree > constructor and save them as instance variables. You could have a > separate class with makeNode1() and makeNode2() methods and pass an > instance of that to parse() or Tree.__init__()... That gives me much to play with. Thanks :-) Best to all, Brian vdB From smichr at hotmail.com Fri Mar 18 06:48:44 2005 From: smichr at hotmail.com (C Smith) Date: Fri Mar 18 06:49:51 2005 Subject: [Tutor] primes In-Reply-To: <20050317234909.CDCEA1E4010@bag.python.org> Message-ID: <BAY101-DAV12D43E184678288525D1F0C14A0@phx.gbl> On Thursday, Mar 17, 2005, at 17:49 America/Chicago, tutor-request@python.org wrote: > On my system, it took 415 seconds to generate a list of primes < 50,000 > using range, but only 386 seconds if I use the same code, but with > xrange instead. > > If you only calculate y up to sqrt(x) you will see a dramatic time reduction: ### import math big=50000 [x for x in xrange(2,big) if not [y for y in range(2,int(math.sqrt(x)+1)) if x%y==0]] ### /c From shaleh at speakeasy.net Fri Mar 18 08:02:41 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Mar 18 08:04:27 2005 Subject: [Tutor] primes In-Reply-To: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> Message-ID: <423A7D11.4010202@speakeasy.net> Danny Yoo wrote: > Here is one that's traduced... er... adapted from material from the > classic textbook "Structure and Interpretation of Computer Programs": > > ###### > >>>>from itertools import ifilter, count >>>> >>>>def notDivisibleBy(n): > > ... def f(x): > ... return x % n != 0 > ... return f > ... > >>>>def sieve(iterable): > > ... nextPrime = iterable.next() > ... yield nextPrime > ... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable)) > ... for prime in restOfPrimes: > ... yield prime > ... > >>>>primes = sieve(count(2)) >>>>primes.next() > which is cool, until you try to use it (-: It dies at 999 primes due to an overloaded stack. Bummer. It is such a nifty implementation. I modified this version to follow it better. from itertools import ifilter, count def notDivisibleBy(n): def f(x): return x % n != 0 return f def sieve(iterable): nextPrime = iterable.next() print 'x', nextPrime yield nextPrime restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable)) for prime in restOfPrimes: print 'p', prime yield prime primes = sieve(count(2)) current = primes.next() count = 1 while current <= 20: print 'Prime:', current current = primes.next() count += 1 The output is (note this is each prime < 20): x 2 Prime: 2 x 3 p 3 Prime: 3 x 5 p 5 p 5 Prime: 5 x 7 p 7 p 7 p 7 Prime: 7 x 11 p 11 p 11 p 11 p 11 Prime: 11 x 13 p 13 p 13 p 13 p 13 p 13 Prime: 13 x 17 p 17 p 17 p 17 p 17 p 17 p 17 Prime: 17 x 19 p 19 p 19 p 19 p 19 p 19 p 19 p 19 Prime: 19 x 23 p 23 p 23 p 23 p 23 p 23 p 23 p 23 p 23 Not exactly efficient. From maxnoel_fr at yahoo.fr Fri Mar 18 11:23:38 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Mar 18 11:23:41 2005 Subject: [Tutor] primes In-Reply-To: <423A39D4.8070904@tds.net> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> <e97d8fcf71e32d5254a1e54f0d55cd23@yahoo.fr> <423A39D4.8070904@tds.net> Message-ID: <6f2ea25fb0d3d40609eea9bc70bebdb3@yahoo.fr> On Mar 18, 2005, at 02:15, Kent Johnson wrote: > Max Noel wrote: >> #!/usr/bin/env python >> import math >> import timeit >> def primeConcise(limit): >> return [2] + [x for x in xrange(3, limit, 2) if not [y for y in >> [2] + range(3,x,2) if x%y==0]] >> def primeConciseOptimized(limit): >> return [2] + [x for x in xrange(3, limit, 2) if not [y for y in >> [2] + range(3,int(math.sqrt(x)), 2) if x%y==0]] > > Hmm, I didn't know that 9 and 15 were prime... > When I'm doing timings like this I usually check the output. You can > write a *very* fast algorithm if correctness does not count :-) Damn. Got bitten again by the fact that range/xrange return start <= n < end and not start <= n <= end. Python lacks Ruby's range objects ( (start..end) or (start...end) depending on what you want). In the (pythonized) words of E. Dijkstra, "if it doesn't have to work, pass is a good solution". I blame sleep deprivation. -.- > Note I don't bother testing for divisibility by 2 since the candidates > are all odd. This allows using xrange() instead of range() for a > significant improvement. > > My times: > listPrimes 0.143752069048 > primeConciseOptimized 0.586845814203 > primeConciseOptimized2 0.391731351331 > > Kent Mmh... Good one. Didn't think of it. What can I say... I love stupid optimization challenges. Now I wonder if someone is going to dare come up and kick our asses with a version that does this with a C module... :D -- 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?" From pierre.barbier at cirad.fr Fri Mar 18 12:08:14 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri Mar 18 12:06:49 2005 Subject: [Tutor] primes In-Reply-To: <423A0493.2000902@aon.at> References: <423A0493.2000902@aon.at> Message-ID: <423AB69E.2020201@cirad.fr> Gregor Lingl a ?crit : > Hi! > Who knows a more concise or equally concise but more efficient > expression, which returns the same result as > > [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] > > Gregor > > P.S.: ... or a more beautiful one ;-) > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > The fastest know way for your problem is the Eratosten sieve ... Here's an implementation : from sets import Set from math import sqrt def sieve( max ): max_val = int( sqrt( max ) ) s = Set(xrange( 4, max, 2 )) for i in xrange( 3, max_val, 2 ): s.update( xrange( 2*i, max, i ) ) return [ i for i in xrange( 2, max ) if i not in s ] I compared with the implementations of Gregor (optimized) and Max and here is the result : listPrimes(100000) = 0.637619972229 (Max implementation) primeConciseOptimized(100000) = 2.9141831398 (Gregor optimized) sieve(100000) = 0.49525809288 (Eratosten sieve) You'll just notice that Eratosten sieve is O(n) space consumption when others are less (I don't remember the density of prime numbers :o) ) were n is the maximum number you're looking for. Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From meesters at uni-mainz.de Fri Mar 18 13:04:40 2005 From: meesters at uni-mainz.de (Christian Meesters) Date: Fri Mar 18 13:04:43 2005 Subject: [Tutor] how to initialize a class with arbitrary argument list from a file? Message-ID: <cd83a8f46c572fb601d87396933bdd76@uni-mainz.de> Hi How can I initialize a class like this from a file: class Some: def __init__(self,data,axis,**kwargs): pass 'data' and 'axis' should be lists of floats. Meta data can be passed to kwargs like 'name="name",date="2/3/05",...'. Right now the return value of my function reading the file looks like this: dummy = fromFile(path) print dummy [[[datalist],[axislist],'name="name"','date="2/3/05"',...],...] And, of course, initializing Some with dummy[0] like: Some(dummy[0]) will throw an exception; a TypeError, since the argument list is not of the right length and of the wrong type. Well, I've tried a few things to solve this problem, but didn't succeed: How do I have to alter FromFile() so, that I can use dummy to initialize Some? Oh, and I should mention that **kwargs can be of arbitrary length: __init__ has default values for every keyword not given. And for the record: I'm still stuck with version 2.3 until I'll upgrade to Tiger (on OSX). I'm totally lost. It would be great if you could help me out here. Thanks a lot in advance, Christian From kent37 at tds.net Fri Mar 18 13:35:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 18 13:35:18 2005 Subject: [Tutor] subclassing across multiple modules In-Reply-To: <423A69B3.6000002@po-box.mcgill.ca> References: <423A13A2.8020405@po-box.mcgill.ca> <423A3269.6020602@tds.net> <423A69B3.6000002@po-box.mcgill.ca> Message-ID: <423ACB01.7040402@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 2005-03-17 20:44: >> The multiple inheritance from MyNode and Toolkit.NodeX is a smell. I >> guess you do this because you want to override methods of Toolkit.Node >> as well as Toolkit.NodeX, or add methods to both MyNode1 and MyNode2? >> I would look for another way to do this, maybe using some kind of >> helper class to hold some common functions? > > > > The adding methods rationale. I never instantiate Node, instead I use it > for behaviour common to Node1 and Node2. Toolkit.py gives specialized > methods to both Node1 and Node2. I need MyNode1 and MyNode2 (the > Application.py versions) to have all the powers of the Toolkit.Node1 and > Node2 classes, plus some new powers in common, and some new powers > defined separately. That is the sort of thing I had understood multiple > inheritance to be for -- but my understanding is about as shaky as an > addict in withdrawal :-) > > Are you suggesting the multiple inheritance is always a smell? No. Some people would agree with that - e.g. the creators of Java - but I have seen many times where MI is useful. Usually it is to combine a primary base class with a mixin - a class that adds functionality orthogonal to that of the base class, or that modifies a carefully chosen set of base class methods. http://c2.com/cgi/wiki?MultipleInheritanceIsNotEvil http://c2.com/cgi/wiki?MixIn For example in a GUI toolkit you might have an Observable add-in that gives a class means to remember and broadcast to listeners. In the Python library there are SocketServer mixins that create a threaded server. BUT there are some clear gotchas to MI. They mostly arise when you inherit from classes that themselves have a common base class. The "diamond" pattern is the usual example: class A: .. class B(A): .. class C(A): .. class D(B, C): .. Now you can have all kinds of fun (i.e. subtle bugs and confusion) if A, B, C and D have methods in common and if they want to call the methods of their base classes. One of the changes is new-style classes (the addition of super() and a change to the "method resolution order") was made to address some deficiencies in how old-style classes handle this situation. So, calling this a code smell is probably not the right term. It's more like a red warning light and klaxon :-) You just don't want to do this without understanding the issues. See http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000330000000000000000 and PEP 253 for details or google "diamond multiple inheritance" > I'll google, but my only grasp of the meaning of "helper class" is what > comes from intuition. For example, instead of subclassing Toolkit.Node, could you define the extra methods in another class. Then your NodeX subclasses can inherit from Toolkit.NodeX and NodeHelper. e.g. class MyNodeHelper: def doSomethingSpecial(self): # does something with a Toolkit.Node class MyNode1(Toolkit.Node1, MyNodeHelper): .. This is an example of a mixin class. Kent From kent37 at tds.net Fri Mar 18 13:43:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 18 13:43:06 2005 Subject: [Tutor] how to initialize a class with arbitrary argument list from a file? In-Reply-To: <cd83a8f46c572fb601d87396933bdd76@uni-mainz.de> References: <cd83a8f46c572fb601d87396933bdd76@uni-mainz.de> Message-ID: <423ACCD8.90104@tds.net> Christian Meesters wrote: > Hi > > How can I initialize a class like this from a file: > class Some: > def __init__(self,data,axis,**kwargs): > pass > > 'data' and 'axis' should be lists of floats. Meta data can be passed to > kwargs like 'name="name",date="2/3/05",...'. > Right now the return value of my function reading the file looks like this: > dummy = fromFile(path) > print dummy > [[[datalist],[axislist],'name="name"','date="2/3/05"',...],...] Something like this (untested): allSome = [] for args in dummy: # args looks like [[datalist],[axislist],'name="name"','date="2/3/05"',...] datalist = args[0] axislist = args[1] kwargs = {} for kv in args[2:]: # kv looks like 'name="name"' k, v = kv.split('=') kwargs[k] = v.strip('"') # You may need more sophisticated processing of v # and more error detection, depending on the details of the data... some = Some(datalist, axislist, **kwargs) allSome.append(some) Kent From bvande at po-box.mcgill.ca Fri Mar 18 16:28:55 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Mar 18 16:40:27 2005 Subject: [Tutor] subclassing across multiple modules In-Reply-To: <423ACB01.7040402@tds.net> References: <423A13A2.8020405@po-box.mcgill.ca> <423A3269.6020602@tds.net> <423A69B3.6000002@po-box.mcgill.ca> <423ACB01.7040402@tds.net> Message-ID: <423AF3B7.7030506@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-03-18 07:35: > Brian van den Broek wrote: > >> Kent Johnson said unto the world upon 2005-03-17 20:44: > > >>> The multiple inheritance from MyNode and Toolkit.NodeX is a smell. I >>> guess you do this because you want to override methods of >>> Toolkit.Node as well as Toolkit.NodeX, or add methods to both MyNode1 >>> and MyNode2? I would look for another way to do this, maybe using >>> some kind of helper class to hold some common functions? <SNIP Brian's original rational for using multiple inheritance> >> Are you suggesting the multiple inheritance is always a smell? > > > No. Some people would agree with that - e.g. the creators of Java - but > I have seen many times where > MI is useful. Usually it is to combine a primary base class with a mixin > - a class that adds > functionality orthogonal to that of the base class, or that modifies a > carefully chosen set of base > class methods. > http://c2.com/cgi/wiki?MultipleInheritanceIsNotEvil > http://c2.com/cgi/wiki?MixIn <SNIP GUI example> > BUT there are some clear gotchas to MI. They mostly arise when you > inherit from classes that > themselves have a common base class. The "diamond" pattern is the usual > example: > > class A: > .. > > class B(A): > .. > > class C(A): > .. > > class D(B, C): > .. > > Now you can have all kinds of fun (i.e. subtle bugs and confusion) if A, > B, C and D have methods in > common and if they want to call the methods of their base classes. One > of the changes is new-style > classes (the addition of super() and a change to the "method resolution > order") was made to address > some deficiencies in how old-style classes handle this situation. > > So, calling this a code smell is probably not the right term. It's more > like a red warning light and > klaxon :-) You just don't want to do this without understanding the issues. > > See > http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION000330000000000000000 > and PEP > 253 for details or google "diamond multiple inheritance" Well, if I let failure of understanding stop me, I'd still be writing nothing but DOS batch files :-) But, point taken. Thanks for the links. I'd read about the diamond pattern in the past, but at a time before I'd ever written a class to call my own. Pushed by this discussion, and with a problem context to read the texts through, I re-read the dead-tree sources I have at hand. For anyone following along, the relevant section of the Nutshell (p 88ff) makes a good deal of sense of this. Learning Python 370ff is also on point. >> I'll google, but my only grasp of the meaning of "helper class" is >> what comes from intuition. > > > For example, instead of subclassing Toolkit.Node, could you define the > extra methods in another > class. Then your NodeX subclasses can inherit from Toolkit.NodeX and > NodeHelper. e.g. > > class MyNodeHelper: > def doSomethingSpecial(self): > # does something with a Toolkit.Node > > class MyNode1(Toolkit.Node1, MyNodeHelper): > .. > > This is an example of a mixin class. OK, that makes sense. The effect, as I understand it, is to put the new behaviour common to NodeX classes in a separate bundle for safety, thereby making the MRO more transparent. And, as I learned when I used to work road construction, safety first! :-) Thanks for the help, Kent. Best to all, Brian vdB From michael.hall at critterpixstudios.com Fri Mar 18 19:35:57 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 18 19:36:12 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <20050318172735.GA71118@tektite.k12usa.internal> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <20050317040029.GE35825@tektite.k12usa.internal> <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> <20050318172735.GA71118@tektite.k12usa.internal> Message-ID: <a6718887b717016b7c7fa85f937d01ee@critterpixstudios.com> On Mar 18, 2005, at 9:27 AM, Christopher Weimann wrote: > On 03/17/2005-10:15AM, Mike Hall wrote: >> >> <applause> Very nice sir. I'm interested in what you're doing here >> with >> the caret metacharacter. For one thing, why enclose it and the >> whitespace flag within a character class? > > A caret as the first charachter in a class is a negation. > So this [^\s]+ means match one or more of any char that > isn't whitespace. Ok, so the context of metas change within a class. That makes sense, but I'm unclear on the discrepancy below. >> Does this not traditionally >> mean you want to strip a metacharacter of it's special meaning? >> > > That would be \ Here's where I'm confused. From the Python docs: Special characters are not active inside sets. For example, [akm$] will match any of the characters "a", "k", "m", or "$" -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1669 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050318/3bd41298/attachment.bin From csw at k12hq.com Fri Mar 18 22:02:08 2005 From: csw at k12hq.com (Christopher Weimann) Date: Fri Mar 18 22:02:57 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <a6718887b717016b7c7fa85f937d01ee@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <20050317040029.GE35825@tektite.k12usa.internal> <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> <20050318172735.GA71118@tektite.k12usa.internal> <a6718887b717016b7c7fa85f937d01ee@critterpixstudios.com> Message-ID: <20050318210207.GB71118@tektite.k12usa.internal> On 03/18/2005-10:35AM, Mike Hall wrote: > > > > A caret as the first charachter in a class is a negation. > > So this [^\s]+ means match one or more of any char that > > isn't whitespace. > > > > Ok, so the context of metas change within a class. That makes sense, > but I'm unclear on the discrepancy below. > The ^ means begining of line EXCEPT inside a charachter class. There it means NOT for the entire class and it only means that if it is the very first charachter. I suppose you could consider that the there are two separate types of char classes. One is started with [ and the other is started with [^. > > > > > That would be \ > > > > Here's where I'm confused. From the Python docs: > > Special characters are not active inside sets. For example, [akm$] will > match any of the characters "a", "k", "m", or "$" > And the next paragraphs says... You can match the characters not within a range by complementing the set. This is indicated by including a "^" as the first character of the class; "^" elsewhere will simply match the "^" character. For example, [^5] will match any character except "5". From michael.hall at critterpixstudios.com Fri Mar 18 23:20:38 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 18 23:20:55 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <20050318210207.GB71118@tektite.k12usa.internal> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <20050317040029.GE35825@tektite.k12usa.internal> <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> <20050318172735.GA71118@tektite.k12usa.internal> <a6718887b717016b7c7fa85f937d01ee@critterpixstudios.com> <20050318210207.GB71118@tektite.k12usa.internal> Message-ID: <f37783b3d0b2f982d737296a9a3a03d5@critterpixstudios.com> On Mar 18, 2005, at 1:02 PM, Christopher Weimann wrote: > On 03/18/2005-10:35AM, Mike Hall wrote: >>> >>> A caret as the first charachter in a class is a negation. >>> So this [^\s]+ means match one or more of any char that >>> isn't whitespace. >>> >> >> Ok, so the context of metas change within a class. That makes sense, >> but I'm unclear on the discrepancy below. >> > > The ^ means begining of line EXCEPT inside a charachter class. There it > means NOT for the entire class and it only means that if it is the very > first charachter. I suppose you could consider that the there are two > separate types of char classes. One is started with [ and the other is > started with [^. > Got it, thanks. >> >>> >>> That would be \ >>> >> >> Here's where I'm confused. From the Python docs: >> >> Special characters are not active inside sets. For example, [akm$] >> will >> match any of the characters "a", "k", "m", or "$" >> > > And the next paragraphs says... > > You can match the characters not within a range by complementing the > set. This is indicated by including a "^" as the first character of > the > class; "^" elsewhere will simply match the "^" character. For > example, > [^5] will match any character except "5". > > The sad thing is I have read that paragraph before (but obviously hadn't absorbed the significance). I'm new to this, it'll sink in. Thanks. From glingl at aon.at Sat Mar 19 01:04:57 2005 From: glingl at aon.at (Gregor Lingl) Date: Sat Mar 19 01:02:17 2005 Subject: [Tutor] primes (generator) In-Reply-To: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> Message-ID: <423B6CA9.2050509@aon.at> Hi all of you! Many thanks for your remarks, ideas and experiments. When I posted my input yesterday: [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] my intention was indeed to find a "shortest" a program, disregarding efficiency. Thus range instead of xrange etc. (About one year ago I was involved in a "coding contest" at Linux-Tag in Karlsruhe, where the goal was to achive a certain output with a shortest program ;-) Strange. I used Python, but I didn't win :-( ) Clearly there are several criteria concerning the quality of programs as e. g. conciseness, clarity, efficiency, beauty(!) etc. which may not be achieved optimally all together ... I definitely intend to sum up your contibutions (for me) later, but for now (because of lack of time) I'll only present one more idea, induced by Danny's (unfortunately buggy - because of recursion overflow) contribution: Thought it would be nice to use Python's new generator-expressions instead of itertool module. First idea: ################################################################## # infinite prime generator # induced by ideas of Danny Yoo, # which themselves were induced by material of SICP import math def prime(n): return [x for x in range(2,1+int(math.sqrt(n))) if n%x==0]==[] def infrange(n): while True: yield n n+=1 primes = (p for p in infrange(2) if prime(p)) ############### The generator primes works like this: >>> primes.next() 2 >>> primes.next() 3 >>> primes.next() 5 >>> [primes.next() for i in range(10)] [7, 11, 13, 17, 19, 23, 29, 31, 37, 41] >>> [primes.next() for i in range(100)] [43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617] >>> >>> ### You may also use it this way: >>> for p in primes: if p > 1000: break print p, 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 With a fresh generator [primes.next() for p in xrange(10000)] produces (on my machine) a list of the first 10000 primes (upto 104729) within 4.68 secs. Now for a bit of optimization: instead of building a list of all divisors use a loop and get out as soon as possible: So I replace prime by: def prime(n): for d in range(2,1+int(math.sqrt(n))): if n%d == 0: return False return True This makes the generator nearly 4 times as fast. I get my list in 1.33 secs. Lets optimize a bit more: test only 2 and odd numbers: def infrange(n): yield 2 n=3 while True: yield n n+=2 and do a similar thing for searching for divisors: def prime(n): if n==2: return True for d in [2]+ range(3,1+int(math.sqrt(n)),2): if n%d == 0: return False return True Now the first 10000 primes get computed in 0.67 secs. Again double speed. Together seven times as fast as first version. But IMO at the cost of clarity and conciseness. Maybe you have amendments (of course a matter of taste) to this code. I'd be interested in them .. Maybe sombody likes to compare these algorithms to the ones mentioned before in this thread. I would be interested in the results. Regards, Gregor Danny Yoo schrieb: > > On Thu, 17 Mar 2005, Gregor Lingl wrote: > > >>Hi! >>Who knows a more concise or equally concise but more efficient >>expression, which returns the same result as ... > ###### > >>>>from itertools import ifilter, count >>>> >>>>def notDivisibleBy(n): > > ... def f(x): > ... return x % n != 0 > ... return f > ... > >>>>def sieve(iterable): > > ... nextPrime = iterable.next() > ... yield nextPrime > ... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable)) > ... for prime in restOfPrimes: > ... yield prime > ... > >>>>primes = sieve(count(2)) >>>>primes.next() > > 2 > >>>>primes.next() ... >>>>primes.next() > > 23 > ###### > > The neat thing about this code is that it produces an infinite iterator of > prime numbers. The original code in Scheme is itself quite concise and > quite nice. It is described here: > > http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#call_footnote_Temp_455 > > > Best of wishes to you! > > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From glingl at aon.at Sat Mar 19 01:57:25 2005 From: glingl at aon.at (Gregor Lingl) Date: Sat Mar 19 01:54:45 2005 Subject: [Tutor] primes (Cautious remark on Python and Scheme) In-Reply-To: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> Message-ID: <423B78F5.4040202@aon.at> Hi Danny! Preliminary remark: I know that "beautiful" and "beauty" are concepts very seldom applied to computer programs or programming languages. I suppose mainly because they are to a large extent a matter of taste ... Nevertheless: regardeless of the fact that I'm not a very skilled scheme-programmer, for me Scheme is the most beautiful programming language I know, mainly because of the clear and simple concepts which are purely realized. (I do *not* want to discuss here questions like functional versus object-oriented languages etc...) However - Python - for me - is a programming language for the "pragmatic lover". Do you consider this expression as self explanatory? Lover -- because it makes so much fun to use it. Pragmatic -- because it is a language for the real world ;-) im*h*o the primes - examples we are just discussing shows, that going *the Python way* may well be more successful or rewarding than trying to translate, traduce, ...er .. adapt Scheme-concepts quasi trying to show that Python is at least as good as Scheme. This is not the question. (I suppose that this also was not your goal?) A deeper question perhaps would be to what degree the content of cs texts depends on the choice of the mainly used language therein. On the contrary - we may learn from this example that Python is a *very* good language in its own right - with carefully chosen concepts and syntax and a very slow, serious and publicly controlled development process resulting in a more and more easily and efficiently usable language. Finally I'd like to stress that your contribution for me was very valuable and constructive - as are most of your innumerable contributions to the discussions on this list. Thanks an regards, Gregor post scriptum: as always when writing not only about technical facts but about opinions and values in English, I'm a bit axious if I was able to express correctly what I wanted to say. Hmmm. Hope that I didn't create any misunderstandings .... Danny Yoo schrieb: > > On Thu, 17 Mar 2005, Gregor Lingl wrote: > > >>Hi! >>Who knows a more concise or equally concise but more efficient >>expression, which returns the same result as >> >>[x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] > > > > Hi Gregor, > > Here is one that's traduced... er... adapted from material from the > classic textbook "Structure and Interpretation of Computer Programs": > > ###### > >>>>from itertools import ifilter, count >>>> >>>>def notDivisibleBy(n): > > ... def f(x): > ... return x % n != 0 > ... return f > ... > >>>>def sieve(iterable): > > ... nextPrime = iterable.next() > ... yield nextPrime > ... restOfPrimes = sieve(ifilter(notDivisibleBy(nextPrime), iterable)) > ... for prime in restOfPrimes: > ... yield prime > ... > >>>>primes = sieve(count(2)) >>>>primes.next() > > 2 > >>>>primes.next() > > 3 > >>>>primes.next() > > 5 > >>>>primes.next() > > 7 > >>>>primes.next() > > 11 > >>>>primes.next() > > 13 > >>>>primes.next() > > 17 > >>>>primes.next() > > 19 > >>>>primes.next() > > 23 > ###### > > The neat thing about this code is that it produces an infinite iterator of > prime numbers. The original code in Scheme is itself quite concise and > quite nice. It is described here: > > http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-24.html#call_footnote_Temp_455 > > > Best of wishes to you! > > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From glingl at aon.at Sat Mar 19 02:09:11 2005 From: glingl at aon.at (Gregor Lingl) Date: Sat Mar 19 02:06:31 2005 Subject: [Tutor] primes (Cautious remark on Python and Scheme) In-Reply-To: <423B78F5.4040202@aon.at> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> <423B78F5.4040202@aon.at> Message-ID: <423B7BB7.2080201@aon.at> Concerning my previous posting - perhaps it would suffice to summarize: While Python is a language for the "pragmatic" lover, Scheme is much more "fundamentalistic". (thought-) *PROVOKING*? Gregor From shaleh at speakeasy.net Sat Mar 19 04:26:07 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sat Mar 19 04:27:56 2005 Subject: [Tutor] primes In-Reply-To: <423AB69E.2020201@cirad.fr> References: <423A0493.2000902@aon.at> <423AB69E.2020201@cirad.fr> Message-ID: <423B9BCF.1080000@speakeasy.net> Pierre Barbier de Reuille wrote: > > def sieve( max ): > max_val = int( sqrt( max ) ) > s = Set(xrange( 4, max, 2 )) > for i in xrange( 3, max_val, 2 ): > s.update( xrange( 2*i, max, i ) ) > return [ i for i in xrange( 2, max ) if i not in s ] > just for grins, here is the same (mostly) code in haskell import Data.Set(elems, fromList, member, union) primeSieve :: Int -> [Int] primeSieve n = [ prime | prime <- [ 2 .. n ], not $ prime `member` nonPrimes ] where evenSet = fromList [4, 6 .. n ] xIncrements x = [ 2 * x, (2 * x) + x .. n ] maxVal = floor . sqrt $ fromIntegral n oddSet = fromList . concat $ map xIncrements [ 3, 5 .. maxVal ] nonPrimes = union evenSet oddSet fromList makes a list into a Set. [ x | x <- y, pred ] is analogous to Python's [ x for x in y if pred x ]. The '$' operator removes the need for parens. foo $ bar baz --> foo (bar baz) oh and '.' is the function composition operator. From bvande at po-box.mcgill.ca Sat Mar 19 05:08:01 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Mar 19 05:08:55 2005 Subject: [OT] Re: [Tutor] primes (Cautious remark on Python and Scheme) In-Reply-To: <423B78F5.4040202@aon.at> References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> <423B78F5.4040202@aon.at> Message-ID: <423BA5A1.9000809@po-box.mcgill.ca> Gregor Lingl said unto the world upon 2005-03-18 19:57: > Hi Danny! > > Preliminary remark: I know that "beautiful" and "beauty" > are concepts very seldom applied to computer programs or > programming languages. I suppose mainly because they are > to a large extent a matter of taste ... Hi Gregor and all, Though I've not had the time to follow the details of the thread closely, it's stored for future perusal -- I'm really glad you started it, Gregor. But, your comment above caught my eye. import this to see that beauty is embraced by the zen :-) It's been a long day, so I don't feel I am saying this well, but: When not trying to learn Python, I'm a (grad student) philosopher of logic and mathematics. I've thought some about beauty in proof, and hope to think seriously about it one day. Beauty in maths is like what the judge said about pornography -- "I can't define it, but I know it when I see it." I've never met a philosopher or a mathematician who could give a compelling (and robust) account of what makes for beauty, but there is widespread convergence of judgements about which proofs are beautiful and which ugly. (This even though taste does enter into it, too.) I think the same is true of (at least academic) computer science. The comp sci people I know at my uni all work in automated-theorem proving, and I know they use their perceptions of beauty as a design guide. And, with my much more limited experience with programming, my judgements that "this code is ugly" have been pretty reliable in identifying the problematic parts. "If it is beautiful, it might be right. If it is ugly, it is likely wrong" seems a safe claim. Anyway, all this is to say that I think that what you "know" above is wrong :-) <SNIP> > post scriptum: as always when writing not only about technical > facts but about opinions and values in English, I'm a bit axious > if I was able to express correctly what I wanted to say. Hmmm. > Hope that I didn't create any misunderstandings .... Ich kann Deutsch, aber nur ein bischen. I think I'd be a very happy fellow if my German were half as good as your English :-) Best to all, Brian vdB From keridee at jayco.net Sat Mar 19 17:07:36 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Mar 19 17:06:54 2005 Subject: [Tutor] Okay, something's funky Message-ID: <000301c52c9d$ce478b50$625428cf@JSLAPTOP> Hi everyone. Very simple set up for the problem, strange problem. #### Cards.py ### ## Taken almost directly from Thinking Like a Computer Scientist class Card: suitList = ["Clubs","Diamonds","Hearts","Spades"] rankList = ["","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"] def __init__(self,suit,rank): self.suit = suit self.rank = rank def __repr__(self): return str(self) def __str__(self): return "%s of %s" % (self.rankList[self.rank],self.suitList[self.suit]) def __cmp__(self,other): if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 return 0 class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(1,14): self.cards.append(Card(suit,rank)) def __str__(self): for card in self.cards: print card ### End of Cards.py ### Nothing wrong, right? So I fire up the interpreter and enter these commands Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Cards import * >>> a = Deck() >>> print a Ace of Clubs 2 of Clubs 3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs 7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs Jack of Clubs Queen of Clubs King of Clubs Ace of Diamonds 2 of Diamonds 3 of Diamonds 4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds 8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds Queen of Diamonds King of Diamonds Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts 5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts 9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts King of Hearts Ace of Spades 2 of Spades 3 of Spades 4 of Spades 5 of Spades 6 of Spades 7 of Spades 8 of Spades 9 of Spades 10 of Spades Jack of Spades Queen of Spades King of Spades Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: __str__ returned non-string (type NoneType) >>>Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >>>win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Cards import * >>> a = Deck() >>> print a Ace of Clubs 2 of Clubs 3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs 7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs Jack of Clubs Queen of Clubs King of Clubs Ace of Diamonds 2 of Diamonds 3 of Diamonds 4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds 8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds Queen of Diamonds King of Diamonds Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts 5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts 9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts King of Hearts Ace of Spades 2 of Spades 3 of Spades 4 of Spades 5 of Spades 6 of Spades 7 of Spades 8 of Spades 9 of Spades 10 of Spades Jack of Spades Queen of Spades King of Spades Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: __str__ returned non-string (type NoneType) >>>Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >>>win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Cards import * >>> a = Deck() >>> print a Ace of Clubs 2 of Clubs 3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs 7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs Jack of Clubs Queen of Clubs King of Clubs Ace of Diamonds 2 of Diamonds 3 of Diamonds 4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds 8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds Queen of Diamonds King of Diamonds Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts 5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts 9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts King of Hearts Ace of Spades 2 of Spades 3 of Spades 4 of Spades 5 of Spades 6 of Spades 7 of Spades 8 of Spades 9 of Spades 10 of Spades Jack of Spades Queen of Spades King of Spades Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: __str__ returned non-string (type NoneType) >>>Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >>>win32 Type "help", "copyright", "credits" or "license" for more information. >>> from Cards import * >>> a = Deck() >>> print a Ace of Clubs 2 of Clubs 3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs 7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs Jack of Clubs Queen of Clubs King of Clubs Ace of Diamonds 2 of Diamonds 3 of Diamonds 4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds 8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds Queen of Diamonds King of Diamonds Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts 5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts 9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts King of Hearts Ace of Spades 2 of Spades 3 of Spades 4 of Spades 5 of Spades 6 of Spades 7 of Spades 8 of Spades 9 of Spades 10 of Spades Jack of Spades Queen of Spades King of Spades Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: __str__ returned non-string (type NoneType) >>> a.cards [Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of Clubs, 7 of Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of Clubs, King of Clubs, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 of Dia monds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of Diamond s, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Hearts, 2 of He arts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 of Hear ts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of Hearts, Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of Spades, 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, Queen of Sp ades, King of Spades] >>> for card in a.cards: ... print card ... Ace of Clubs 2 of Clubs 3 of Clubs 4 of Clubs 5 of Clubs 6 of Clubs 7 of Clubs 8 of Clubs 9 of Clubs 10 of Clubs Jack of Clubs Queen of Clubs King of Clubs Ace of Diamonds 2 of Diamonds 3 of Diamonds 4 of Diamonds 5 of Diamonds 6 of Diamonds 7 of Diamonds 8 of Diamonds 9 of Diamonds 10 of Diamonds Jack of Diamonds Queen of Diamonds King of Diamonds Ace of Hearts 2 of Hearts 3 of Hearts 4 of Hearts 5 of Hearts 6 of Hearts 7 of Hearts 8 of Hearts 9 of Hearts 10 of Hearts Jack of Hearts Queen of Hearts King of Hearts Ace of Spades 2 of Spades 3 of Spades 4 of Spades 5 of Spades 6 of Spades 7 of Spades 8 of Spades 9 of Spades 10 of Spades Jack of Spades Queen of Spades King of Spades >>> len(a.cards) 52 >>> Why am I getting a NoneType in my loop? Any help appreciated. Jacob From sigurd at 12move.de Sat Mar 19 18:00:30 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sat Mar 19 18:04:39 2005 Subject: [Tutor] primes (generator) In-Reply-To: <423B6CA9.2050509@aon.at> (Gregor Lingl's message of "Sat, 19 Mar 2005 01:04:57 +0100") References: <Pine.LNX.4.44.0503171546300.22508-100000@hkn.eecs.berkeley.edu> <423B6CA9.2050509@aon.at> Message-ID: <ufyyrh9qh.fsf@hamster.pflaesterer.de> On 19 Mrz 2005, glingl@aon.at wrote: [Code] > Maybe sombody likes to compare these algorithms to the > ones mentioned before in this thread. I would be > interested in the results. I did it and on my machine here (a slow one) the following straight forward version is the fastest one. It's no iterator and since all the numbers are stored in a list you need place proportional the number of entries but it's fast and it works nearly the same way the original sieve of Erasthosthens algorithm works. Here it is no error to modify the list which gets iterated over. def sieve (max): max = max + 1 border = round(max**0.5) nums = range(0, max) nums[0] = nums[1] = None for p in nums: if p: if p >= border: break for i in xrange(p+p, max, p): nums[i] = None return filter(None, nums) Karl -- Please do *not* send copies of replies to me. I read the list From kent37 at tds.net Sat Mar 19 19:02:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 19 19:02:17 2005 Subject: [Tutor] Okay, something's funky In-Reply-To: <000301c52c9d$ce478b50$625428cf@JSLAPTOP> References: <000301c52c9d$ce478b50$625428cf@JSLAPTOP> Message-ID: <423C6921.4000306@tds.net> Jacob S. wrote: > Hi everyone. Very simple set up for the problem, strange problem. > class Deck: > def __init__(self): > self.cards = [] > for suit in range(4): > for rank in range(1,14): > self.cards.append(Card(suit,rank)) > def __str__(self): > for card in self.cards: > print card __str__() should *return* a string representation of the object, not print it! Your __str__() method prints the Deck and returns None, which is the source of the error. Try def __str__(self): return '\n'.join(str(card) for card in self.cards) Kent > > ### End of Cards.py ### > > Nothing wrong, right? > So I fire up the interpreter and enter these commands > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>> from Cards import * >>>> a = Deck() >>>> print a > > Ace of Clubs > 2 of Clubs > 3 of Clubs > 4 of Clubs > 5 of Clubs > 6 of Clubs > 7 of Clubs > 8 of Clubs > 9 of Clubs > 10 of Clubs > Jack of Clubs > Queen of Clubs > King of Clubs > Ace of Diamonds > 2 of Diamonds > 3 of Diamonds > 4 of Diamonds > 5 of Diamonds > 6 of Diamonds > 7 of Diamonds > 8 of Diamonds > 9 of Diamonds > 10 of Diamonds > Jack of Diamonds > Queen of Diamonds > King of Diamonds > Ace of Hearts > 2 of Hearts > 3 of Hearts > 4 of Hearts > 5 of Hearts > 6 of Hearts > 7 of Hearts > 8 of Hearts > 9 of Hearts > 10 of Hearts > Jack of Hearts > Queen of Hearts > King of Hearts > Ace of Spades > 2 of Spades > 3 of Spades > 4 of Spades > 5 of Spades > 6 of Spades > 7 of Spades > 8 of Spades > 9 of Spades > 10 of Spades > Jack of Spades > Queen of Spades > King of Spades > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: __str__ returned non-string (type NoneType) > >>>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] >>>> on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> from Cards import * >>>> a = Deck() >>>> print a > > Ace of Clubs > 2 of Clubs > 3 of Clubs > 4 of Clubs > 5 of Clubs > 6 of Clubs > 7 of Clubs > 8 of Clubs > 9 of Clubs > 10 of Clubs > Jack of Clubs > Queen of Clubs > King of Clubs > Ace of Diamonds > 2 of Diamonds > 3 of Diamonds > 4 of Diamonds > 5 of Diamonds > 6 of Diamonds > 7 of Diamonds > 8 of Diamonds > 9 of Diamonds > 10 of Diamonds > Jack of Diamonds > Queen of Diamonds > King of Diamonds > Ace of Hearts > 2 of Hearts > 3 of Hearts > 4 of Hearts > 5 of Hearts > 6 of Hearts > 7 of Hearts > 8 of Hearts > 9 of Hearts > 10 of Hearts > Jack of Hearts > Queen of Hearts > King of Hearts > Ace of Spades > 2 of Spades > 3 of Spades > 4 of Spades > 5 of Spades > 6 of Spades > 7 of Spades > 8 of Spades > 9 of Spades > 10 of Spades > Jack of Spades > Queen of Spades > King of Spades > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: __str__ returned non-string (type NoneType) > >>>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] >>>> on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> from Cards import * >>>> a = Deck() >>>> print a > > Ace of Clubs > 2 of Clubs > 3 of Clubs > 4 of Clubs > 5 of Clubs > 6 of Clubs > 7 of Clubs > 8 of Clubs > 9 of Clubs > 10 of Clubs > Jack of Clubs > Queen of Clubs > King of Clubs > Ace of Diamonds > 2 of Diamonds > 3 of Diamonds > 4 of Diamonds > 5 of Diamonds > 6 of Diamonds > 7 of Diamonds > 8 of Diamonds > 9 of Diamonds > 10 of Diamonds > Jack of Diamonds > Queen of Diamonds > King of Diamonds > Ace of Hearts > 2 of Hearts > 3 of Hearts > 4 of Hearts > 5 of Hearts > 6 of Hearts > 7 of Hearts > 8 of Hearts > 9 of Hearts > 10 of Hearts > Jack of Hearts > Queen of Hearts > King of Hearts > Ace of Spades > 2 of Spades > 3 of Spades > 4 of Spades > 5 of Spades > 6 of Spades > 7 of Spades > 8 of Spades > 9 of Spades > 10 of Spades > Jack of Spades > Queen of Spades > King of Spades > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: __str__ returned non-string (type NoneType) > >>>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] >>>> on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> from Cards import * >>>> a = Deck() >>>> print a > > Ace of Clubs > 2 of Clubs > 3 of Clubs > 4 of Clubs > 5 of Clubs > 6 of Clubs > 7 of Clubs > 8 of Clubs > 9 of Clubs > 10 of Clubs > Jack of Clubs > Queen of Clubs > King of Clubs > Ace of Diamonds > 2 of Diamonds > 3 of Diamonds > 4 of Diamonds > 5 of Diamonds > 6 of Diamonds > 7 of Diamonds > 8 of Diamonds > 9 of Diamonds > 10 of Diamonds > Jack of Diamonds > Queen of Diamonds > King of Diamonds > Ace of Hearts > 2 of Hearts > 3 of Hearts > 4 of Hearts > 5 of Hearts > 6 of Hearts > 7 of Hearts > 8 of Hearts > 9 of Hearts > 10 of Hearts > Jack of Hearts > Queen of Hearts > King of Hearts > Ace of Spades > 2 of Spades > 3 of Spades > 4 of Spades > 5 of Spades > 6 of Spades > 7 of Spades > 8 of Spades > 9 of Spades > 10 of Spades > Jack of Spades > Queen of Spades > King of Spades > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: __str__ returned non-string (type NoneType) > >>>> a.cards > > [Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of > Clubs, 7 of > Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of > Clubs, King > of Clubs, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, > 5 of Dia > monds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of > Diamond > s, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Hearts, > 2 of He > arts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 > of Hear > ts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of > Hearts, > Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of > Spades, > 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, > Queen of Sp > ades, King of Spades] > >>>> for card in a.cards: > > ... print card > ... > Ace of Clubs > 2 of Clubs > 3 of Clubs > 4 of Clubs > 5 of Clubs > 6 of Clubs > 7 of Clubs > 8 of Clubs > 9 of Clubs > 10 of Clubs > Jack of Clubs > Queen of Clubs > King of Clubs > Ace of Diamonds > 2 of Diamonds > 3 of Diamonds > 4 of Diamonds > 5 of Diamonds > 6 of Diamonds > 7 of Diamonds > 8 of Diamonds > 9 of Diamonds > 10 of Diamonds > Jack of Diamonds > Queen of Diamonds > King of Diamonds > Ace of Hearts > 2 of Hearts > 3 of Hearts > 4 of Hearts > 5 of Hearts > 6 of Hearts > 7 of Hearts > 8 of Hearts > 9 of Hearts > 10 of Hearts > Jack of Hearts > Queen of Hearts > King of Hearts > Ace of Spades > 2 of Spades > 3 of Spades > 4 of Spades > 5 of Spades > 6 of Spades > 7 of Spades > 8 of Spades > 9 of Spades > 10 of Spades > Jack of Spades > Queen of Spades > King of Spades > >>>> len(a.cards) > > 52 > >>>> > > Why am I getting a NoneType in my loop? > > Any help appreciated. > Jacob > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Sat Mar 19 20:48:56 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Mar 19 20:48:29 2005 Subject: [Tutor] Okay, something's funky References: <000301c52c9d$ce478b50$625428cf@JSLAPTOP> <423C6921.4000306@tds.net> Message-ID: <000301c52cbc$be19e8d0$135428cf@JSLAPTOP> Oh thanks!! Sometimes I just look blind... Jacob > Jacob S. wrote: >> Hi everyone. Very simple set up for the problem, strange problem. >> class Deck: >> def __init__(self): >> self.cards = [] >> for suit in range(4): >> for rank in range(1,14): >> self.cards.append(Card(suit,rank)) >> def __str__(self): >> for card in self.cards: >> print card > > __str__() should *return* a string representation of the object, not print > it! Your __str__() method prints the Deck and returns None, which is the > source of the error. Try > def __str__(self): > return '\n'.join(str(card) for card in self.cards) > > Kent > >> >> ### End of Cards.py ### >> >> Nothing wrong, right? >> So I fire up the interpreter and enter these commands >> >> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>>>> from Cards import * >>>>> a = Deck() >>>>> print a >> >> Ace of Clubs >> 2 of Clubs >> 3 of Clubs >> 4 of Clubs >> 5 of Clubs >> 6 of Clubs >> 7 of Clubs >> 8 of Clubs >> 9 of Clubs >> 10 of Clubs >> Jack of Clubs >> Queen of Clubs >> King of Clubs >> Ace of Diamonds >> 2 of Diamonds >> 3 of Diamonds >> 4 of Diamonds >> 5 of Diamonds >> 6 of Diamonds >> 7 of Diamonds >> 8 of Diamonds >> 9 of Diamonds >> 10 of Diamonds >> Jack of Diamonds >> Queen of Diamonds >> King of Diamonds >> Ace of Hearts >> 2 of Hearts >> 3 of Hearts >> 4 of Hearts >> 5 of Hearts >> 6 of Hearts >> 7 of Hearts >> 8 of Hearts >> 9 of Hearts >> 10 of Hearts >> Jack of Hearts >> Queen of Hearts >> King of Hearts >> Ace of Spades >> 2 of Spades >> 3 of Spades >> 4 of Spades >> 5 of Spades >> 6 of Spades >> 7 of Spades >> 8 of Spades >> 9 of Spades >> 10 of Spades >> Jack of Spades >> Queen of Spades >> King of Spades >> Traceback (most recent call last): >> File "<stdin>", line 1, in ? >> TypeError: __str__ returned non-string (type NoneType) >> >>>>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >>>>> win32 >> >> Type "help", "copyright", "credits" or "license" for more information. >> >>>>> from Cards import * >>>>> a = Deck() >>>>> print a >> >> Ace of Clubs >> 2 of Clubs >> 3 of Clubs >> 4 of Clubs >> 5 of Clubs >> 6 of Clubs >> 7 of Clubs >> 8 of Clubs >> 9 of Clubs >> 10 of Clubs >> Jack of Clubs >> Queen of Clubs >> King of Clubs >> Ace of Diamonds >> 2 of Diamonds >> 3 of Diamonds >> 4 of Diamonds >> 5 of Diamonds >> 6 of Diamonds >> 7 of Diamonds >> 8 of Diamonds >> 9 of Diamonds >> 10 of Diamonds >> Jack of Diamonds >> Queen of Diamonds >> King of Diamonds >> Ace of Hearts >> 2 of Hearts >> 3 of Hearts >> 4 of Hearts >> 5 of Hearts >> 6 of Hearts >> 7 of Hearts >> 8 of Hearts >> 9 of Hearts >> 10 of Hearts >> Jack of Hearts >> Queen of Hearts >> King of Hearts >> Ace of Spades >> 2 of Spades >> 3 of Spades >> 4 of Spades >> 5 of Spades >> 6 of Spades >> 7 of Spades >> 8 of Spades >> 9 of Spades >> 10 of Spades >> Jack of Spades >> Queen of Spades >> King of Spades >> Traceback (most recent call last): >> File "<stdin>", line 1, in ? >> TypeError: __str__ returned non-string (type NoneType) >> >>>>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >>>>> win32 >> >> Type "help", "copyright", "credits" or "license" for more information. >> >>>>> from Cards import * >>>>> a = Deck() >>>>> print a >> >> Ace of Clubs >> 2 of Clubs >> 3 of Clubs >> 4 of Clubs >> 5 of Clubs >> 6 of Clubs >> 7 of Clubs >> 8 of Clubs >> 9 of Clubs >> 10 of Clubs >> Jack of Clubs >> Queen of Clubs >> King of Clubs >> Ace of Diamonds >> 2 of Diamonds >> 3 of Diamonds >> 4 of Diamonds >> 5 of Diamonds >> 6 of Diamonds >> 7 of Diamonds >> 8 of Diamonds >> 9 of Diamonds >> 10 of Diamonds >> Jack of Diamonds >> Queen of Diamonds >> King of Diamonds >> Ace of Hearts >> 2 of Hearts >> 3 of Hearts >> 4 of Hearts >> 5 of Hearts >> 6 of Hearts >> 7 of Hearts >> 8 of Hearts >> 9 of Hearts >> 10 of Hearts >> Jack of Hearts >> Queen of Hearts >> King of Hearts >> Ace of Spades >> 2 of Spades >> 3 of Spades >> 4 of Spades >> 5 of Spades >> 6 of Spades >> 7 of Spades >> 8 of Spades >> 9 of Spades >> 10 of Spades >> Jack of Spades >> Queen of Spades >> King of Spades >> Traceback (most recent call last): >> File "<stdin>", line 1, in ? >> TypeError: __str__ returned non-string (type NoneType) >> >>>>> Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on >>>>> win32 >> >> Type "help", "copyright", "credits" or "license" for more information. >> >>>>> from Cards import * >>>>> a = Deck() >>>>> print a >> >> Ace of Clubs >> 2 of Clubs >> 3 of Clubs >> 4 of Clubs >> 5 of Clubs >> 6 of Clubs >> 7 of Clubs >> 8 of Clubs >> 9 of Clubs >> 10 of Clubs >> Jack of Clubs >> Queen of Clubs >> King of Clubs >> Ace of Diamonds >> 2 of Diamonds >> 3 of Diamonds >> 4 of Diamonds >> 5 of Diamonds >> 6 of Diamonds >> 7 of Diamonds >> 8 of Diamonds >> 9 of Diamonds >> 10 of Diamonds >> Jack of Diamonds >> Queen of Diamonds >> King of Diamonds >> Ace of Hearts >> 2 of Hearts >> 3 of Hearts >> 4 of Hearts >> 5 of Hearts >> 6 of Hearts >> 7 of Hearts >> 8 of Hearts >> 9 of Hearts >> 10 of Hearts >> Jack of Hearts >> Queen of Hearts >> King of Hearts >> Ace of Spades >> 2 of Spades >> 3 of Spades >> 4 of Spades >> 5 of Spades >> 6 of Spades >> 7 of Spades >> 8 of Spades >> 9 of Spades >> 10 of Spades >> Jack of Spades >> Queen of Spades >> King of Spades >> Traceback (most recent call last): >> File "<stdin>", line 1, in ? >> TypeError: __str__ returned non-string (type NoneType) >> >>>>> a.cards >> >> [Ace of Clubs, 2 of Clubs, 3 of Clubs, 4 of Clubs, 5 of Clubs, 6 of >> Clubs, 7 of >> Clubs, 8 of Clubs, 9 of Clubs, 10 of Clubs, Jack of Clubs, Queen of >> Clubs, King >> of Clubs, Ace of Diamonds, 2 of Diamonds, 3 of Diamonds, 4 of Diamonds, 5 >> of Dia >> monds, 6 of Diamonds, 7 of Diamonds, 8 of Diamonds, 9 of Diamonds, 10 of >> Diamond >> s, Jack of Diamonds, Queen of Diamonds, King of Diamonds, Ace of Hearts, >> 2 of He >> arts, 3 of Hearts, 4 of Hearts, 5 of Hearts, 6 of Hearts, 7 of Hearts, 8 >> of Hear >> ts, 9 of Hearts, 10 of Hearts, Jack of Hearts, Queen of Hearts, King of >> Hearts, >> Ace of Spades, 2 of Spades, 3 of Spades, 4 of Spades, 5 of Spades, 6 of >> Spades, >> 7 of Spades, 8 of Spades, 9 of Spades, 10 of Spades, Jack of Spades, >> Queen of Sp >> ades, King of Spades] >> >>>>> for card in a.cards: >> >> ... print card >> ... >> Ace of Clubs >> 2 of Clubs >> 3 of Clubs >> 4 of Clubs >> 5 of Clubs >> 6 of Clubs >> 7 of Clubs >> 8 of Clubs >> 9 of Clubs >> 10 of Clubs >> Jack of Clubs >> Queen of Clubs >> King of Clubs >> Ace of Diamonds >> 2 of Diamonds >> 3 of Diamonds >> 4 of Diamonds >> 5 of Diamonds >> 6 of Diamonds >> 7 of Diamonds >> 8 of Diamonds >> 9 of Diamonds >> 10 of Diamonds >> Jack of Diamonds >> Queen of Diamonds >> King of Diamonds >> Ace of Hearts >> 2 of Hearts >> 3 of Hearts >> 4 of Hearts >> 5 of Hearts >> 6 of Hearts >> 7 of Hearts >> 8 of Hearts >> 9 of Hearts >> 10 of Hearts >> Jack of Hearts >> Queen of Hearts >> King of Hearts >> Ace of Spades >> 2 of Spades >> 3 of Spades >> 4 of Spades >> 5 of Spades >> 6 of Spades >> 7 of Spades >> 8 of Spades >> 9 of Spades >> 10 of Spades >> Jack of Spades >> Queen of Spades >> King of Spades >> >>>>> len(a.cards) >> >> 52 >> >>>>> >> >> Why am I getting a NoneType in my loop? >> >> Any help appreciated. >> Jacob >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at jayloden.com Sun Mar 20 02:52:16 2005 From: python at jayloden.com (Jay Loden) Date: Sat Mar 19 21:55:30 2005 Subject: [Tutor] Prepend to a list? Message-ID: <200503192052.16534.python@jayloden.com> How can I prepend something to a list? I thought that I could do list.prepend() since you can do list.append() but apparently not. Any way to add something to a list at the beginning, or do I just have to make a new list? -Jay From cyresse at gmail.com Sat Mar 19 22:10:45 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Mar 19 22:10:48 2005 Subject: [Tutor] Prepend to a list? In-Reply-To: <200503192052.16534.python@jayloden.com> References: <200503192052.16534.python@jayloden.com> Message-ID: <f2ff2d05031913105e2254a7@mail.gmail.com> Hi Jay, >>> x = [2,3,4,5,6,7,8] >>> x.insert(0,1) >>> print x [1, 2, 3, 4, 5, 6, 7, 8] >>> print x.insert.__doc__ L.insert(index, object) -- insert object before index Or >>> a = [2,3,4,5,6,7,8] >>> a.reverse() >>> a.append(1) >>> a.reverse() >>> print a [1, 2, 3, 4, 5, 6, 7, 8] >>> print a.reverse.__doc__ L.reverse() -- reverse *IN PLACE* the IN PLACE is important. It doesn't return a modified copy, it modifies the original list, same as L.sort() HTH Liam Clarke On Sat, 19 Mar 2005 20:52:16 -0500, Jay Loden <python@jayloden.com> wrote: > How can I prepend something to a list? I thought that I could do > list.prepend() since you can do list.append() but apparently not. Any way to > add something to a list at the beginning, or do I just have to make a new > list? > > -Jay > _______________________________________________ > 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. From shaleh at speakeasy.net Sat Mar 19 22:10:26 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sat Mar 19 22:12:14 2005 Subject: [Tutor] Prepend to a list? In-Reply-To: <200503192052.16534.python@jayloden.com> References: <200503192052.16534.python@jayloden.com> Message-ID: <423C9542.2080700@speakeasy.net> Jay Loden wrote: > How can I prepend something to a list? I thought that I could do > list.prepend() since you can do list.append() but apparently not. Any way to > add something to a list at the beginning, or do I just have to make a new > list? > >>> a = [] >>> help(a.insert) insert(...) L.insert(index, object) -- insert object before index From dyoo at hkn.eecs.berkeley.edu Sun Mar 20 00:08:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 20 00:08:53 2005 Subject: [Tutor] Prepend to a list? In-Reply-To: <200503192052.16534.python@jayloden.com> Message-ID: <Pine.LNX.4.44.0503191459590.22909-100000@hkn.eecs.berkeley.edu> On Sat, 19 Mar 2005, Jay Loden wrote: > How can I prepend something to a list? I thought that I could do > list.prepend() since you can do list.append() but apparently not. Any > way to add something to a list at the beginning, or do I just have to > make a new list? Hi Jay, Liam and Sean pointed out that you can either do a combination of reverse() and append(), or you can use insert(). How often are you planning to prepend onto your lists, though? The performance of both approaches can be quite different, depending on input size. Do you plan to do a lot of prepends at a time? Also, are you dealing with short lists? If you're dealing with short lists, either solution will work fine. But if your lists grow to something much larger (say, in the tens of thousands), then you might need a more specialized solution, such as a 'deque': http://www.python.org/doc/lib/module-collections.html A dequeue behaves like a list, but it also supports very fast "prepend" (in the dequeue documentation, the 'appendleft()' method), so if your needs are specialized, a deque might be an appropriate data structure for you. Best of wishes! From cyresse at gmail.com Sun Mar 20 01:40:27 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 20 01:40:32 2005 Subject: [Tutor] Re: [Pythoncard-users] global menubar In-Reply-To: <OF37C26486.417FDEC3-ON86256FC9.007A8643-86256FC9.007B7E1D@omsdal.com> References: <f2ff2d05031913057861a2e@mail.gmail.com> <OF37C26486.417FDEC3-ON86256FC9.007A8643-86256FC9.007B7E1D@omsdal.com> Message-ID: <f2ff2d05031916409137757@mail.gmail.com> Sorry, I meant Menu Editor... I'm not sure how you would handle your global menubar. You could have one parent window with a menu, and none of the children windows have menus. But, when you open the children, your parent will lose focus, if that's going to be a problem. Ummm... if none of your children windows are going to have menus, would it be that hard to give them all the same menu? Alternatively, you might want to check out the wxPython demo for what you want do do. It has support for the more complex stuff like sash windows, etc. Good luck, Liam Clarke On Sat, 19 Mar 2005 16:28:52 -0600, brad.allen@omsdal.com <brad.allen@omsdal.com> wrote: > > Hm...I don't see that option on any of my windows under Background Info. I'm > using PythonCard .81 with Python 2.3 under Windows XP . I do see a checkbox > called "Status bar on Window", but unchecking that had no effect that I > could see. The menus on my primary parent window are still not available in > child windows. > > To clarify, what I'm trying to accomplish here is an overarching application > window which contains other windows. At least, that's what it would look > like under Windows. On a Mac, it would just be an menubar globally available > and applicable independent of which window happened to be active. I'm not > clear on how to accomplish this in PythonCard. > > Thanks! > > Liam Clarke <cyresse@gmail.com> wrote on 03/19/2005 03:05:09 PM: > > > > In the Resource Editor, go to Background Info and turn off menus for > > the windows. > > > > > > On Sat, 19 Mar 2005 11:59:09 -0600, brad.allen@omsdal.com > > <brad.allen@omsdal.com> wrote: > > > > > > I've noticed that the basic structure in PythonCard involves every > window > > > having a separate menubar. Is there a way in PythonCard to have an > > > overarching application menu, with no menus in each window? > > > > > > Thanks! > > > > > > -- > > '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. > -- '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. From cweimann at k12hq.com Fri Mar 18 18:27:35 2005 From: cweimann at k12hq.com (Christopher Weimann) Date: Sun Mar 20 04:06:08 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <20050317040029.GE35825@tektite.k12usa.internal> <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> Message-ID: <20050318172735.GA71118@tektite.k12usa.internal> On 03/17/2005-10:15AM, Mike Hall wrote: > > <applause> Very nice sir. I'm interested in what you're doing here with > the caret metacharacter. For one thing, why enclose it and the > whitespace flag within a character class? A caret as the first charachter in a class is a negation. So this [^\s]+ means match one or more of any char that isn't whitespace. > Does this not traditionally > mean you want to strip a metacharacter of it's special meaning? > That would be \ From dyoo at hkn.eecs.berkeley.edu Sun Mar 20 04:18:54 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 20 04:18:58 2005 Subject: [Tutor] Prepend to a list? (fwd) Message-ID: <Pine.LNX.4.44.0503191918510.2283-100000@hkn.eecs.berkeley.edu> ---------- Forwarded message ---------- Date: Sun, 20 Mar 2005 00:05:07 -0500 From: Jay Loden <python@jayloden.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] Prepend to a list? Thanks for the replies everyone, I ended up changing my approach so that it won't require appending to the list, but it's good to know anyway because I'm sure it will come up in the future. I'm sort of surprised there isn't a prepend() method for lists, but I'm sure there's a reason. Danny, thanks for the extra info, I'll definitely keep that in mind. The script(s) I'm working on are for a content management system using Python/PHP in combination. Most of the data is small sets, but fairly frequently run, so I'm looking for more efficient code in terms of CPU cycles on the server. In such a case, is one of the approaches better, or are they fairly equal? -Jay On Saturday 19 March 2005 06:08 pm, you wrote: > Hi Jay, > > Liam and Sean pointed out that you can either do a combination of > reverse() and append(), or you can use insert(). > > How often are you planning to prepend onto your lists, though? The > performance of both approaches can be quite different, depending on input > size. Do you plan to do a lot of prepends at a time? Also, are you > dealing with short lists? > > If you're dealing with short lists, either solution will work fine. But > if your lists grow to something much larger (say, in the tens of > thousands), then you might need a more specialized solution, such as a > 'deque': > > http://www.python.org/doc/lib/module-collections.html > > A dequeue behaves like a list, but it also supports very fast "prepend" > (in the dequeue documentation, the 'appendleft()' method), so if your > needs are specialized, a deque might be an appropriate data structure for > you. > > > Best of wishes! From pickleboy77 at hotmail.com Sun Mar 20 05:33:32 2005 From: pickleboy77 at hotmail.com (Brainerd HeadFat) Date: Sun Mar 20 05:33:36 2005 Subject: [Tutor] program for creation of unique objects In-Reply-To: <20050319194828.AA6C41E4010@bag.python.org> Message-ID: <BAY101-F250A5C812EF14032C27073A34C0@phx.gbl> Hi, I'm having trouble trying to figure out how to create multiple objects that contain duplicate entries that can be uniquely identified within a Tkinter GUI. I want a user to define an item and then define multiple characteristics about that item, save a dictionary of items, and then reload the items back into the GUI upon restart. The code I'm have trouble with looks something like this. def newitem(): itemframe = Frame(parent) entry1 = Entryfield(itemframe) entry2 = Entryfield(itemframe) button1 = Button(itemframe, command = update()) def update(): a = entry1.getvalue() b = entry2.getvalue() values = [a,b] print values The problem I'm having is that as soon as the user runs newitem() the previous itemframe loses its name and i can only access the most recently created itemframe. I feel like the most convenient way to accomplish this would be something like x = Frame() in parent itemframe'x' = itemframe Where 'x' is a unique integer. But I don't know how to create unique variables on the fly. I'm sure there are a thousand ways to accomplish what I'm trying to, and it seems like a trivial thing that gets dealt with all the time, and I'm embarrased that I have to ask. I'm pretty new to programming and this is my first attempt at a GUI or a really useful program. Thanks for your help. From kent37 at tds.net Sun Mar 20 13:27:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 20 13:27:22 2005 Subject: [Tutor] program for creation of unique objects In-Reply-To: <BAY101-F250A5C812EF14032C27073A34C0@phx.gbl> References: <BAY101-F250A5C812EF14032C27073A34C0@phx.gbl> Message-ID: <423D6C26.8020504@tds.net> Brainerd HeadFat wrote: > Hi, > > I'm having trouble trying to figure out how to create multiple > objects that contain duplicate entries that can be uniquely identified > within a Tkinter GUI. > > I want a user to define an item and then > define multiple characteristics about that item, > save a dictionary of items, > and then reload the items back into the GUI upon restart. > > The code I'm have trouble with looks something like this. > > > def newitem(): > itemframe = Frame(parent) > entry1 = Entryfield(itemframe) > entry2 = Entryfield(itemframe) > button1 = Button(itemframe, command = update()) > > def update(): > a = entry1.getvalue() > b = entry2.getvalue() > values = [a,b] > print values > > The problem I'm having is that as soon as the user runs newitem() > the previous itemframe loses its name and i can only access the most > recently > created itemframe. It sounds like maybe you should keep a list of the itemframes and their contents. One way to do this would be to have a list itemframes = [] then in newitem() save the parts you care about like this: itemdetails = (itemframe, entry1, entry2) itemframes.append(itemdetails) Then when you want to access all the itemframes use a loop like this: for itemframe, entry1, entry2 in itemframes: # do something with itemframe, entry1, entry2 Kent > > I feel like the most convenient way to accomplish this would be > something like > > x = Frame() in parent > itemframe'x' = itemframe > > > Where 'x' is a unique integer. But I don't know how to create unique > variables on the fly. > > I'm sure there are a thousand ways to accomplish what I'm trying to, > and it seems like a trivial thing that gets dealt with all the time, > and I'm embarrased that I have to ask. > I'm pretty new to programming and this is my first attempt at a GUI or > a really useful program. Thanks for your help. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From smnordby at yahoo.com Sun Mar 20 14:46:24 2005 From: smnordby at yahoo.com (Steve N) Date: Sun Mar 20 14:46:27 2005 Subject: [Tutor] Why is this not an error? In-Reply-To: <20050320110142.5A6DA1E4021@bag.python.org> Message-ID: <20050320134624.70681.qmail@web54410.mail.yahoo.com> This code runs, but it seems to me it should generate a syntax error. Can someone explain what's going on? x = [1,2,3,4] z = 4 if z in x: print 'found:', z for i in x: print 'in the loop with', i else: print 'not found:', z >>> found: 4 in the loop with 1 in the loop with 2 in the loop with 3 in the loop with 4 not found: 4 >>> -- Steve __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From hameed.u.khan at gmail.com Sun Mar 20 15:20:37 2005 From: hameed.u.khan at gmail.com (Hameed U. Khan) Date: Sun Mar 20 15:20:33 2005 Subject: [Tutor] Why is this not an error? In-Reply-To: <20050320134624.70681.qmail@web54410.mail.yahoo.com> References: <20050320134624.70681.qmail@web54410.mail.yahoo.com> Message-ID: <200503201921.00540.hameed.u.khan@gmail.com> On Sunday 20 Mar 2005 1846, Steve N wrote: > This code runs, but it seems to me it should generate > a syntax error. Can someone explain what's going on? Why do you think there is a syntax error? > x = [1,2,3,4] > z = 4 > if z in x: > print 'found:', z if clause has been ended here. > for i in x: > print 'in the loop with', i > else: > print 'not found:', z This else is the part of the for loop. And the statements in this else will be executed if your for loop will complete all of its iterations. if you want this else with 'if' statement then remove the for loop. > > found: 4 > in the loop with 1 > in the loop with 2 > in the loop with 3 > in the loop with 4 > not found: 4 > > -- > Steve > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Easier than ever with enhanced search. Learn more. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Hameed U. Khan, <hameed.u.khan at gmail dot com> Registered Linux User #: 354374 From shaleh at speakeasy.net Sun Mar 20 17:55:55 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sun Mar 20 17:57:44 2005 Subject: [Tutor] Why is this not an error? In-Reply-To: <200503201921.00540.hameed.u.khan@gmail.com> References: <20050320134624.70681.qmail@web54410.mail.yahoo.com> <200503201921.00540.hameed.u.khan@gmail.com> Message-ID: <423DAB1B.4020601@speakeasy.net> Hameed U. Khan wrote: > > This else is the part of the for loop. And the statements in this else will be > executed if your for loop will complete all of its iterations. if you want > this else with 'if' statement then remove the for loop. > for instance: looking_for = 11 for i in range(0,10): if i == looking_for: handle_it(i) break else: print "Did not find", looking_for From alan.gauld at freenet.co.uk Sun Mar 20 18:27:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 20 18:26:25 2005 Subject: [Tutor] Re: [Pythoncard-users] global menubar References: <f2ff2d05031913057861a2e@mail.gmail.com><OF37C26486.417FDEC3-ON86256FC9.007A8643-86256FC9.007B7E1D@omsdal.com> <f2ff2d05031916409137757@mail.gmail.com> Message-ID: <003401c52d72$15f72fd0$93c28651@xp> > > To clarify, what I'm trying to accomplish here is an overarching application > > window which contains other windows. At least, that's what it would look > > like under Windows. You mean this would be an MDI Application? There is usually a special class or attribute to support MDI in theGUI toolkits. Searching for MDI in the help/FAQ might help locate what you need? > > On a Mac, it would just be an menubar globally available > > and applicable independent of which window happened to be active. In other words a standard MacOS style aplication. You also omit X WIndows (Linux, BSD, Solaris etc) from your list but in those the menu locatio is a user preference and is controlled by the Window Manager chosen by the user. This raises an interesting issue around GUI design. One objective should be to "go with the norm", that is to follow the paradigm of the underlying platform, and that includes the placement of controls. Users expect to find the controls, including menus, in the same place each time, to do otherwise will invariably make you application less user-friendly. The GUI toolkits do this for us if we stick to the norm, so there needs to be a very good reason to depart from the standard layout. > > I'm not clear on how to accomplish this in PythonCard. Me neither! But its based on wxWidgets so it might be worth trawling around there for clues. Alan G. From alan.gauld at freenet.co.uk Sun Mar 20 18:45:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 20 18:44:26 2005 Subject: [Tutor] program for creation of unique objects References: <BAY101-F250A5C812EF14032C27073A34C0@phx.gbl> Message-ID: <003901c52d74$997d2920$93c28651@xp> > I want a user to define an item and then > define multiple characteristics about that item, > save a dictionary of items, > and then reload the items back into the GUI upon restart. I'm still not absolutely sure what you mean. Do you mean the GUI itself is going to grow new panels etc as the user works with it? Or is it the items the GUI displays that increase - like graphics objects within a canvas for example? > The code I'm have trouble with looks something like this. > > > def newitem(): > itemframe = Frame(parent) > entry1 = Entryfield(itemframe) > entry2 = Entryfield(itemframe) > button1 = Button(itemframe, command = update()) These variables only live for as long as the function lives. You need to store them in eitther a global variable somewhere (or more probably a global container somewhere) or as part of a class from which you create multiple instances. One of the primary advantages of OOP and classes is that although they share code the data in distinct for each object. > def update(): > a = entry1.getvalue() > b = entry2.getvalue() > values = [a,b] > print values Is it the list [a,b] that you want to persist? If so, you need to save the list (instead of printing it), thus you need a global container which will contain the [a,b] pairs. (A tuple (a,b) is the most natural way if doing this rather than a list [a,b]) > The problem I'm having is that as soon as the user runs newitem() > the previous itemframe loses its name and i can only access the most > recently > created itemframe. > > I feel like the most convenient way to accomplish this would be something > like > > x = Frame() in parent > itemframe'x' = itemframe THe most conventiant way is OOP. class myFrame(Frame): def __init__(self,parent=0): # replace newitem() Frame.__init__(self,parent) self.entry1 = Entryfield(itemframe) self.entry2 = Entryfield(itemframe) self.button1 = Button(itemframe, command = update()) def update(): self.a = self.entry1.getvalue() self.b = self.entry2.getvalue() print self.a, self.b Now you can do things like: x = MyFrame() y = MyFRame() x.update() y.update() and so on. I'm still not entirely sure this is what you want. And there's a lot of work to fix the code to be sensible Tkinter - no layout manager calls here for example... But OOP is almost certainly the best approach to your problem. > Where 'x' is a unique integer. But I don't know how to create unique > variables on the fly. Do you mean unique variable names or unique values? The latter can be achieved simply with a global sequence number and a function that returns a name and increments the sequence number. Remember to save the last value between program runs. > I'm sure there are a thousand ways to accomplish what I'm trying to, > and it seems like a trivial thing that gets dealt with all the time, Givemn I'm not sure what you are trying to do exactly I'm not so sure its done all the time. But it may be that you are falling into the trap of trying to name your objects dynamically too? In which case rethink the idea and use a container to store the instances instead, its much easier long term. See my OOP page for more on OOP in general and how to avoid dynamic variable creation using a dictionary. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From lumbricus at gmx.net Sun Mar 20 20:06:26 2005 From: lumbricus at gmx.net (Joerg Woelke) Date: Sun Mar 20 20:08:47 2005 Subject: [Tutor] stopping greedy matches In-Reply-To: <20050318172735.GA71118@tektite.k12usa.internal> References: <3e3567d76c3f1e8f6dff673e61c98a93@critterpixstudios.com> <20050317040029.GE35825@tektite.k12usa.internal> <41ee6bc77f03fb44d0e98eac0dcfcb22@critterpixstudios.com> <20050318172735.GA71118@tektite.k12usa.internal> Message-ID: <20050320190626.GA1832@laplace> On Fri, Mar 18, 2005 at 12:27:35PM -0500, Christopher Weimann wrote: > So this [^\s]+ means match one or more of any char that > isn't whitespace. Could be just \S+ Greetings, J"o! -- Reply hazy, ask again later. From glingl at aon.at Sun Mar 20 20:18:03 2005 From: glingl at aon.at (Gregor Lingl) Date: Sun Mar 20 20:15:19 2005 Subject: [Tutor] primes (generator) Message-ID: <423DCC6B.3050709@aon.at> Karl Pfl?sterer schrieb: > On 19 Mrz 2005, glingl@aon.at wrote: > > [Code] > >>Maybe sombody likes... > > > I did it ... : > > def sieve (max): > max = max + 1 > border = round(max**0.5) > nums = range(0, max) > nums[0] = nums[1] = None > for p in nums: > if p: > if p >= border: break > for i in xrange(p+p, max, p): > nums[i] = None > return filter(None, nums) > Hi Karl! The following variation of your sieve, using extended slice assignment seems to be sgnificantly faster. Try it out, if you like. def sieve (maximum): limit = int(maximum**0.5) nums = range(maximum+1) nums[0] = nums[1] = None for p in nums: if p: if p > limit: break nums[p*p:maximum+1:p] = [False]*(1-p+maximum//p) return filter(None, nums) Regards Gregor > > > Karl From cyresse at gmail.com Sun Mar 20 20:36:46 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 20 20:36:49 2005 Subject: [Tutor] Re: [Pythoncard-users] global menubar In-Reply-To: <OFA058702F.D80023E4-ON86256FCA.00631477-86256FCA.00635C46@omsdal.com> References: <003401c52d72$15f72fd0$93c28651@xp> <OFA058702F.D80023E4-ON86256FCA.00631477-86256FCA.00635C46@omsdal.com> Message-ID: <f2ff2d05032011364d214689@mail.gmail.com> On Sun, 20 Mar 2005 12:05:11 -0600, brad.allen@omsdal.com <brad.allen@omsdal.com> wrote: > > Thanks for the thoughts. I noticed that you didn't post directly to the > PythonCard users list, Sorry, that was my bad, I cc'ed to the tutor list instead of the Pythoncard list. -- '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. From igor.r at vodafone.net Sun Mar 20 20:38:40 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Sun Mar 20 20:38:52 2005 Subject: [Tutor] Changing Keyboard output Message-ID: <000a01c52d84$6ba781c0$c000a8c0@ARCISDESKTOP> Hi, I am totally new to Python and still learning. I am looking for a way to change keyboard output within Tkinter widget - for example, say I press "p" and I want it to come out as "t". Could anyone possibly point me in the right direction? Igor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050320/8c517fb8/attachment.htm From klappnase at freenet.de Sun Mar 20 21:18:16 2005 From: klappnase at freenet.de (Michael Lange) Date: Sun Mar 20 21:14:55 2005 Subject: [Tutor] Changing Keyboard output In-Reply-To: <000a01c52d84$6ba781c0$c000a8c0@ARCISDESKTOP> References: <000a01c52d84$6ba781c0$c000a8c0@ARCISDESKTOP> Message-ID: <20050320211816.17af3815.klappnase@freenet.de> On Sun, 20 Mar 2005 19:38:40 -0000 "Igor Riabtchuk" <igor.r@vodafone.net> wrote: > Hi, > > I am totally new to Python and still learning. > > I am looking for a way to change keyboard output within Tkinter widget - for example, say I press "p" and I want it to come out as "t". > > Could anyone possibly point me in the right direction? > > Igor You can use the widget's bind() method to replace the standard callback with a new one: from Tkinter import * root = Tk() e = Entry(r) e.pack() def PtoT(event): e.insert('insert', 't') return 'break' e.bind('<p>', PtoT) the "return 'break'" statement prevents the event from being propagated to Tk's standard event handler; without it both "p" and "t" would be inserted into the Entry. I hope this helps Michael From shaleh at speakeasy.net Sun Mar 20 22:39:08 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sun Mar 20 22:40:57 2005 Subject: [Tutor] primes (generator) In-Reply-To: <423DCC6B.3050709@aon.at> References: <423DCC6B.3050709@aon.at> Message-ID: <423DED7C.9030704@speakeasy.net> Gregor Lingl wrote: > > The following variation of your sieve, using > extended slice assignment seems to > be sgnificantly faster. Try it out, if you like. > Here are the numbers: Primes 1 - 1,000,000 timing: extendedSliceSieve: 0.708388 seconds listPrimes: 0.998758 seconds karlSieve: 1.703553 seconds primeConciseOptimized: 5.133922 seconds setSieve: 7.564576 seconds primeConcise: 1644.683214 seconds --> 27 minutes 24 seconds if __name__ == '__main__': # setup timers as a list of tuples (name, timeit instance) results = [] longest = 0 for t in timers: result = t[1].timeit(1) longest = max(longest, len(t[0])) results.append((t[0], result)) results.sort(lambda x, y: cmp(x[1], y[1])) print "Primes 1 - 1,000,000 timing:" format_str = "%%%ds: %%f seconds" % longest for i in results: print format_str % i From matthew.williams at cancer.org.uk Sun Mar 20 23:05:23 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Sun Mar 20 23:05:04 2005 Subject: [Tutor] Filtering a String Message-ID: <1111356323.5248.29.camel@localhost.localdomain> Dear List, I'm trying to filter a file, to get rid of some characters I don't want in it. I've got the "Python Cookbook", which handily seems to do what I want, but: a) doesn't quite and b) I don't understand it I'm trying to use the string.maketrans() and string.translate(). From what I've read (in the book and the Python Docs), I need to make a translation table, (using maketrans) and then pass the table, plus and optional set of characters to be deleted, to the translate() function. I've tried: #!/usr/bin/python import string test="1,2,3,bob,%,)" allchar=string.maketrans('','') #This aiming to delete the % and ): x=''.translate(test,allchar,"%,)") but get: TypeError: translate expected at most 2 arguments, got 3 Please could someone explain this to me (slowly). As a measure of my slowness: This is my first programming language I couldn't get the tutor list to work for ages - until I realised I was sending all the desperate pleas for help to tutor-request. Perhaps there is no hope...... Matt Williams From kent37 at tds.net Sun Mar 20 23:04:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 20 23:05:27 2005 Subject: [Tutor] Why is this not an error? In-Reply-To: <200503201921.00540.hameed.u.khan@gmail.com> References: <20050320134624.70681.qmail@web54410.mail.yahoo.com> <200503201921.00540.hameed.u.khan@gmail.com> Message-ID: <423DF38B.20709@tds.net> Hameed U. Khan wrote: > This else is the part of the for loop. And the statements in this else will be > executed if your for loop will complete all of its iterations. if you want > this else with 'if' statement then remove the for loop. Or if you want the for loop to be part of the if then indent the for: if z in x: print 'found:', z for i in x: print 'in the loop with', i else: print 'not found:', z Remember - indentation is syntactically significant in Python! From keridee at jayco.net Sun Mar 20 23:25:25 2005 From: keridee at jayco.net (Jacob S.) Date: Sun Mar 20 23:24:43 2005 Subject: [Tutor] Filtering a String References: <1111356323.5248.29.camel@localhost.localdomain> Message-ID: <003001c52d9b$bbc0c240$695428cf@JSLAPTOP> > I'm trying to filter a file, to get rid of some characters I don't want > in it. The easiest thing to do is use the string method replace. For example: char = "1" a = open("Myfile.txt","r") b = a.read() a.close() b = b.replace(char,"") a = open("Myfile.txt","w") ## Notice "w" so we can replace the file a.write(b) a.close > I've got the "Python Cookbook", which handily seems to do what I want, > but: > > a) doesn't quite and > b) I don't understand it > > I'm trying to use the string.maketrans() and string.translate(). From > what I've read (in the book and the Python Docs), I need to make a > translation table, (using maketrans) and then pass the table, plus and > optional set of characters to be deleted, to the translate() function. I've never messed with translate() etc... > I've tried: > > #!/usr/bin/python > import string > test="1,2,3,bob,%,)" > allchar=string.maketrans('','') > #This aiming to delete the % and ): > x=''.translate(test,allchar,"%,)") > > but get: > TypeError: translate expected at most 2 arguments, got 3 Ah, your test uses more than one replace factor. So, this should do what you want.. ##### x = " [ text ] " # Replace this with your file output -- possibly fileobject.read() def removechar(stri, char): return stri.replace(char,"") test = "1,2,3,bob,%,)" allchar = test.split(",") # this makes allchar = ['1','2','3','bob','%',')'] for char in allchar: x = removechar(x,char) ###### Remember, if you need help--just ask. Oh, and don't give up hope! HTH, Jacob From galepsus at gmail.com Sun Mar 20 23:45:40 2005 From: galepsus at gmail.com (Archie Maskill) Date: Sun Mar 20 23:45:42 2005 Subject: [Tutor] Filtering a String In-Reply-To: <1111356323.5248.29.camel@localhost.localdomain> References: <1111356323.5248.29.camel@localhost.localdomain> Message-ID: <5a314f2505032014451d56db7@mail.gmail.com> On Sun, 20 Mar 2005 22:05:23 +0000, Matt Williams <matthew.williams@cancer.org.uk> wrote: > I've tried: > > #!/usr/bin/python > import string > test="1,2,3,bob,%,)" > allchar=string.maketrans('','') > #This aiming to delete the % and ): > x=''.translate(test,allchar,"%,)") > > but get: > TypeError: translate expected at most 2 arguments, got 3 According to Python's builtin help on the translate string method : >>> help(''.translate) translate(...) S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. So it was all ok up to the last line, where instead of : x=''.translate(test,allchar,"%,)") you want : x = test.translate(allchar,"%,)") This will get rid of the commas as well, which you don't mention in the comment on the preceeding line, so it's possible you need this instead : x = test.translate(allchar,"%)") - Archie From shaleh at speakeasy.net Sun Mar 20 23:51:49 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sun Mar 20 23:53:28 2005 Subject: [Tutor] Filtering a String In-Reply-To: <1111356323.5248.29.camel@localhost.localdomain> References: <1111356323.5248.29.camel@localhost.localdomain> Message-ID: <423DFE85.6060003@speakeasy.net> Matt Williams wrote: > Dear List, > > I'm trying to filter a file, to get rid of some characters I don't want > in it. > > I've got the "Python Cookbook", which handily seems to do what I want, > but: > > a) doesn't quite and > b) I don't understand it > > I'm trying to use the string.maketrans() and string.translate(). From > what I've read (in the book and the Python Docs), I need to make a > translation table, (using maketrans) and then pass the table, plus and > optional set of characters to be deleted, to the translate() function. > > I've tried: > > #!/usr/bin/python > import string > test="1,2,3,bob,%,)" > allchar=string.maketrans('','') > #This aiming to delete the % and ): > x=''.translate(test,allchar,"%,)") > > but get: > TypeError: translate expected at most 2 arguments, got 3 > > Please could someone explain this to me (slowly). Here is an updated version. #!/usr/bin/python import string test = "1,2,3,bob,%,)" allchar = string.maketrans('','') #This aiming to delete the % and ): x = test.translate(allchar,"%,)") print x # end x = test.translate() rather than x = ''.translate() is the key. You want to call the translate method of the test string. Your code could have worked by doing 'x = string.translate(test, allchar, "blah")' which uses the translate function in the module named 'string'. Confusing because the names are the same. You received an error because ''.translate() only needs the table and the deletechars string. I personally avoid empty string methods (''.translate, ''.join, etc) because they can be visually confusing and definitely confound the new python programmers. A comment on style. Use spaces around assignments -- x=5 should be x = 5. From alan.gauld at freenet.co.uk Sun Mar 20 23:58:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Mar 20 23:57:43 2005 Subject: [Tutor] Changing Keyboard output References: <000a01c52d84$6ba781c0$c000a8c0@ARCISDESKTOP> Message-ID: <006101c52da0$6002f130$93c28651@xp> > I am looking for a way to change keyboard output within > Tkinter widget - for example, say I press "p" and I want > it to come out as "t". > > Could anyone possibly point me in the right direction? Take a look at the Event Driven programming topic in my tutor, it covers reading keyboard input in Tkinter. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From glingl at aon.at Mon Mar 21 01:13:34 2005 From: glingl at aon.at (Gregor Lingl) Date: Mon Mar 21 01:10:51 2005 Subject: [Tutor] primes - sieve of odds In-Reply-To: <423DED7C.9030704@speakeasy.net> References: <423DCC6B.3050709@aon.at> <423DED7C.9030704@speakeasy.net> Message-ID: <423E11AE.10400@aon.at> Hi Sean! Thanks for your measurements. In the meantime I did another amendment, leaving out the even numbers from the sieve. It goes like this: def sieve(maximum): nums = range(3, maximum+1, 2) for p in nums: if p: if p*p > maximum: break start = (p*p-2)//2 nums[start::p] = [False]*(1+((maximum-3)//2-start)//p) return [2] + filter(None, nums) Perhaps not very elegant. But approximately twice as fast as the former version. Best wishes, Gregor Sean Perry schrieb: > Gregor Lingl wrote: > >> >> The following variation of your sieve, using >> extended slice assignment seems to >> be sgnificantly faster. Try it out, if you like. >> > > Here are the numbers: > Primes 1 - 1,000,000 timing: > extendedSliceSieve: 0.708388 seconds > listPrimes: 0.998758 seconds > karlSieve: 1.703553 seconds > primeConciseOptimized: 5.133922 seconds > setSieve: 7.564576 seconds > primeConcise: 1644.683214 seconds --> 27 minutes 24 seconds > > if __name__ == '__main__': > # setup timers as a list of tuples (name, timeit instance) > > results = [] > longest = 0 > for t in timers: > result = t[1].timeit(1) > longest = max(longest, len(t[0])) > results.append((t[0], result)) > > results.sort(lambda x, y: cmp(x[1], y[1])) > > print "Primes 1 - 1,000,000 timing:" > > format_str = "%%%ds: %%f seconds" % longest > for i in results: > print format_str % i > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From dyoo at hkn.eecs.berkeley.edu Mon Mar 21 02:01:13 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 21 02:01:20 2005 Subject: [Tutor] Prepend to a list? (fwd) In-Reply-To: <Pine.LNX.4.44.0503191918510.2283-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503201643210.10873-100000@hkn.eecs.berkeley.edu> > I ended up changing my approach so that it won't require appending to > the list, but it's good to know anyway because I'm sure it will come up > in the future. I'm sort of surprised there isn't a prepend() method for > lists, but I'm sure there's a reason. Hi Jay, The interface of a data structure can encourage certain ways of programming, and discourage others. Python lists don't support fast prependings, so that's why its not a standard method in the API. > Most of the data is small sets, but fairly frequently run, so I'm > looking for more efficient code in terms of CPU cycles on the server. In > such a case, is one of the approaches better, or are they fairly equal? If your data set is small, it probably don't matter. *grin* But yeah, they do perform differently. For your application, you probably shouldn't worry about it unless you notice sluggishness, in which case you should "profile" first to see where the time sink is. But just to hint at what makes prepend expensive, let's imagine that there's a list of people waiting in line for new Star Wars movie: ['luke', 'leia', 'han'] And let's say that there's an annoying twerp that pushes everyone off to the side, just to get in front of everyone else. The jerk shoves everyone off balance. That push forces everyone off to the side by one: [None, 'luke', 'leia', 'han'] And then, having room to squat, the malefactor plonks down. ['jarjar', 'luke', 'leia', 'han'] When push comes to shove, what's "costly" is the movement of the folks who are already in line. There were three people in line earlier, and prepending 'jarjar' forces everyone in line to shift around by one. And in general, prepending on a Python list is more costly than appending because it's more disruptive to the existing data in the list. Does this make sense so far? I have to point out that the expense of an operation depends on the particular data structure we use to represent things. Python lists (a.k.a. "arrays") can give us fast appends, fast random access, but slow prepends. There are other structures that have different compromises. This stuff is the heart of studying computer algorithms, so if you're really interested in this, you might be interested in a book like "Introduction to Algorithms": http://theory.lcs.mit.edu/~clr/ If you have more questions, please feel free to ask! From brad.allen at omsdal.com Sun Mar 20 19:05:11 2005 From: brad.allen at omsdal.com (brad.allen@omsdal.com) Date: Mon Mar 21 08:30:00 2005 Subject: [Tutor] Re: [Pythoncard-users] global menubar In-Reply-To: <003401c52d72$15f72fd0$93c28651@xp> Message-ID: <OFA058702F.D80023E4-ON86256FCA.00631477-86256FCA.00635C46@omsdal.com> Thanks for the thoughts. I noticed that you didn't post directly to the PythonCard users list, so you might not be reading the discussion that followed. It sounds like MDI applications are deprecated under Windows, so I'm going to go with a single tabbed window with some small menuless child windows and dialogs. On the Mac side, it appears that the MDI style approach does work naturally in PythonCard. "Alan Gauld" <alan.gauld@freenet.co.uk> wrote on 03/20/2005 11:27:23 AM: > > > To clarify, what I'm trying to accomplish here is an overarching > application > > > window which contains other windows. At least, that's what it > would look > > > like under Windows. > > You mean this would be an MDI Application? > There is usually a special class or attribute to support MDI in theGUI > toolkits. > Searching for MDI in the help/FAQ might help locate what you need? > > > > On a Mac, it would just be an menubar globally available > > > and applicable independent of which window happened to be active. > > In other words a standard MacOS style aplication. > > You also omit X WIndows (Linux, BSD, Solaris etc) from your list but > in those the menu locatio is a user preference and is controlled by > the Window Manager chosen by the user. This raises an interesting > issue around GUI design. One objective should be to "go with the > norm", > that is to follow the paradigm of the underlying platform, and that > includes the placement of controls. Users expect to find the controls, > including menus, in the same place each time, to do otherwise > will invariably make you application less user-friendly. The GUI > toolkits do this for us if we stick to the norm, so there needs > to be a very good reason to depart from the standard layout. > > > > I'm not clear on how to accomplish this in PythonCard. > > Me neither! But its based on wxWidgets so it might be worth > trawling around there for clues. > > Alan G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050320/138edac1/attachment.html From shitizb at yahoo.com Mon Mar 21 08:38:41 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Mar 21 08:38:45 2005 Subject: [Tutor] print command Message-ID: <20050321073842.49277.qmail@web53801.mail.yahoo.com> Now this is so basic, i am feeling sheepish asking about it. I am outputting to the terminal, how do i use a print command without making it jump no newline after execution, which is the default behaviour in python. To clarify: print 1 print 2 print 3 I want output to be 123 whereas by default it is 1 2 3 . Shitiz __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From lutz.horn at gmx.de Mon Mar 21 08:57:48 2005 From: lutz.horn at gmx.de (Lutz Horn) Date: Mon Mar 21 08:57:50 2005 Subject: [Tutor] print command References: <20050321073842.49277.qmail@web53801.mail.yahoo.com> Message-ID: <14654.1111391868@www4.gmx.net> Hi, > To clarify: > > print 1 > print 2 > print 3 > > I want output to be > > 123 >>> l = [1, 2 3] >>> i = int("".join(map(str, l))) >>> print i, type(i) 123 <type 'int'> If you don't care about the blanks, you can use >>> print 1, 2, 3 1 2 3 Lutz -- pub 1024D/6EBDA359 1999-09-20 Lutz Horn <lutz.horn@gmx.de> 438D 31FC 9300 CED0 1CDE A19D CD0F 9CA2 6EBD A359 http://purl.oclc.org/NET/lutz.horn DSL Komplett von GMX +++ Supergünstig und stressfrei einsteigen! AKTION "Kein Einrichtungspreis" nutzen: http://www.gmx.net/de/go/dsl From kent37 at tds.net Mon Mar 21 11:57:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 21 11:57:35 2005 Subject: [Tutor] print command In-Reply-To: <20050321073842.49277.qmail@web53801.mail.yahoo.com> References: <20050321073842.49277.qmail@web53801.mail.yahoo.com> Message-ID: <423EA898.708@tds.net> Shitiz Bansal wrote: > Now this is so basic, i am feeling sheepish asking > about it. > I am outputting to the terminal, how do i use a print > command without making it jump no newline after > execution, which is the default behaviour in python. > To clarify: > > print 1 > print 2 > print 3 > > I want output to be > > 123 You can suppress the newline by ending the print statement with a comma, but you will still get the space: print 1, print 2, print 3 will print 1 2 3 You can get full control of the output by using sys.stdout.write() instead of print. Note the arguments to write() must be strings: import sys sys.stdout.write(str(1)) sys.stdout.write(str(2)) sys.stdout.write(str(3)) sys.stdout.write('\n') Or you can accumulate the values into a list and print the list as Lutz has suggested: l = [] l.append(1) l.append(2) l.append(3) print ''.join(map(str, l)) where map(str, l) generates a list of strings by applying str() to each element of l: >>> map(str, l) ['1', '2', '3'] and ''.join() takes the resulting list and concatenates it into a single string with individual elements separated by the empty string ''. Kent From matthew.williams at cancer.org.uk Mon Mar 21 12:57:21 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Mon Mar 21 12:57:29 2005 Subject: [Tutor] Accessing List items Message-ID: <1111406241.2922.11.camel@dhcp0320.acl.icnet.uk> Dear List, Thanks for the help with the previous problem - now all solved! I have a question about accessing lists. I'm trying to do something to each item in a list, and then assign it back into the list, overwriting the old value. However, the first loop here doesn't work, whereas the second loop does - but is very ugly. x = "200% inv_nodes=0-2 node_caps=no" y=x.split() for i in y: i="z" print y for i in range(len(y)): y[i]="z" print y Surely there must be a better way than this ? Thanks, Matt From maxnoel_fr at yahoo.fr Mon Mar 21 13:13:56 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Mar 21 13:13:58 2005 Subject: [Tutor] Accessing List items In-Reply-To: <1111406241.2922.11.camel@dhcp0320.acl.icnet.uk> References: <1111406241.2922.11.camel@dhcp0320.acl.icnet.uk> Message-ID: <2077a4008c0cfa0565df605027e2fe5f@yahoo.fr> On Mar 21, 2005, at 12:57, Matt Williams wrote: > for i in range(len(y)): > y[i]="z" > print y > > Surely there must be a better way than this ? Sounds like a job for... list comprehensions! (cue cheesy superhero music) y = ["z" for i in y] -- 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?" -- 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?" From kedart at gmail.com Mon Mar 21 16:01:17 2005 From: kedart at gmail.com (kedar thangudu) Date: Mon Mar 21 16:01:21 2005 Subject: [Tutor] reg: readline module Message-ID: <f3c4328a050321070127d6b691@mail.gmail.com> hi, I hav been working on python in developing pyshell... I am using python readline module to for the command line.. Can u help me with how to replace or erase the current readline line-buffer.. the readline module just provides a insert_text func which is appending the text to the line-buffer.. but i want to replace the contents of the line-buffer to something else.. how can i do this ? regards kedar From bill.mill at gmail.com Mon Mar 21 20:48:02 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon Mar 21 20:48:08 2005 Subject: [Tutor] Accessing List items In-Reply-To: <1111406241.2922.11.camel@dhcp0320.acl.icnet.uk> References: <1111406241.2922.11.camel@dhcp0320.acl.icnet.uk> Message-ID: <797fe3d405032111484327d12e@mail.gmail.com> On Mon, 21 Mar 2005 11:57:21 +0000, Matt Williams <matthew.williams@cancer.org.uk> wrote: > Dear List, > > Thanks for the help with the previous problem - now all solved! > > I have a question about accessing lists. I'm trying to do something to > each item in a list, and then assign it back into the list, overwriting > the old value. However, the first loop here doesn't work, whereas the > second loop does - but is very ugly. > > x = "200% inv_nodes=0-2 node_caps=no" > y=x.split() > > for i in y: > i="z" > print y > > for i in range(len(y)): > y[i]="z" > print y > > Surely there must be a better way than this ? As Max pointed out, listcomps are the best way to do it. Another way, which is useful in more complicated scenarios: for i, elt in enumerate(y): ...do something complex with elt... y[i] = elt *** technical yapping about why your first loop doesn't work is below; read it only if you're interested - don't get scared, you don't really need to know it *** The reason that the first list doesn't work is that a string is an immutable object. Thus, when you change it, you basically just tell python to rebind the local name "i" from one immutable object (a string) to another immutable element (another string). This has no effect on the list. If, however, "i" is a mutable object (such as a list or a dict), then your loop works as expected: >>> y = [[1]] >>> for i in y: i.append(2) ... >>> y [[1, 2]] In this case, modifying the list "i" works in-place by modifying the actual mutable object. The change is reflected in the list "y", because the actual object it encloses has changed. I hope this makes sense, and maybe clears up a little of your confusion about variables in Python. It is a bit confusing, even for experienced pythonistas, so ask questions if you don't get it (and you're interested). If not, you can get away without worrying about it for the most part. Peace Bill Mill bill.mill at gmail.com From alan.gauld at freenet.co.uk Mon Mar 21 21:01:29 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 21 21:01:13 2005 Subject: [Tutor] Re: [Pythoncard-users] global menubar References: <OFA058702F.D80023E4-ON86256FCA.00631477-86256FCA.00635C46@omsdal.com> Message-ID: <009301c52e50$c63d61a0$93c28651@xp> > Thanks for the thoughts. I noticed that you didn't post directly to the > PythonCard users list, so you might not be reading the discussion Nope, I just replied to a message on Tutor... > followed. It sounds like MDI applications are deprecated under Windows, Under XP thats true, in earlier versions they were a means of minimising memory usage etc by sharing common resources. > On the Mac side, it appears that the MDI style approach does work > naturally in PythonCard. MDI is rarely seen in Mac apps but they do all have a single shared menubar at the top of the screen. That is true of all Mac apps regardless of the numberof windows open. Alan G. From alan.gauld at freenet.co.uk Mon Mar 21 21:07:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Mar 21 21:08:04 2005 Subject: [Tutor] print command References: <20050321073842.49277.qmail@web53801.mail.yahoo.com> <423EA898.708@tds.net> Message-ID: <009c01c52e51$a26eb480$93c28651@xp> > You can get full control of the output by using sys.stdout.write() instead of print. Note the > arguments to write() must be strings: > > import sys > sys.stdout.write(str(1)) > sys.stdout.write(str(2)) > sys.stdout.write(str(3)) > sys.stdout.write('\n') > > Or you can accumulate the values into a list and print the list as Lutz has suggested: Or for an easier technique than join/split, use a print format string: > l = [] > l.append(1) > l.append(2) > l.append(3) fmtString = "%s" * len(l) print fmtString % tuple(l) HTH, Alan G. From magoldfish at gmail.com Mon Mar 21 22:33:20 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Mon Mar 21 22:33:25 2005 Subject: [Tutor] automatically extending PYTHONPATH? Message-ID: <5e183f3d050321133333b4aa12@mail.gmail.com> I am using Python 2.4/IDLE on WinXP. I organize my sourcefiles in a directory tree, similar to the convention used in Java. When I create a new subdirectory, though, I have to either (i) manually edit my PYTHONPATH environment variable, or (ii) do a sys.append() in IDLE for the new scripts to be visible. Is there a workaround for this? For example, is there a setting in IDLE of Python to specify a root source directory and have all subdirectories added automatically? Hope this makes sense, and that a brilliant mind has a quick solution! Thanks, Marcus From magoldfish at gmail.com Mon Mar 21 22:53:54 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Mon Mar 21 22:53:57 2005 Subject: [Tutor] import statements in functions? Message-ID: <5e183f3d05032113532bd551e1@mail.gmail.com> Is there a convention to be considered for deciding if import statements should be included in a function body? For example, which of these two module layouts would be preferable: # --- MyModule1.py ----- import foo1, foo2, foo3 import foo_special # several coherent functions here def specialFunction(): doSomethingSpecial() or the "embedded import" version: # --- MyModule2.py ----- import foo1, foo2, foo3 import foo_rare # several coherent functions here def specialFunction(): import foo_special doSomethingSpecial() Also, does the choice have any impact on performance/space/etc.? And will the import function get called each time (and possibly ignored) in the second version? The reason I consider the second form is that the module foo_special is only used by the code in specialFunction(), and detracts (IMHO) from understanding the rest of the code in the module. Thanks, Marcus From cyresse at gmail.com Mon Mar 21 23:00:01 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Mar 21 23:00:03 2005 Subject: [Tutor] automatically extending PYTHONPATH? In-Reply-To: <5e183f3d050321133333b4aa12@mail.gmail.com> References: <5e183f3d050321133333b4aa12@mail.gmail.com> Message-ID: <f2ff2d050321140034803ca8@mail.gmail.com> No automatic method, afaik, but why not just do an os.walk() in conjunction with sys.append()? Regards, Liam Clarke On Mon, 21 Mar 2005 16:33:20 -0500, Marcus Goldfish <magoldfish@gmail.com> wrote: > I am using Python 2.4/IDLE on WinXP. I organize my sourcefiles in a > directory tree, similar to the convention used in Java. When I create > a new subdirectory, though, I have to either (i) manually edit my > PYTHONPATH environment variable, or (ii) do a sys.append() in IDLE for > the new scripts to be visible. Is there a workaround for this? For > example, is there a setting in IDLE of Python to specify a root source > directory and have all subdirectories added automatically? > > Hope this makes sense, and that a brilliant mind has a quick solution! > > Thanks, > Marcus > _______________________________________________ > 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. From magoldfish at gmail.com Mon Mar 21 23:06:28 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Mon Mar 21 23:06:31 2005 Subject: [Tutor] python console, IDLE startup scripts Message-ID: <5e183f3d05032114064ef0226f@mail.gmail.com> Is there a special startup script the command-line python IDE and/or IDLE use? As per Liam's response to my previous post, I would like to use os.walk() to automatically set my sys.path() variable... Marcus From bvande at po-box.mcgill.ca Mon Mar 21 23:42:56 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Mar 21 23:43:22 2005 Subject: [Tutor] python console, IDLE startup scripts In-Reply-To: <5e183f3d05032114064ef0226f@mail.gmail.com> References: <5e183f3d05032114064ef0226f@mail.gmail.com> Message-ID: <423F4DF0.9030709@po-box.mcgill.ca> Marcus Goldfish said unto the world upon 2005-03-21 17:06: > Is there a special startup script the command-line python IDE and/or > IDLE use? As per Liam's response to my previous post, I would like to > use os.walk() to automatically set my sys.path() variable... > > Marcus > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Marcus, I've not done so myself, but you can put custom initialization code into a module named sitecustomize.py. See <http://www.python.org/doc/2.4/lib/module-site.html> for more details. Best, Brian vdB From shaleh at speakeasy.net Mon Mar 21 23:42:16 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Mon Mar 21 23:44:06 2005 Subject: [Tutor] import statements in functions? In-Reply-To: <5e183f3d05032113532bd551e1@mail.gmail.com> References: <5e183f3d05032113532bd551e1@mail.gmail.com> Message-ID: <423F4DC8.80202@speakeasy.net> Marcus Goldfish wrote: > Is there a convention to be considered for deciding if import > statements should be included in a function body? For example, which > of these two module layouts would be preferable: > imports are cached. So once it is imported, it stays imported. > The reason I consider the second form is that the module foo_special > is only used by the code in specialFunction(), and detracts (IMHO) > from understanding the rest of the code in the module. > and this is a good reason why you would perform the import inside the function. From alan.gauld at freenet.co.uk Tue Mar 22 00:12:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 22 00:12:34 2005 Subject: [Tutor] import statements in functions? References: <5e183f3d05032113532bd551e1@mail.gmail.com> Message-ID: <00c101c52e6b$8285eac0$93c28651@xp> > Is there a convention to be considered for deciding if import > statements should be included in a function body? The convention is for all imports to be at the top of a module. > def specialFunction(): > import foo_special > doSomethingSpecial() BUt I copnfess I do occasionally use this form under certain conditions, see below... > Also, does the choice have any impact on performance/space/etc.? Marginally, because imports do take some time. If the import is not normally going to be needed hiding it inside a function definition can save a little bit of time. > will the import function get called each time (and possibly ignored) > in the second version? Yes it will but because Python has already seen it it will not be a big impact - especially if the function is itself rarely used. > The reason I consider the second form is that the module foo_special > is only used by the code in specialFunction(), and detracts (IMHO) > from understanding the rest of the code in the module. And thats exactly when I would use the embedded import - it hides some complexity, - slightly increases performamnce and - has little impact when called becauiuse such calls are rare. A personal perspective :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Mar 22 00:47:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 00:47:51 2005 Subject: [Tutor] automatically extending PYTHONPATH? In-Reply-To: <5e183f3d050321133333b4aa12@mail.gmail.com> References: <5e183f3d050321133333b4aa12@mail.gmail.com> Message-ID: <423F5D21.5060100@tds.net> You can create a .pth file in site-packages. See these links for details: http://docs.python.org/inst/search-path.html#SECTION000410000000000000000 http://bob.pythonmac.org/archives/2005/02/06/using-pth-files-for-python-development/ As Liam suggested, you can walk the dir yourself and modify sys.path. The walk code could be in a site-customize.py file in site-packages so it will be run automatically every time Python starts up. Finally, you could put your packages directly in site-packages, then they will always be available. Kent Marcus Goldfish wrote: > I am using Python 2.4/IDLE on WinXP. I organize my sourcefiles in a > directory tree, similar to the convention used in Java. When I create > a new subdirectory, though, I have to either (i) manually edit my > PYTHONPATH environment variable, or (ii) do a sys.append() in IDLE for > the new scripts to be visible. Is there a workaround for this? For > example, is there a setting in IDLE of Python to specify a root source > directory and have all subdirectories added automatically? > > Hope this makes sense, and that a brilliant mind has a quick solution! > > Thanks, > Marcus > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Mar 22 00:54:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 00:54:37 2005 Subject: [Tutor] automatically extending PYTHONPATH? In-Reply-To: <423F5D21.5060100@tds.net> References: <5e183f3d050321133333b4aa12@mail.gmail.com> <423F5D21.5060100@tds.net> Message-ID: <423F5EB8.1070904@tds.net> Kent Johnson wrote: > As Liam suggested, you can walk the dir yourself and modify sys.path. > The walk code could be in a site-customize.py file in site-packages so > it will be run automatically every time Python starts up. Oops, as Brian correctly pointed out, the correct file name is sitecustomize.py. Anything you put in this file will be run at startup. The file can be anywhere on the Python path; site-packages is a good place for it. Kent From pythonlists at hardcorr.net Tue Mar 22 05:57:54 2005 From: pythonlists at hardcorr.net (Colin Corr) Date: Tue Mar 22 05:57:47 2005 Subject: [Tutor] Help with unnamed arguments in a merge function In-Reply-To: <4237E434.9030304@po-box.mcgill.ca> References: <1110955096.5190.47.camel@pythondev.hardcorr.net> <4237E434.9030304@po-box.mcgill.ca> Message-ID: <1111467474.4742.4.camel@pythondev.hardcorr.net> On Wed, 2005-03-16 at 02:45 -0500, Brian van den Broek wrote: > Colin Corr said unto the world upon 2005-03-16 01:38: > > Greetings Tutors, > > > > I am having some difficulties with the concept of functions which can > > accept an unnamed number of arguments. Specifically, when trying to > > write a function that deals with an unnamed number of dictionaries. I > > want to be able to merge any number of dictionaries, while preserving > > the values (ie. cannot use update()). > > > > ~I would appreciate any help that can point in me in the right > > direction, without directly providing me the answer.~ > > > > I understand how to accomplish this task with named arguments: > > > > def mergedicts(firstdict, seconddict): > > '''merges two dictionaries into a single dictionary, and converts > > duplicate key values to a list''' > > newdict = firstdict.copy() > > for key in seconddict.keys(): > > if key in firstdict.keys(): > > newdict[key] = firstdict[key], seconddict[key] > > newdict[key] = list(newdict[key]) > > else: > > newdict[key] = seconddict[key] > > > > return newdict > > > > > > dict1 = {'1':'a','2':'b','3':'c'} > > dict2 = {'4':'d','5':'e','6':'f','1':'g'} > > somedicts1 = mergedicts(dict1,dict2) > > print somedicts1 > > > > #returns: {'1': ['a', 'g'], '3': 'c', '2': 'b', '5': 'e', '4': 'd', '6': > > 'f'} > > > > I also think I understand how to use unnamed arguments to merge lists: > > > > def mergelists(*somelists): > > '''merges multiple lists into a single list and consolidates lists > > elements''' > > mergedict = {} > > for element in somelists: > > for unique in element: > > mergedict[unique] = 1 > > combolist = mergedict.keys() > > > > return combolist > > > > Where I am getting hung up is that, if I do this with unnamed arguments > > for dictionaries: > > > > def mergedicts(*somedicts): > > > > I get an: AttributeError: 'tuple' object has no attribute 'keys' > > > > > > However, I run into the same problem when trying with one named, and > > unnamed. > > > > def mergedicts2(firstdict,*somedicts): > > '''merges any number of dictionaries into a single dictionary, and > > converts duplicate key values to a list''' > > merged = firstdict.copy() > > for key in somedicts.keys(): > > if key in merged.keys(): > > merged[key] = merged[key], somedicts[key] > > merged[key] = list(merged[key]) > > else: > > merged[key] = somedicts[key] > > > > return merged > > > > Based on my understanding of how unnamed arguments work in functions: I > > think the dictionaries are being converted into a tuple of all of the > > dictionary values, and I cannot make a working copy of the first > > dictionary passed to the function, with the named example. Should I then > > unpack the resulting tuple into corresponding first,second,third... > > dictionaries for further processing? > > > > I am also wondering if this is even the right approach? Can this be done > > with only unnamed arguments, or do I at least need to name the first > > argument for the first reference dictionary, and then use an *unnamed > > for each additional dictionary? > > > > > > Thanks for any pointers, > > > > Colin > > Hi Colin, > > The problem is that somedicts is indeed a tuple -- having *args in a > function def collects non-positional, non-keyword arguments into a > tuple. So, in your function body, somedicts is a tuple of dicts. (It's > not that each dict is somehow tuplized.) > > See if this helps: > > >>> def print_values(*some_dicts): > ... for a_dict in some_dicts: > ... for key in a_dict: > ... print a_dict[key] > ... > >>> d1 = {1:2, 3:4} > >>> d2 = {1:42, 2:84} > >>> print_values(d1, d2) > 2 > 4 > 42 > 84 > > Best, > > Brian vdB > Hi Brian, Thanks for the quick response to my post. And my apologies for the delayed gratitude. You helped me to confirm my thoughts on the problem, and I now have a fresh perspective on how to solve it... though I haven't had the time to get back to it yet. Thanks again, Colin From cyresse at gmail.com Tue Mar 22 07:20:30 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 22 07:20:32 2005 Subject: [Tutor] OT - SQL methodology. Message-ID: <f2ff2d05032122206975d76a@mail.gmail.com> Hi, This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) After I've run an insert statement, should I get the new primary key (it's autoincrementing) by using PySQLite's cursor.lastrowid in a select statement, or is there a more SQLish way to do this? In the SQL books I've got, they always seem to have an optional select statement on the end of inserts/updates, and I was thinking maybe I could do it that way also, but I can't figure out a logical way of putting 'select primary_key from foo where primary_key value > every other primary_key value' into SQL parlance. I figure this would be a safe way of doing it, as the primary key is going to autoincrement ever upwards. Just don't know if I can do it. I'm trying to avoid firing off a select statement filled with the exact same info as I just inserted/updated, as the only unique column in my tables is the primary key. Any assistance that can be rendered, would be gratefully accepted. 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. From tony at tcapp.com Tue Mar 22 07:33:59 2005 From: tony at tcapp.com (Tony Cappellini) Date: Tue Mar 22 07:34:14 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable number of lists to zip() Message-ID: <6.1.2.0.0.20050321223148.01fc0010@mail.yamato.com> I have a program which currently passes 6 lists as arguments to zip(), but this could easily change to a larger number of arguments. Would someone suggest a way to pass a variable number of lists to zip() ? From shaleh at speakeasy.net Tue Mar 22 07:37:14 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 22 07:39:06 2005 Subject: [Tutor] OT - SQL methodology. In-Reply-To: <f2ff2d05032122206975d76a@mail.gmail.com> References: <f2ff2d05032122206975d76a@mail.gmail.com> Message-ID: <423FBD1A.1000707@speakeasy.net> Liam Clarke wrote: > Hi, > > This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) > > After I've run an insert statement, should I get the new primary key > (it's autoincrementing) by using PySQLite's cursor.lastrowid in a > select statement, or is there a more SQLish way to do this? > > In the SQL books I've got, they always seem to have an optional select > statement on the end of inserts/updates, and I was thinking maybe I > could do it that way also, but I can't figure out a logical way of > putting > > 'select primary_key from foo where primary_key value > every other > primary_key value' > select max(primary_key) from foo? From cyresse at gmail.com Tue Mar 22 07:45:09 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 22 07:45:11 2005 Subject: [Tutor] OT - SQL methodology. In-Reply-To: <423FBD1A.1000707@speakeasy.net> References: <f2ff2d05032122206975d76a@mail.gmail.com> <423FBD1A.1000707@speakeasy.net> Message-ID: <f2ff2d05032122456b000ced@mail.gmail.com> Brilliant, thanks Sean. On Mon, 21 Mar 2005 22:37:14 -0800, Sean Perry <shaleh@speakeasy.net> wrote: > Liam Clarke wrote: > > Hi, > > > > This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) > > > > After I've run an insert statement, should I get the new primary key > > (it's autoincrementing) by using PySQLite's cursor.lastrowid in a > > select statement, or is there a more SQLish way to do this? > > > > In the SQL books I've got, they always seem to have an optional select > > statement on the end of inserts/updates, and I was thinking maybe I > > could do it that way also, but I can't figure out a logical way of > > putting > > > > 'select primary_key from foo where primary_key value > every other > > primary_key value' > > > > select max(primary_key) from foo? > _______________________________________________ > 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. From shaleh at speakeasy.net Tue Mar 22 07:51:31 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 22 07:53:23 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable number of lists to zip() In-Reply-To: <6.1.2.0.0.20050321223148.01fc0010@mail.yamato.com> References: <6.1.2.0.0.20050321223148.01fc0010@mail.yamato.com> Message-ID: <423FC073.6080701@speakeasy.net> Tony Cappellini wrote: > > > I have a program which currently passes 6 lists as arguments to zip(), > but this could easily change to a larger number of arguments. > Would someone suggest a way to pass a variable number of lists to zip() ? > well, I would have said "apply(zip, (l1, l2, l3, ...))" but apply has been deprecated in 2.3. So how about this? arg_list = [] # fill up arg_list zipped = zip(*arg_list) ? From terryusa at comcast.net Tue Mar 22 09:15:00 2005 From: terryusa at comcast.net (Terry Johnson) Date: Tue Mar 22 09:16:42 2005 Subject: [Tutor] Very Newbie Message-ID: <20050322081500.GA4613@comcast.net> Hey to the tutors. I am a newbie of course about the only background is some old qbasic and very little c and perl. I have been wanting to write my own Web Server Program and when I saw a few times mentioned around python about it I am starting to check into it. If the is anyone who has done such a thing or can oint me in the best direction for learning about it please respond. Thanks in Advance -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20050322/18cbe15a/attachment.pgp From lutz.horn at gmx.de Tue Mar 22 09:23:40 2005 From: lutz.horn at gmx.de (Lutz Horn) Date: Tue Mar 22 09:23:42 2005 Subject: [Tutor] Very Newbie References: <20050322081500.GA4613@comcast.net> Message-ID: <17945.1111479820@www74.gmx.net> Hi, > I have been wanting to write > my own Web Server Program and when I saw a few times mentioned around > python about it I am starting to check into it. Take a look at the BaseHTTPServer[0] and the SimpleHTTPServer[1], both come with Python. [0] http://docs.python.org/lib/lib.html [1] http://docs.python.org/lib/module-SimpleHTTPServer.html -- pub 1024D/6EBDA359 1999-09-20 Lutz Horn <lutz.horn@gmx.de> 438D 31FC 9300 CED0 1CDE A19D CD0F 9CA2 6EBD A359 http://purl.oclc.org/NET/lutz.horn DSL Komplett von GMX +++ Supergünstig und stressfrei einsteigen! AKTION "Kein Einrichtungspreis" nutzen: http://www.gmx.net/de/go/dsl From shidai.liu at gmail.com Tue Mar 22 11:04:51 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Tue Mar 22 11:04:54 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable number of lists to zip() In-Reply-To: <423FC073.6080701@speakeasy.net> References: <6.1.2.0.0.20050321223148.01fc0010@mail.yamato.com> <423FC073.6080701@speakeasy.net> Message-ID: <33194d7305032202042a52fd85@mail.gmail.com> On Mon, 21 Mar 2005 22:51:31 -0800, Sean Perry <shaleh@speakeasy.net> wrote: > Tony Cappellini wrote: > > well, I would have said "apply(zip, (l1, l2, l3, ...))" but apply has > been deprecated in 2.3. > > So how about this? > > arg_list = [] > # fill up arg_list > zipped = zip(*arg_list) > I met a similar question. what if one has L = [[1,2],[3,4]], K = [100, 200] How to 'zip' a List like [[1,2,100], [3,4,200]]? -- With best wishes! Shidai From kent37 at tds.net Tue Mar 22 12:00:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 12:00:23 2005 Subject: [Tutor] OT - SQL methodology. In-Reply-To: <f2ff2d05032122206975d76a@mail.gmail.com> References: <f2ff2d05032122206975d76a@mail.gmail.com> Message-ID: <423FFAC0.2010703@tds.net> Liam Clarke wrote: > Hi, > > This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) Uh oh, you're in trouble if you think I'm an "advanced db guru" :-) > > After I've run an insert statement, should I get the new primary key > (it's autoincrementing) by using PySQLite's cursor.lastrowid in a > select statement, or is there a more SQLish way to do this? AFAIK there is no standard SQL way to do this, it is database-dependent. Python DB-API provides a portable interface using lastrowid; I would use that. You don't have to do another select, lastrowid is an attribute of the cursor itself. It calls the SQLite function sqlite_last_insert_rowid(). > In the SQL books I've got, they always seem to have an optional select > statement on the end of inserts/updates, and I was thinking maybe I > could do it that way also, but I can't figure out a logical way of > putting > > 'select primary_key from foo where primary_key value > every other > primary_key value' Use cursor.lastrowid, that's what it is for. Kent From kent37 at tds.net Tue Mar 22 12:09:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 12:09:08 2005 Subject: [Tutor] Very Newbie In-Reply-To: <20050322081500.GA4613@comcast.net> References: <20050322081500.GA4613@comcast.net> Message-ID: <423FFCCF.9000508@tds.net> Terry Johnson wrote: > Hey to the tutors. I am a newbie of course about the only background is > some old qbasic and very little c and perl. I have been wanting to write > my own Web Server Program and when I saw a few times mentioned around > python about it I am starting to check into it. If the is anyone who has > done such a thing or can oint me in the best direction for learning > about it please respond. Thanks in Advance There are many options for doing this. For a very simple server you might look at the standard library modules mentioned by Lutz; there is also a CGIHTTPServer module. You can also write CGI programs in Python for use with another web server such as Apache. Basic information about writing CGI's in Python is here: http://www.python.org/topics/web/basic-cgi.html Beyond that, the options multiply. This web page lists many of them: http://www.python.org/moin/WebProgramming Snakelets is one that is oriented toward ease of learning. Quixote, CherryPy and Twisted are probably the most popular. If you give us some more information we might be able to help you narrow down the options a little. Is this just for fun and learning or will it be a production site eventually? Do you want to create dynamic content or just serve static web pages? Ultimately though the selection is a matter of finding an alternative you are comfortable with. Kent From kent37 at tds.net Tue Mar 22 13:47:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 13:47:31 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable number of lists to zip() In-Reply-To: <33194d7305032202042a52fd85@mail.gmail.com> References: <6.1.2.0.0.20050321223148.01fc0010@mail.yamato.com> <423FC073.6080701@speakeasy.net> <33194d7305032202042a52fd85@mail.gmail.com> Message-ID: <424013DF.7070401@tds.net> Shidai Liu wrote: > On Mon, 21 Mar 2005 22:51:31 -0800, Sean Perry <shaleh@speakeasy.net> wrote: >>arg_list = [] >># fill up arg_list >>zipped = zip(*arg_list) >> > > I met a similar question. > what if one has L = [[1,2],[3,4]], K = [100, 200] What do you want to do with these lists? > How to 'zip' a List like [[1,2,100], [3,4,200]]? >>> zip(*[[1,2,100], [3,4,200]]) [(1, 3), (2, 4), (100, 200)] If that's not what you mean, please give an example of the input *and results* you want. Kent From rkashyap at sympatico.ca Tue Mar 22 14:58:06 2005 From: rkashyap at sympatico.ca (rkashyap@sympatico.ca) Date: Tue Mar 22 14:58:10 2005 Subject: [Tutor] Visual Python from Active State Message-ID: <20050322135806.GRSL1796.tomts6-srv.bellnexxia.net@mxmta.bellnexxia.net> Hi, I would like to get comments on Pros/Cons of using Visual Python. On another note, I have created a couple of MS Access databases for my work. At a recent conference, a lot of people have expressed an interest in using these as products for their own use. I am looking for ways to code a mechanism to have license keys for evaluation (30day/60day trial, and fully licensed version, etc.). I would like to use this opportunity to jump into using Python as the development platform if possible. Most of the work I do is in the MS Office Professional. regards, Ramkumar From vicki at stanfield.net Tue Mar 22 15:02:17 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Tue Mar 22 15:03:51 2005 Subject: [Tutor] Python cgi doesn't get data from html form as expected Message-ID: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> I have recently started doing cgi in Python and have run into a problem. I have an html form which has various widgets which accept data. I also have this in that html file: <form action="formdata.py" method="post"> formdata.py runs but doesn't seem to contain the data from the form. I'm not sure of the format for the for with regard to FieldStorage btw. Here is the contents of formdata.py: ---------------- #! /usr/bin/python import cgitb, os, sys cgitb.enable() import cgi print "Content-Type: text/html\n\n" print "<html><head></head><body>" form = cgi.FieldStorage() for each in form: print "each" print form['fname'].value, form['lname'].value #print "address:", form['addr'].value() print "</body></html>" ------------------ From mlasky1 at cox.net Tue Mar 22 16:21:05 2005 From: mlasky1 at cox.net (Michael Lasky) Date: Tue Mar 22 16:21:26 2005 Subject: [Tutor] Python cgi doesn't get data from html form as expected In-Reply-To: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> References: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> Message-ID: <1111504866.17299.2.camel@localhost.localdomain> I haven't done too much web stuff (or much of anything) with python, but I looked into your question a bit (researching other's problems may help me avoid them =)). A quick search brought up this page which seems to have information which may help you. http://gnosis.cx/publish/programming/feature_5min_python.html Hope that helps. Best Regards, Michael Lasky On Tue, 2005-03-22 at 14:02 +0000, Vicki Stanfield wrote: > I have recently started doing cgi in Python and have run into a problem. I > have an html form which has various widgets which accept data. I also have > this in that html file: > > <form action="formdata.py" method="post"> > > formdata.py runs but doesn't seem to contain the data from the form. I'm > not sure of the format for the for with regard to FieldStorage btw. Here > is the contents of formdata.py: > > ---------------- > #! /usr/bin/python > import cgitb, os, sys > cgitb.enable() > > import cgi > > print "Content-Type: text/html\n\n" > print "<html><head></head><body>" > form = cgi.FieldStorage() > for each in form: > print "each" > print form['fname'].value, form['lname'].value > #print "address:", form['addr'].value() > print "</body></html>" > ------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From vicki at stanfield.net Tue Mar 22 16:33:40 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Tue Mar 22 16:35:19 2005 Subject: [Tutor] Python cgi doesn't get data from html form as expected In-Reply-To: <1111504866.17299.2.camel@localhost.localdomain> References: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> <1111504866.17299.2.camel@localhost.localdomain> Message-ID: <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> > I haven't done too much web stuff (or much of anything) with python, but > I looked into your question a bit (researching other's problems may help > me avoid them =)). A quick search brought up this page which seems to > have information which may help you. > > http://gnosis.cx/publish/programming/feature_5min_python.html > > Hope that helps. > Best Regards, > Michael Lasky I don't see anything in that page that changes what I am doing. I can get rid of everything that has to do with retrieving data from cgi-FieldStorage, and the code executes fine although I get a blank page. I have revised the code somewhat, but the initial problem of cgi.FieldStorage being empty is still there. I don't get an error now, just an empty page. Here is the revised code: #! /usr/bin/python print "Content-Type: text/html\n\n" print print "<html><head></head><body>\n\n" import cgitb, os, sys cgitb.enable() sys.strerr = sys.stdout import cgi form = cgi.FieldStorage() field_list = '<ul>\n' for field in form.keys(): field_list = field_list + '<li>%s</li>\n' % field field_list = field_list + '</ul>\n' print field_list print "</body></html>\n\n" From kent37 at tds.net Tue Mar 22 16:58:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 16:58:58 2005 Subject: [Tutor] Python cgi doesn't get data from html form as expected In-Reply-To: <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> References: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> <1111504866.17299.2.camel@localhost.localdomain> <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> Message-ID: <424040BF.9070706@tds.net> Vicki Stanfield wrote: > I don't see anything in that page that changes what I am doing. I can get > rid of everything that has to do with retrieving data from > cgi-FieldStorage, and the code executes fine although I get a blank page. > I have revised the code somewhat, but the initial problem of > cgi.FieldStorage being empty is still there. I don't get an error now, > just an empty page. Here is the revised code: > > #! /usr/bin/python > print "Content-Type: text/html\n\n" > print > print "<html><head></head><body>\n\n" > > import cgitb, os, sys > cgitb.enable() > sys.strerr = sys.stdout > > import cgi > > form = cgi.FieldStorage() > field_list = '<ul>\n' > for field in form.keys(): > field_list = field_list + '<li>%s</li>\n' % field > field_list = field_list + '</ul>\n' > print field_list > print "</body></html>\n\n" Please post the HTML for the form you are submitting and the HTML from a View Source on the result. Kent From smichr at hotmail.com Tue Mar 22 15:59:36 2005 From: smichr at hotmail.com (C Smith) Date: Tue Mar 22 18:11:56 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable In-Reply-To: <20050322110116.4A73D1E402C@bag.python.org> Message-ID: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, tutor-request@python.org wrote: > I met a similar question. > what if one has L = [[1,2],[3,4]], K = [100, 200] > How to 'zip' a List like [[1,2,100], [3,4,200]]? > I would do something like: ### for i in range(len(L)): L[i].append(K[i]) ### /c From smichr at hotmail.com Tue Mar 22 18:37:11 2005 From: smichr at hotmail.com (C Smith) Date: Tue Mar 22 18:38:11 2005 Subject: [Tutor] primes - sieve of odds In-Reply-To: <20050321010121.35DC31E400E@bag.python.org> Message-ID: <BAY101-DAV12AFBD9B03492E7EE99D82C14E0@phx.gbl> 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 > Hi Sean! > > Thanks for your measurements. > In the meantime I did another amendment, > leaving out the even numbers from the sieve. > It goes like this: > > def sieve(maximum): > nums = range(3, maximum+1, 2) > for p in nums: > if p: > if p*p > maximum: break > start = (p*p-2)//2 > nums[start::p] = [False]*(1+((maximum-3)//2-start)//p) > return [2] + filter(None, nums) > > Perhaps not very elegant. But approximately twice as fast as > the former version. From kent37 at tds.net Tue Mar 22 19:30:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 19:30:13 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable In-Reply-To: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> References: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> Message-ID: <42406431.2040103@tds.net> C Smith wrote: > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > tutor-request@python.org wrote: > >> I met a similar question. >> what if one has L = [[1,2],[3,4]], K = [100, 200] >> How to 'zip' a List like [[1,2,100], [3,4,200]]? >> > I would do something like: > > ### > for i in range(len(L)): > L[i].append(K[i]) > ### Oh, the light goes on :-) Thanks C Smith! Here is another way: >>> L = [[1,2],[3,4]] >>> K = [100, 200] >>> [ x+[y] for x, y in zip(L, K) ] [[1, 2, 100], [3, 4, 200]] Note C Smith's approach modifies L to include the items in K; my approach makes a new list. Kent From python at venix.com Tue Mar 22 20:10:24 2005 From: python at venix.com (Lloyd Kvam) Date: Tue Mar 22 20:10:29 2005 Subject: [Tutor] OT - SQL methodolgy Message-ID: <1111518624.25406.73.camel@laptop.venix.com> > > In the SQL books I've got, they always seem to have an optional select > > statement on the end of inserts/updates, and I was thinking maybe I > > could do it that way also, but I can't figure out a logical way of > > putting > > > > 'select primary_key from foo where primary_key value > every other > > primary_key value' > > > > select max(primary_key) from foo? select max will NOT work reliably when you have concurrent database inserts. You could obtain the number from someone else's insert. You need to use the function provided by the RDBMS that is tied to your connection/cursor so that you retrieve the primary_key that was assigned to *your* record. (I understood your request to be looking for the primary_key auto-assigned to your insert statement) -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Tue Mar 22 20:53:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 22 20:53:44 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable number of lists to zip() In-Reply-To: <423FC073.6080701@speakeasy.net> Message-ID: <Pine.LNX.4.44.0503221141240.15315-100000@hkn.eecs.berkeley.edu> > well, I would have said "apply(zip, (l1, l2, l3, ...))" but apply has > been deprecated in 2.3. Hi Sean, Sorry for straying away from the original poster's question, but do you know why apply() is being deprecated? This is new to me! ... ok, I see some discussion on it: http://mail.python.org/pipermail/python-bugs-list/2004-October/025450.html And I now see the reference to it in the "Code Migration and Modernization" PEP 290: http://www.python.org/peps/pep-0290.html#replace-apply-with-a-direct-function-call Wow, this is somewhat of a shock to me, that the syntactic sugar approach is the preferred approach to "apply" in Python. Ok, thanks for letting me know. From vicki at stanfield.net Tue Mar 22 21:18:14 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Tue Mar 22 21:19:50 2005 Subject: [Tutor] Python cgi doesn't get data from html form as expected In-Reply-To: <424040BF.9070706@tds.net> References: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> <1111504866.17299.2.camel@localhost.localdomain> <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> <424040BF.9070706@tds.net> Message-ID: <3823.216.37.46.162.1111522694.squirrel@216.37.46.162> > Please post the HTML for the form you are submitting and the HTML from a > View Source on the result. > > Kent Sorry to have bothered the list. I figured out the answer (sort of). I had parse the HTML code through an XHTML parser which removed all the name= leaving id= only. That doesn't work with the cgi.FieldStorage function. I still don't know how to do it with XHTML which doesn't evidently support the name= at all. So, html it is. Thanks, Vicki From gsf at panix.com Tue Mar 22 21:26:05 2005 From: gsf at panix.com (Gabriel Farrell) Date: Tue Mar 22 21:26:09 2005 Subject: [Tutor] CGI script to create an XML document from an HTML form Message-ID: <20050322202605.GA3542@panix.com> Hi, I'm just starting to get my feet wet with Python. I'm trying to write a CGI script to create an XML document using input from a web form. The created document would be a MODS record[1], so I already have a Schema for it. I think I could make it work if I just feed the input into a long string as variables, then write that out to a new document, but I'd like to start investigating some of Python's XML modules because that's a sexier solution and I'll probably be doing more work in XML in the future. I've been looking around at various resources such as the Python/XML Howto[2], some of the articles by Uche Ogbuji[3], and elsewhere, and frankly I'm a little overwhelmed by the many seemingly overlapping methods. Which one would the wise tutors recommend for my situation? gabe [1] http://www.loc.gov/standards/mods/ [2] http://pyxml.sourceforge.net/topics/howto/xml-howto.html [3] http://www.xml.com/pub/au/84 From bill.mill at gmail.com Tue Mar 22 21:27:02 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Mar 22 21:27:05 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable In-Reply-To: <42406431.2040103@tds.net> References: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> <42406431.2040103@tds.net> Message-ID: <797fe3d405032212271226446f@mail.gmail.com> On Tue, 22 Mar 2005 13:30:09 -0500, Kent Johnson <kent37@tds.net> wrote: > C Smith wrote: > > > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > > tutor-request@python.org wrote: > > > >> I met a similar question. > >> what if one has L = [[1,2],[3,4]], K = [100, 200] > >> How to 'zip' a List like [[1,2,100], [3,4,200]]? > >> > > I would do something like: > > > > ### > > for i in range(len(L)): > > L[i].append(K[i]) > > ### > > Oh, the light goes on :-) Thanks C Smith! > > Here is another way: > >>> L = [[1,2],[3,4]] > >>> K = [100, 200] > >>> [ x+[y] for x, y in zip(L, K) ] > [[1, 2, 100], [3, 4, 200]] > > Note C Smith's approach modifies L to include the items in K; my approach makes a new list. Just for kicks - if you don't mind if the 100 and 200 appear first instead of last, and conversion of your inner lists to tuples, then: >>> L = [[1,2], [3,4]] >>> K = [100, 200] >>> zip(K, *L) [(100, 1, 3), (200, 2, 4)] works, and looks a little nicer. Also, to modify the list in-place with a listcomp, you could use: >>> L = [[1,2], [3,4]] >>> K = [100, 200] >>> [x.append(y) for x, y in zip(L, K)] [None, None] >>> L [[1, 2, 100], [3, 4, 200]] And, to create a new list in the format you originally asked for, we can modify the first trick I showed you: >>> L = [[1,2], [3,4]] >>> K = [100, 200] >>> [[b,c,a] for a,b,c in zip(K, *L)] [[1, 3, 100], [2, 4, 200]] which I think is pretty cool, if a little obtuse. Peace Bill Mill bill.mill at gmail.com From shidai.liu at gmail.com Tue Mar 22 21:54:55 2005 From: shidai.liu at gmail.com (Shidai Liu) Date: Tue Mar 22 21:55:16 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable In-Reply-To: <797fe3d405032212271226446f@mail.gmail.com> References: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> <42406431.2040103@tds.net> <797fe3d405032212271226446f@mail.gmail.com> Message-ID: <33194d7305032212543b0b370@mail.gmail.com> On Tue, 22 Mar 2005 15:27:02 -0500, Bill Mill <bill.mill@gmail.com> wrote: > >>> zip(K, *L) > [(100, 1, 3), (200, 2, 4)] Any idea why zip(*L, K) fails? -- With best wishes! Shidai From kent37 at tds.net Tue Mar 22 21:55:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 22 21:55:23 2005 Subject: [Tutor] CGI script to create an XML document from an HTML form In-Reply-To: <20050322202605.GA3542@panix.com> References: <20050322202605.GA3542@panix.com> Message-ID: <42408635.4020600@tds.net> Gabriel Farrell wrote: > I've been looking around at various resources such as the Python/XML > Howto[2], some of the articles by Uche Ogbuji[3], and elsewhere, and > frankly I'm a little overwhelmed by the many seemingly overlapping > methods. Which one would the wise tutors recommend for my situation? I'm a fan of ElementTree for XML work. It is kind of bare-bones but what is there is very easy to use. The main thing I miss is full XPath support. http://effbot.org/zone/element.htm Kent From hiower4 at elitemail.org Tue Mar 22 22:10:54 2005 From: hiower4 at elitemail.org (nicke) Date: Tue Mar 22 22:11:05 2005 Subject: [Tutor] print command In-Reply-To: <423EA898.708@tds.net> References: <20050321073842.49277.qmail@web53801.mail.yahoo.com> <423EA898.708@tds.net> Message-ID: <20050322231054.74424019@nadir> On Mon, 21 Mar 2005 05:57:28 -0500 Kent Johnson <kent37@tds.net> wrote: > Shitiz Bansal wrote: > > Now this is so basic, i am feeling sheepish asking > > about it. > > I am outputting to the terminal, how do i use a print > > command without making it jump no newline after > > execution, which is the default behaviour in python. > > To clarify: > > > > print 1 > > print 2 > > print 3 > > > > I want output to be > > > > 123 > > You can suppress the newline by ending the print statement with a comma, but you will still get the > space: > > print 1, > print 2, > print 3 > > will print > 1 2 3 > > You can get full control of the output by using sys.stdout.write() instead of print. Note the > arguments to write() must be strings: > > import sys > sys.stdout.write(str(1)) > sys.stdout.write(str(2)) > sys.stdout.write(str(3)) > sys.stdout.write('\n') > > Or you can accumulate the values into a list and print the list as Lutz has suggested: > > l = [] > l.append(1) > l.append(2) > l.append(3) > print ''.join(map(str, l)) > > where map(str, l) generates a list of strings by applying str() to each element of l: > >>> map(str, l) > ['1', '2', '3'] > > and ''.join() takes the resulting list and concatenates it into a single string with individual > elements separated by the empty string ''. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor why make it difficult? ;) print 1, print '\b'+str(2), print '\b'+str(3) '\b' is the escape character for backspace. From shaleh at speakeasy.net Tue Mar 22 22:10:20 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 22 22:12:14 2005 Subject: [Tutor] Looking for a Pythonic way to pass variable In-Reply-To: <33194d7305032212543b0b370@mail.gmail.com> References: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> <42406431.2040103@tds.net> <797fe3d405032212271226446f@mail.gmail.com> <33194d7305032212543b0b370@mail.gmail.com> Message-ID: <424089BC.7070206@speakeasy.net> Shidai Liu wrote: > On Tue, 22 Mar 2005 15:27:02 -0500, Bill Mill <bill.mill@gmail.com> wrote: > >>>>>zip(K, *L) >> >>[(100, 1, 3), (200, 2, 4)] > > > Any idea why zip(*L, K) fails? > I believe the *'ed item needs to be the last argument. From smaug9 at gmail.com Tue Mar 22 22:20:39 2005 From: smaug9 at gmail.com (jeff) Date: Tue Mar 22 22:20:44 2005 Subject: [Tutor] iterating through large dictionary Message-ID: <267a4b31050322132050b68889@mail.gmail.com> Hi, I'm trying to print out all the attributes of a user account in active directory. I got a script from: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303348/index_txt Now I'd like it to print pretty. What I have now is: import win32com,win32com.client def ad_dict(ldap_path,value_required=1): attr_dict={} adobj=win32com.client.GetObject(ldap_path) schema_obj=win32com.client.GetObject(adobj.schema) for i in schema_obj.MandatoryProperties: value=getattr(adobj,i) if value_required and value==None: continue attr_dict[i]=value for i in schema_obj.OptionalProperties: value=getattr(adobj,i) if value_required and value==None: continue attr_dict[i]=value return attr_dict user='LDAP://cn=Wardlaw\, Jeff,OU=IS Department,OU=IT department,DC=acpdom,DC=acp,DC=edu' for k, v in ad_dict(user): print "%s=%s" % (k, v) I get the following error when I try this: D:\Python24>ad-attr.py Traceback (most recent call last): File "D:\Python24\ad-attr.py", line 32, in ? for k, v in ad_dict(user): ValueError: too many values to unpack Thanks! -- --Jeff From garnaez at gmail.com Tue Mar 22 22:32:23 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Tue Mar 22 22:32:27 2005 Subject: [Tutor] Re: Tutor Digest, Vol 13, Issue 65 In-Reply-To: <20050322183017.19D451E400F@bag.python.org> References: <20050322183017.19D451E400F@bag.python.org> Message-ID: <148eea71050322133257986b32@mail.gmail.com> Hello, Im a newbie python user, love the way it "just makes sense" but Im also a working doctor and have been thinking about coumadin and how to dose it. I am not sure where to ask this, so I am going to ask on this list for two reasons 1. I intend to use python to prototype it. 2. There must some serious math dudes on this list or at least know enough math to let me know what I am talking about or point me in the right direction. The question is, When I adjust coumadin doses I normal have to use whole or half pills of the medicien the patient already has. Fer Instance, if a pt takes 5mg of coumadin a day, that's 35mg of coumadin week and suppose I do a test that says thye are not taking enough coumadin and to increase the dose by 10%, ie add another 3.5mg but have it split evenly over the week or at least every other day. normall, I would say ok Take 5mg coumadine everty but on mon and thurs day take 7.5mg (Note the patient only has 5mg tabs, which they can split to make dose adjust my 2.5) My question is, How would I solve this using math instead of geustimating it. What kind of math am I talking about here? If this is the wrong list, please point in the right direction. i've tried googlie for help, but I dont know enough to even formulate it into a a search expression Thanks all G On Tue, 22 Mar 2005 19:30:17 +0100 (CET), tutor-request@python.org <tutor-request@python.org> wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > > 1. Re: OT - SQL methodology. (Kent Johnson) > 2. Re: Very Newbie (Kent Johnson) > 3. Re: Looking for a Pythonic way to pass variable number of > lists to zip() (Kent Johnson) > 4. Visual Python from Active State (rkashyap@sympatico.ca) > 5. Python cgi doesn't get data from html form as expected > (Vicki Stanfield) > 6. Re: Python cgi doesn't get data from html form as expected > (Michael Lasky) > 7. Re: Python cgi doesn't get data from html form as expected > (Vicki Stanfield) > 8. Re: Python cgi doesn't get data from html form as expected > (Kent Johnson) > 9. Re: Looking for a Pythonic way to pass variable (C Smith) > 10. Re: primes - sieve of odds (C Smith) > 11. Re: Looking for a Pythonic way to pass variable (Kent Johnson) > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 22 Mar 2005 06:00:16 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] OT - SQL methodology. > Cc: Tutor Tutor <tutor@python.org> > Message-ID: <423FFAC0.2010703@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Liam Clarke wrote: > > Hi, > > > > This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) > > Uh oh, you're in trouble if you think I'm an "advanced db guru" :-) > > > > After I've run an insert statement, should I get the new primary key > > (it's autoincrementing) by using PySQLite's cursor.lastrowid in a > > select statement, or is there a more SQLish way to do this? > > AFAIK there is no standard SQL way to do this, it is database-dependent. Python DB-API provides a > portable interface using lastrowid; I would use that. > > You don't have to do another select, lastrowid is an attribute of the cursor itself. It calls the > SQLite function sqlite_last_insert_rowid(). > > > In the SQL books I've got, they always seem to have an optional select > > statement on the end of inserts/updates, and I was thinking maybe I > > could do it that way also, but I can't figure out a logical way of > > putting > > > > 'select primary_key from foo where primary_key value > every other > > primary_key value' > > Use cursor.lastrowid, that's what it is for. > > Kent > > ------------------------------ > > Message: 2 > Date: Tue, 22 Mar 2005 06:09:03 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Very Newbie > Cc: tutor@python.org > Message-ID: <423FFCCF.9000508@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Terry Johnson wrote: > > Hey to the tutors. I am a newbie of course about the only background is > > some old qbasic and very little c and perl. I have been wanting to write > > my own Web Server Program and when I saw a few times mentioned around > > python about it I am starting to check into it. If the is anyone who has > > done such a thing or can oint me in the best direction for learning > > about it please respond. Thanks in Advance > > There are many options for doing this. For a very simple server you might look at the standard > library modules mentioned by Lutz; there is also a CGIHTTPServer module. You can also write CGI > programs in Python for use with another web server such as Apache. Basic information about writing > CGI's in Python is here: > http://www.python.org/topics/web/basic-cgi.html > > Beyond that, the options multiply. This web page lists many of them: > http://www.python.org/moin/WebProgramming > Snakelets is one that is oriented toward ease of learning. > Quixote, CherryPy and Twisted are probably the most popular. > > If you give us some more information we might be able to help you narrow down the options a little. > Is this just for fun and learning or will it be a production site eventually? Do you want to create > dynamic content or just serve static web pages? > > Ultimately though the selection is a matter of finding an alternative you are comfortable with. > > Kent > > ------------------------------ > > Message: 3 > Date: Tue, 22 Mar 2005 07:47:27 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > number of lists to zip() > Cc: p <tutor@python.org> > Message-ID: <424013DF.7070401@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Shidai Liu wrote: > > On Mon, 21 Mar 2005 22:51:31 -0800, Sean Perry <shaleh@speakeasy.net> wrote: > >>arg_list = [] > >># fill up arg_list > >>zipped = zip(*arg_list) > >> > > > > I met a similar question. > > what if one has L = [[1,2],[3,4]], K = [100, 200] > > What do you want to do with these lists? > > > How to 'zip' a List like [[1,2,100], [3,4,200]]? > > >>> zip(*[[1,2,100], [3,4,200]]) > [(1, 3), (2, 4), (100, 200)] > > If that's not what you mean, please give an example of the input *and results* you want. > > Kent > > ------------------------------ > > Message: 4 > Date: Tue, 22 Mar 2005 8:58:06 -0500 > From: <rkashyap@sympatico.ca> > Subject: [Tutor] Visual Python from Active State > To: <tutor@python.org> > Message-ID: > <20050322135806.GRSL1796.tomts6-srv.bellnexxia.net@mxmta.bellnexxia.net> > > Content-Type: text/plain; charset=iso-8859-1 > > Hi, > > I would like to get comments on Pros/Cons of using Visual Python. > > On another note, I have created a couple of MS Access databases for my work. At a recent conference, a lot of people have expressed an interest in using these as products for their own use. I am looking for ways to code a mechanism to have license keys for evaluation (30day/60day trial, and fully licensed version, etc.). > > I would like to use this opportunity to jump into using Python as the development platform if possible. Most of the work I do is in the MS Office Professional. > > regards, > > Ramkumar > > ------------------------------ > > Message: 5 > Date: Tue, 22 Mar 2005 14:02:17 -0000 (GMT) > From: "Vicki Stanfield" <vicki@stanfield.net> > Subject: [Tutor] Python cgi doesn't get data from html form as > expected > To: tutor@python.org > Message-ID: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> > Content-Type: text/plain;charset=iso-8859-1 > > I have recently started doing cgi in Python and have run into a problem. I > have an html form which has various widgets which accept data. I also have > this in that html file: > > <form action="formdata.py" method="post"> > > formdata.py runs but doesn't seem to contain the data from the form. I'm > not sure of the format for the for with regard to FieldStorage btw. Here > is the contents of formdata.py: > > ---------------- > #! /usr/bin/python > import cgitb, os, sys > cgitb.enable() > > import cgi > > print "Content-Type: text/html\n\n" > print "<html><head></head><body>" > form = cgi.FieldStorage() > for each in form: > print "each" > print form['fname'].value, form['lname'].value > #print "address:", form['addr'].value() > print "</body></html>" > ------------------ > > ------------------------------ > > Message: 6 > Date: Tue, 22 Mar 2005 09:21:05 -0600 > From: Michael Lasky <mlasky1@cox.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > To: tutor@python.org > Message-ID: <1111504866.17299.2.camel@localhost.localdomain> > Content-Type: text/plain > > I haven't done too much web stuff (or much of anything) with python, but > I looked into your question a bit (researching other's problems may help > me avoid them =)). A quick search brought up this page which seems to > have information which may help you. > > http://gnosis.cx/publish/programming/feature_5min_python.html > > Hope that helps. > Best Regards, > Michael Lasky > > On Tue, 2005-03-22 at 14:02 +0000, Vicki Stanfield wrote: > > I have recently started doing cgi in Python and have run into a problem. I > > have an html form which has various widgets which accept data. I also have > > this in that html file: > > > > <form action="formdata.py" method="post"> > > > > formdata.py runs but doesn't seem to contain the data from the form. I'm > > not sure of the format for the for with regard to FieldStorage btw. Here > > is the contents of formdata.py: > > > > ---------------- > > #! /usr/bin/python > > import cgitb, os, sys > > cgitb.enable() > > > > import cgi > > > > print "Content-Type: text/html\n\n" > > print "<html><head></head><body>" > > form = cgi.FieldStorage() > > for each in form: > > print "each" > > print form['fname'].value, form['lname'].value > > #print "address:", form['addr'].value() > > print "</body></html>" > > ------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ > > Message: 7 > Date: Tue, 22 Mar 2005 15:33:40 -0000 (GMT) > From: "Vicki Stanfield" <vicki@stanfield.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > To: "Michael Lasky" <mlasky1@cox.net> > Cc: tutor@python.org > Message-ID: <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> > Content-Type: text/plain;charset=iso-8859-1 > > > I haven't done too much web stuff (or much of anything) with python, but > > I looked into your question a bit (researching other's problems may help > > me avoid them =)). A quick search brought up this page which seems to > > have information which may help you. > > > > http://gnosis.cx/publish/programming/feature_5min_python.html > > > > Hope that helps. > > Best Regards, > > Michael Lasky > > I don't see anything in that page that changes what I am doing. I can get > rid of everything that has to do with retrieving data from > cgi-FieldStorage, and the code executes fine although I get a blank page. > I have revised the code somewhat, but the initial problem of > cgi.FieldStorage being empty is still there. I don't get an error now, > just an empty page. Here is the revised code: > > #! /usr/bin/python > print "Content-Type: text/html\n\n" > print > print "<html><head></head><body>\n\n" > > import cgitb, os, sys > cgitb.enable() > sys.strerr = sys.stdout > > import cgi > > form = cgi.FieldStorage() > field_list = '<ul>\n' > for field in form.keys(): > field_list = field_list + '<li>%s</li>\n' % field > field_list = field_list + '</ul>\n' > print field_list > print "</body></html>\n\n" > > ------------------------------ > > Message: 8 > Date: Tue, 22 Mar 2005 10:58:55 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > Cc: tutor@python.org > Message-ID: <424040BF.9070706@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Vicki Stanfield wrote: > > I don't see anything in that page that changes what I am doing. I can get > > rid of everything that has to do with retrieving data from > > cgi-FieldStorage, and the code executes fine although I get a blank page. > > I have revised the code somewhat, but the initial problem of > > cgi.FieldStorage being empty is still there. I don't get an error now, > > just an empty page. Here is the revised code: > > > > #! /usr/bin/python > > print "Content-Type: text/html\n\n" > > print > > print "<html><head></head><body>\n\n" > > > > import cgitb, os, sys > > cgitb.enable() > > sys.strerr = sys.stdout > > > > import cgi > > > > form = cgi.FieldStorage() > > field_list = '<ul>\n' > > for field in form.keys(): > > field_list = field_list + '<li>%s</li>\n' % field > > field_list = field_list + '</ul>\n' > > print field_list > > print "</body></html>\n\n" > > Please post the HTML for the form you are submitting and the HTML from a View Source on the result. > > Kent > > ------------------------------ > > Message: 9 > Date: Tue, 22 Mar 2005 08:59:36 -0600 > From: C Smith <smichr@hotmail.com> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > To: tutor@python.org > Message-ID: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> > Content-Type: text/plain; charset=US-ASCII; format=flowed > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > tutor-request@python.org wrote: > > > I met a similar question. > > what if one has L = [[1,2],[3,4]], K = [100, 200] > > How to 'zip' a List like [[1,2,100], [3,4,200]]? > > > I would do something like: > > ### > for i in range(len(L)): > L[i].append(K[i]) > ### > > /c > > ------------------------------ > > Message: 10 > Date: Tue, 22 Mar 2005 11:37:11 -0600 > From: C Smith <smichr@hotmail.com> > Subject: Re: [Tutor] primes - sieve of odds > To: tutor@python.org > Message-ID: <BAY101-DAV12AFBD9B03492E7EE99D82C14E0@phx.gbl> > Content-Type: text/plain; charset=US-ASCII; format=flowed > > 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 > > > Hi Sean! > > > > Thanks for your measurements. > > In the meantime I did another amendment, > > leaving out the even numbers from the sieve. > > It goes like this: > > > > def sieve(maximum): > > nums = range(3, maximum+1, 2) > > for p in nums: > > if p: > > if p*p > maximum: break > > start = (p*p-2)//2 > > nums[start::p] = [False]*(1+((maximum-3)//2-start)//p) > > return [2] + filter(None, nums) > > > > Perhaps not very elegant. But approximately twice as fast as > > the former version. > > ------------------------------ > > Message: 11 > Date: Tue, 22 Mar 2005 13:30:09 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > Cc: tutor@python.org > Message-ID: <42406431.2040103@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > C Smith wrote: > > > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > > tutor-request@python.org wrote: > > > >> I met a similar question. > >> what if one has L = [[1,2],[3,4]], K = [100, 200] > >> How to 'zip' a List like [[1,2,100], [3,4,200]]? > >> > > I would do something like: > > > > ### > > for i in range(len(L)): > > L[i].append(K[i]) > > ### > > Oh, the light goes on :-) Thanks C Smith! > > Here is another way: > >>> L = [[1,2],[3,4]] > >>> K = [100, 200] > >>> [ x+[y] for x, y in zip(L, K) ] > [[1, 2, 100], [3, 4, 200]] > > Note C Smith's approach modifies L to include the items in K; my approach makes a new list. > > Kent > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > End of Tutor Digest, Vol 13, Issue 65 > ************************************* > From garnaez at gmail.com Tue Mar 22 22:33:04 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Tue Mar 22 22:33:07 2005 Subject: [Tutor] Math Question In-Reply-To: <148eea71050322133257986b32@mail.gmail.com> References: <20050322183017.19D451E400F@bag.python.org> <148eea71050322133257986b32@mail.gmail.com> Message-ID: <148eea7105032213331051b83a@mail.gmail.com> This is a resend, but I change the subject so I can track this better, please excuse duplicate ---------- Forwarded message ---------- From: gerardo arnaez <garnaez@gmail.com> Date: Tue, 22 Mar 2005 13:32:23 -0800 Subject: Re: Tutor Digest, Vol 13, Issue 65 To: tutor@python.org Hello, Im a newbie python user, love the way it "just makes sense" but Im also a working doctor and have been thinking about coumadin and how to dose it. I am not sure where to ask this, so I am going to ask on this list for two reasons 1. I intend to use python to prototype it. 2. There must some serious math dudes on this list or at least know enough math to let me know what I am talking about or point me in the right direction. The question is, When I adjust coumadin doses I normal have to use whole or half pills of the medicien the patient already has. Fer Instance, if a pt takes 5mg of coumadin a day, that's 35mg of coumadin week and suppose I do a test that says thye are not taking enough coumadin and to increase the dose by 10%, ie add another 3.5mg but have it split evenly over the week or at least every other day. normall, I would say ok Take 5mg coumadine everty but on mon and thurs day take 7.5mg (Note the patient only has 5mg tabs, which they can split to make dose adjust my 2.5) My question is, How would I solve this using math instead of geustimating it. What kind of math am I talking about here? If this is the wrong list, please point in the right direction. i've tried googlie for help, but I dont know enough to even formulate it into a a search expression Thanks all G On Tue, 22 Mar 2005 19:30:17 +0100 (CET), tutor-request@python.org <tutor-request@python.org> wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > > 1. Re: OT - SQL methodology. (Kent Johnson) > 2. Re: Very Newbie (Kent Johnson) > 3. Re: Looking for a Pythonic way to pass variable number of > lists to zip() (Kent Johnson) > 4. Visual Python from Active State (rkashyap@sympatico.ca) > 5. Python cgi doesn't get data from html form as expected > (Vicki Stanfield) > 6. Re: Python cgi doesn't get data from html form as expected > (Michael Lasky) > 7. Re: Python cgi doesn't get data from html form as expected > (Vicki Stanfield) > 8. Re: Python cgi doesn't get data from html form as expected > (Kent Johnson) > 9. Re: Looking for a Pythonic way to pass variable (C Smith) > 10. Re: primes - sieve of odds (C Smith) > 11. Re: Looking for a Pythonic way to pass variable (Kent Johnson) > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 22 Mar 2005 06:00:16 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] OT - SQL methodology. > Cc: Tutor Tutor <tutor@python.org> > Message-ID: <423FFAC0.2010703@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Liam Clarke wrote: > > Hi, > > > > This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) > > Uh oh, you're in trouble if you think I'm an "advanced db guru" :-) > > > > After I've run an insert statement, should I get the new primary key > > (it's autoincrementing) by using PySQLite's cursor.lastrowid in a > > select statement, or is there a more SQLish way to do this? > > AFAIK there is no standard SQL way to do this, it is database-dependent. Python DB-API provides a > portable interface using lastrowid; I would use that. > > You don't have to do another select, lastrowid is an attribute of the cursor itself. It calls the > SQLite function sqlite_last_insert_rowid(). > > > In the SQL books I've got, they always seem to have an optional select > > statement on the end of inserts/updates, and I was thinking maybe I > > could do it that way also, but I can't figure out a logical way of > > putting > > > > 'select primary_key from foo where primary_key value > every other > > primary_key value' > > Use cursor.lastrowid, that's what it is for. > > Kent > > ------------------------------ > > Message: 2 > Date: Tue, 22 Mar 2005 06:09:03 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Very Newbie > Cc: tutor@python.org > Message-ID: <423FFCCF.9000508@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Terry Johnson wrote: > > Hey to the tutors. I am a newbie of course about the only background is > > some old qbasic and very little c and perl. I have been wanting to write > > my own Web Server Program and when I saw a few times mentioned around > > python about it I am starting to check into it. If the is anyone who has > > done such a thing or can oint me in the best direction for learning > > about it please respond. Thanks in Advance > > There are many options for doing this. For a very simple server you might look at the standard > library modules mentioned by Lutz; there is also a CGIHTTPServer module. You can also write CGI > programs in Python for use with another web server such as Apache. Basic information about writing > CGI's in Python is here: > http://www.python.org/topics/web/basic-cgi.html > > Beyond that, the options multiply. This web page lists many of them: > http://www.python.org/moin/WebProgramming > Snakelets is one that is oriented toward ease of learning. > Quixote, CherryPy and Twisted are probably the most popular. > > If you give us some more information we might be able to help you narrow down the options a little. > Is this just for fun and learning or will it be a production site eventually? Do you want to create > dynamic content or just serve static web pages? > > Ultimately though the selection is a matter of finding an alternative you are comfortable with. > > Kent > > ------------------------------ > > Message: 3 > Date: Tue, 22 Mar 2005 07:47:27 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > number of lists to zip() > Cc: p <tutor@python.org> > Message-ID: <424013DF.7070401@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Shidai Liu wrote: > > On Mon, 21 Mar 2005 22:51:31 -0800, Sean Perry <shaleh@speakeasy.net> wrote: > >>arg_list = [] > >># fill up arg_list > >>zipped = zip(*arg_list) > >> > > > > I met a similar question. > > what if one has L = [[1,2],[3,4]], K = [100, 200] > > What do you want to do with these lists? > > > How to 'zip' a List like [[1,2,100], [3,4,200]]? > > >>> zip(*[[1,2,100], [3,4,200]]) > [(1, 3), (2, 4), (100, 200)] > > If that's not what you mean, please give an example of the input *and results* you want. > > Kent > > ------------------------------ > > Message: 4 > Date: Tue, 22 Mar 2005 8:58:06 -0500 > From: <rkashyap@sympatico.ca> > Subject: [Tutor] Visual Python from Active State > To: <tutor@python.org> > Message-ID: > <20050322135806.GRSL1796.tomts6-srv.bellnexxia.net@mxmta.bellnexxia.net> > > Content-Type: text/plain; charset=iso-8859-1 > > Hi, > > I would like to get comments on Pros/Cons of using Visual Python. > > On another note, I have created a couple of MS Access databases for my work. At a recent conference, a lot of people have expressed an interest in using these as products for their own use. I am looking for ways to code a mechanism to have license keys for evaluation (30day/60day trial, and fully licensed version, etc.). > > I would like to use this opportunity to jump into using Python as the development platform if possible. Most of the work I do is in the MS Office Professional. > > regards, > > Ramkumar > > ------------------------------ > > Message: 5 > Date: Tue, 22 Mar 2005 14:02:17 -0000 (GMT) > From: "Vicki Stanfield" <vicki@stanfield.net> > Subject: [Tutor] Python cgi doesn't get data from html form as > expected > To: tutor@python.org > Message-ID: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> > Content-Type: text/plain;charset=iso-8859-1 > > I have recently started doing cgi in Python and have run into a problem. I > have an html form which has various widgets which accept data. I also have > this in that html file: > > <form action="formdata.py" method="post"> > > formdata.py runs but doesn't seem to contain the data from the form. I'm > not sure of the format for the for with regard to FieldStorage btw. Here > is the contents of formdata.py: > > ---------------- > #! /usr/bin/python > import cgitb, os, sys > cgitb.enable() > > import cgi > > print "Content-Type: text/html\n\n" > print "<html><head></head><body>" > form = cgi.FieldStorage() > for each in form: > print "each" > print form['fname'].value, form['lname'].value > #print "address:", form['addr'].value() > print "</body></html>" > ------------------ > > ------------------------------ > > Message: 6 > Date: Tue, 22 Mar 2005 09:21:05 -0600 > From: Michael Lasky <mlasky1@cox.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > To: tutor@python.org > Message-ID: <1111504866.17299.2.camel@localhost.localdomain> > Content-Type: text/plain > > I haven't done too much web stuff (or much of anything) with python, but > I looked into your question a bit (researching other's problems may help > me avoid them =)). A quick search brought up this page which seems to > have information which may help you. > > http://gnosis.cx/publish/programming/feature_5min_python.html > > Hope that helps. > Best Regards, > Michael Lasky > > On Tue, 2005-03-22 at 14:02 +0000, Vicki Stanfield wrote: > > I have recently started doing cgi in Python and have run into a problem. I > > have an html form which has various widgets which accept data. I also have > > this in that html file: > > > > <form action="formdata.py" method="post"> > > > > formdata.py runs but doesn't seem to contain the data from the form. I'm > > not sure of the format for the for with regard to FieldStorage btw. Here > > is the contents of formdata.py: > > > > ---------------- > > #! /usr/bin/python > > import cgitb, os, sys > > cgitb.enable() > > > > import cgi > > > > print "Content-Type: text/html\n\n" > > print "<html><head></head><body>" > > form = cgi.FieldStorage() > > for each in form: > > print "each" > > print form['fname'].value, form['lname'].value > > #print "address:", form['addr'].value() > > print "</body></html>" > > ------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ > > Message: 7 > Date: Tue, 22 Mar 2005 15:33:40 -0000 (GMT) > From: "Vicki Stanfield" <vicki@stanfield.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > To: "Michael Lasky" <mlasky1@cox.net> > Cc: tutor@python.org > Message-ID: <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> > Content-Type: text/plain;charset=iso-8859-1 > > > I haven't done too much web stuff (or much of anything) with python, but > > I looked into your question a bit (researching other's problems may help > > me avoid them =)). A quick search brought up this page which seems to > > have information which may help you. > > > > http://gnosis.cx/publish/programming/feature_5min_python.html > > > > Hope that helps. > > Best Regards, > > Michael Lasky > > I don't see anything in that page that changes what I am doing. I can get > rid of everything that has to do with retrieving data from > cgi-FieldStorage, and the code executes fine although I get a blank page. > I have revised the code somewhat, but the initial problem of > cgi.FieldStorage being empty is still there. I don't get an error now, > just an empty page. Here is the revised code: > > #! /usr/bin/python > print "Content-Type: text/html\n\n" > print > print "<html><head></head><body>\n\n" > > import cgitb, os, sys > cgitb.enable() > sys.strerr = sys.stdout > > import cgi > > form = cgi.FieldStorage() > field_list = '<ul>\n' > for field in form.keys(): > field_list = field_list + '<li>%s</li>\n' % field > field_list = field_list + '</ul>\n' > print field_list > print "</body></html>\n\n" > > ------------------------------ > > Message: 8 > Date: Tue, 22 Mar 2005 10:58:55 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > Cc: tutor@python.org > Message-ID: <424040BF.9070706@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Vicki Stanfield wrote: > > I don't see anything in that page that changes what I am doing. I can get > > rid of everything that has to do with retrieving data from > > cgi-FieldStorage, and the code executes fine although I get a blank page. > > I have revised the code somewhat, but the initial problem of > > cgi.FieldStorage being empty is still there. I don't get an error now, > > just an empty page. Here is the revised code: > > > > #! /usr/bin/python > > print "Content-Type: text/html\n\n" > > print > > print "<html><head></head><body>\n\n" > > > > import cgitb, os, sys > > cgitb.enable() > > sys.strerr = sys.stdout > > > > import cgi > > > > form = cgi.FieldStorage() > > field_list = '<ul>\n' > > for field in form.keys(): > > field_list = field_list + '<li>%s</li>\n' % field > > field_list = field_list + '</ul>\n' > > print field_list > > print "</body></html>\n\n" > > Please post the HTML for the form you are submitting and the HTML from a View Source on the result. > > Kent > > ------------------------------ > > Message: 9 > Date: Tue, 22 Mar 2005 08:59:36 -0600 > From: C Smith <smichr@hotmail.com> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > To: tutor@python.org > Message-ID: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> > Content-Type: text/plain; charset=US-ASCII; format=flowed > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > tutor-request@python.org wrote: > > > I met a similar question. > > what if one has L = [[1,2],[3,4]], K = [100, 200] > > How to 'zip' a List like [[1,2,100], [3,4,200]]? > > > I would do something like: > > ### > for i in range(len(L)): > L[i].append(K[i]) > ### > > /c > > ------------------------------ > > Message: 10 > Date: Tue, 22 Mar 2005 11:37:11 -0600 > From: C Smith <smichr@hotmail.com> > Subject: Re: [Tutor] primes - sieve of odds > To: tutor@python.org > Message-ID: <BAY101-DAV12AFBD9B03492E7EE99D82C14E0@phx.gbl> > Content-Type: text/plain; charset=US-ASCII; format=flowed > > 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 > > > Hi Sean! > > > > Thanks for your measurements. > > In the meantime I did another amendment, > > leaving out the even numbers from the sieve. > > It goes like this: > > > > def sieve(maximum): > > nums = range(3, maximum+1, 2) > > for p in nums: > > if p: > > if p*p > maximum: break > > start = (p*p-2)//2 > > nums[start::p] = [False]*(1+((maximum-3)//2-start)//p) > > return [2] + filter(None, nums) > > > > Perhaps not very elegant. But approximately twice as fast as > > the former version. > > ------------------------------ > > Message: 11 > Date: Tue, 22 Mar 2005 13:30:09 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > Cc: tutor@python.org > Message-ID: <42406431.2040103@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > C Smith wrote: > > > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > > tutor-request@python.org wrote: > > > >> I met a similar question. > >> what if one has L = [[1,2],[3,4]], K = [100, 200] > >> How to 'zip' a List like [[1,2,100], [3,4,200]]? > >> > > I would do something like: > > > > ### > > for i in range(len(L)): > > L[i].append(K[i]) > > ### > > Oh, the light goes on :-) Thanks C Smith! > > Here is another way: > >>> L = [[1,2],[3,4]] > >>> K = [100, 200] > >>> [ x+[y] for x, y in zip(L, K) ] > [[1, 2, 100], [3, 4, 200]] > > Note C Smith's approach modifies L to include the items in K; my approach makes a new list. > > Kent > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > End of Tutor Digest, Vol 13, Issue 65 > ************************************* > From garnaez at gmail.com Tue Mar 22 22:33:53 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Tue Mar 22 22:33:56 2005 Subject: [Tutor] Fwd: Math Question In-Reply-To: <148eea7105032213331051b83a@mail.gmail.com> References: <20050322183017.19D451E400F@bag.python.org> <148eea71050322133257986b32@mail.gmail.com> <148eea7105032213331051b83a@mail.gmail.com> Message-ID: <148eea7105032213335c7666b2@mail.gmail.com> ---------- Forwarded message ---------- From: gerardo arnaez <garnaez@gmail.com> Date: Tue, 22 Mar 2005 13:33:04 -0800 Subject: Math Question To: tutor@python.org This is a resend, but I change the subject so I can track this better, please excuse duplicate ---------- Forwarded message ---------- From: gerardo arnaez <garnaez@gmail.com> Date: Tue, 22 Mar 2005 13:32:23 -0800 Subject: Re: Tutor Digest, Vol 13, Issue 65 To: tutor@python.org Hello, Im a newbie python user, love the way it "just makes sense" but Im also a working doctor and have been thinking about coumadin and how to dose it. I am not sure where to ask this, so I am going to ask on this list for two reasons 1. I intend to use python to prototype it. 2. There must some serious math dudes on this list or at least know enough math to let me know what I am talking about or point me in the right direction. The question is, When I adjust coumadin doses I normal have to use whole or half pills of the medicien the patient already has. Fer Instance, if a pt takes 5mg of coumadin a day, that's 35mg of coumadin week and suppose I do a test that says thye are not taking enough coumadin and to increase the dose by 10%, ie add another 3.5mg but have it split evenly over the week or at least every other day. normall, I would say ok Take 5mg coumadine everty but on mon and thurs day take 7.5mg (Note the patient only has 5mg tabs, which they can split to make dose adjust my 2.5) My question is, How would I solve this using math instead of geustimating it. What kind of math am I talking about here? If this is the wrong list, please point in the right direction. i've tried googlie for help, but I dont know enough to even formulate it into a a search expression Thanks all G On Tue, 22 Mar 2005 19:30:17 +0100 (CET), tutor-request@python.org <tutor-request@python.org> wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > Today's Topics: > > 1. Re: OT - SQL methodology. (Kent Johnson) > 2. Re: Very Newbie (Kent Johnson) > 3. Re: Looking for a Pythonic way to pass variable number of > lists to zip() (Kent Johnson) > 4. Visual Python from Active State (rkashyap@sympatico.ca) > 5. Python cgi doesn't get data from html form as expected > (Vicki Stanfield) > 6. Re: Python cgi doesn't get data from html form as expected > (Michael Lasky) > 7. Re: Python cgi doesn't get data from html form as expected > (Vicki Stanfield) > 8. Re: Python cgi doesn't get data from html form as expected > (Kent Johnson) > 9. Re: Looking for a Pythonic way to pass variable (C Smith) > 10. Re: primes - sieve of odds (C Smith) > 11. Re: Looking for a Pythonic way to pass variable (Kent Johnson) > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 22 Mar 2005 06:00:16 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] OT - SQL methodology. > Cc: Tutor Tutor <tutor@python.org> > Message-ID: <423FFAC0.2010703@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Liam Clarke wrote: > > Hi, > > > > This is a SQL query for the advanced db gurus among you (I'm looking at Kent...) > > Uh oh, you're in trouble if you think I'm an "advanced db guru" :-) > > > > After I've run an insert statement, should I get the new primary key > > (it's autoincrementing) by using PySQLite's cursor.lastrowid in a > > select statement, or is there a more SQLish way to do this? > > AFAIK there is no standard SQL way to do this, it is database-dependent. Python DB-API provides a > portable interface using lastrowid; I would use that. > > You don't have to do another select, lastrowid is an attribute of the cursor itself. It calls the > SQLite function sqlite_last_insert_rowid(). > > > In the SQL books I've got, they always seem to have an optional select > > statement on the end of inserts/updates, and I was thinking maybe I > > could do it that way also, but I can't figure out a logical way of > > putting > > > > 'select primary_key from foo where primary_key value > every other > > primary_key value' > > Use cursor.lastrowid, that's what it is for. > > Kent > > ------------------------------ > > Message: 2 > Date: Tue, 22 Mar 2005 06:09:03 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Very Newbie > Cc: tutor@python.org > Message-ID: <423FFCCF.9000508@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Terry Johnson wrote: > > Hey to the tutors. I am a newbie of course about the only background is > > some old qbasic and very little c and perl. I have been wanting to write > > my own Web Server Program and when I saw a few times mentioned around > > python about it I am starting to check into it. If the is anyone who has > > done such a thing or can oint me in the best direction for learning > > about it please respond. Thanks in Advance > > There are many options for doing this. For a very simple server you might look at the standard > library modules mentioned by Lutz; there is also a CGIHTTPServer module. You can also write CGI > programs in Python for use with another web server such as Apache. Basic information about writing > CGI's in Python is here: > http://www.python.org/topics/web/basic-cgi.html > > Beyond that, the options multiply. This web page lists many of them: > http://www.python.org/moin/WebProgramming > Snakelets is one that is oriented toward ease of learning. > Quixote, CherryPy and Twisted are probably the most popular. > > If you give us some more information we might be able to help you narrow down the options a little. > Is this just for fun and learning or will it be a production site eventually? Do you want to create > dynamic content or just serve static web pages? > > Ultimately though the selection is a matter of finding an alternative you are comfortable with. > > Kent > > ------------------------------ > > Message: 3 > Date: Tue, 22 Mar 2005 07:47:27 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > number of lists to zip() > Cc: p <tutor@python.org> > Message-ID: <424013DF.7070401@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Shidai Liu wrote: > > On Mon, 21 Mar 2005 22:51:31 -0800, Sean Perry <shaleh@speakeasy.net> wrote: > >>arg_list = [] > >># fill up arg_list > >>zipped = zip(*arg_list) > >> > > > > I met a similar question. > > what if one has L = [[1,2],[3,4]], K = [100, 200] > > What do you want to do with these lists? > > > How to 'zip' a List like [[1,2,100], [3,4,200]]? > > >>> zip(*[[1,2,100], [3,4,200]]) > [(1, 3), (2, 4), (100, 200)] > > If that's not what you mean, please give an example of the input *and results* you want. > > Kent > > ------------------------------ > > Message: 4 > Date: Tue, 22 Mar 2005 8:58:06 -0500 > From: <rkashyap@sympatico.ca> > Subject: [Tutor] Visual Python from Active State > To: <tutor@python.org> > Message-ID: > <20050322135806.GRSL1796.tomts6-srv.bellnexxia.net@mxmta.bellnexxia.net> > > Content-Type: text/plain; charset=iso-8859-1 > > Hi, > > I would like to get comments on Pros/Cons of using Visual Python. > > On another note, I have created a couple of MS Access databases for my work. At a recent conference, a lot of people have expressed an interest in using these as products for their own use. I am looking for ways to code a mechanism to have license keys for evaluation (30day/60day trial, and fully licensed version, etc.). > > I would like to use this opportunity to jump into using Python as the development platform if possible. Most of the work I do is in the MS Office Professional. > > regards, > > Ramkumar > > ------------------------------ > > Message: 5 > Date: Tue, 22 Mar 2005 14:02:17 -0000 (GMT) > From: "Vicki Stanfield" <vicki@stanfield.net> > Subject: [Tutor] Python cgi doesn't get data from html form as > expected > To: tutor@python.org > Message-ID: <1154.216.37.46.162.1111500137.squirrel@216.37.46.162> > Content-Type: text/plain;charset=iso-8859-1 > > I have recently started doing cgi in Python and have run into a problem. I > have an html form which has various widgets which accept data. I also have > this in that html file: > > <form action="formdata.py" method="post"> > > formdata.py runs but doesn't seem to contain the data from the form. I'm > not sure of the format for the for with regard to FieldStorage btw. Here > is the contents of formdata.py: > > ---------------- > #! /usr/bin/python > import cgitb, os, sys > cgitb.enable() > > import cgi > > print "Content-Type: text/html\n\n" > print "<html><head></head><body>" > form = cgi.FieldStorage() > for each in form: > print "each" > print form['fname'].value, form['lname'].value > #print "address:", form['addr'].value() > print "</body></html>" > ------------------ > > ------------------------------ > > Message: 6 > Date: Tue, 22 Mar 2005 09:21:05 -0600 > From: Michael Lasky <mlasky1@cox.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > To: tutor@python.org > Message-ID: <1111504866.17299.2.camel@localhost.localdomain> > Content-Type: text/plain > > I haven't done too much web stuff (or much of anything) with python, but > I looked into your question a bit (researching other's problems may help > me avoid them =)). A quick search brought up this page which seems to > have information which may help you. > > http://gnosis.cx/publish/programming/feature_5min_python.html > > Hope that helps. > Best Regards, > Michael Lasky > > On Tue, 2005-03-22 at 14:02 +0000, Vicki Stanfield wrote: > > I have recently started doing cgi in Python and have run into a problem. I > > have an html form which has various widgets which accept data. I also have > > this in that html file: > > > > <form action="formdata.py" method="post"> > > > > formdata.py runs but doesn't seem to contain the data from the form. I'm > > not sure of the format for the for with regard to FieldStorage btw. Here > > is the contents of formdata.py: > > > > ---------------- > > #! /usr/bin/python > > import cgitb, os, sys > > cgitb.enable() > > > > import cgi > > > > print "Content-Type: text/html\n\n" > > print "<html><head></head><body>" > > form = cgi.FieldStorage() > > for each in form: > > print "each" > > print form['fname'].value, form['lname'].value > > #print "address:", form['addr'].value() > > print "</body></html>" > > ------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ > > Message: 7 > Date: Tue, 22 Mar 2005 15:33:40 -0000 (GMT) > From: "Vicki Stanfield" <vicki@stanfield.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > To: "Michael Lasky" <mlasky1@cox.net> > Cc: tutor@python.org > Message-ID: <4738.216.37.46.162.1111505620.squirrel@216.37.46.162> > Content-Type: text/plain;charset=iso-8859-1 > > > I haven't done too much web stuff (or much of anything) with python, but > > I looked into your question a bit (researching other's problems may help > > me avoid them =)). A quick search brought up this page which seems to > > have information which may help you. > > > > http://gnosis.cx/publish/programming/feature_5min_python.html > > > > Hope that helps. > > Best Regards, > > Michael Lasky > > I don't see anything in that page that changes what I am doing. I can get > rid of everything that has to do with retrieving data from > cgi-FieldStorage, and the code executes fine although I get a blank page. > I have revised the code somewhat, but the initial problem of > cgi.FieldStorage being empty is still there. I don't get an error now, > just an empty page. Here is the revised code: > > #! /usr/bin/python > print "Content-Type: text/html\n\n" > print > print "<html><head></head><body>\n\n" > > import cgitb, os, sys > cgitb.enable() > sys.strerr = sys.stdout > > import cgi > > form = cgi.FieldStorage() > field_list = '<ul>\n' > for field in form.keys(): > field_list = field_list + '<li>%s</li>\n' % field > field_list = field_list + '</ul>\n' > print field_list > print "</body></html>\n\n" > > ------------------------------ > > Message: 8 > Date: Tue, 22 Mar 2005 10:58:55 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Python cgi doesn't get data from html form as > expected > Cc: tutor@python.org > Message-ID: <424040BF.9070706@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Vicki Stanfield wrote: > > I don't see anything in that page that changes what I am doing. I can get > > rid of everything that has to do with retrieving data from > > cgi-FieldStorage, and the code executes fine although I get a blank page. > > I have revised the code somewhat, but the initial problem of > > cgi.FieldStorage being empty is still there. I don't get an error now, > > just an empty page. Here is the revised code: > > > > #! /usr/bin/python > > print "Content-Type: text/html\n\n" > > print > > print "<html><head></head><body>\n\n" > > > > import cgitb, os, sys > > cgitb.enable() > > sys.strerr = sys.stdout > > > > import cgi > > > > form = cgi.FieldStorage() > > field_list = '<ul>\n' > > for field in form.keys(): > > field_list = field_list + '<li>%s</li>\n' % field > > field_list = field_list + '</ul>\n' > > print field_list > > print "</body></html>\n\n" > > Please post the HTML for the form you are submitting and the HTML from a View Source on the result. > > Kent > > ------------------------------ > > Message: 9 > Date: Tue, 22 Mar 2005 08:59:36 -0600 > From: C Smith <smichr@hotmail.com> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > To: tutor@python.org > Message-ID: <BAY101-DAV11A3B228F1D54EC47048FBC14E0@phx.gbl> > Content-Type: text/plain; charset=US-ASCII; format=flowed > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > tutor-request@python.org wrote: > > > I met a similar question. > > what if one has L = [[1,2],[3,4]], K = [100, 200] > > How to 'zip' a List like [[1,2,100], [3,4,200]]? > > > I would do something like: > > ### > for i in range(len(L)): > L[i].append(K[i]) > ### > > /c > > ------------------------------ > > Message: 10 > Date: Tue, 22 Mar 2005 11:37:11 -0600 > From: C Smith <smichr@hotmail.com> > Subject: Re: [Tutor] primes - sieve of odds > To: tutor@python.org > Message-ID: <BAY101-DAV12AFBD9B03492E7EE99D82C14E0@phx.gbl> > Content-Type: text/plain; charset=US-ASCII; format=flowed > > 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 > > > Hi Sean! > > > > Thanks for your measurements. > > In the meantime I did another amendment, > > leaving out the even numbers from the sieve. > > It goes like this: > > > > def sieve(maximum): > > nums = range(3, maximum+1, 2) > > for p in nums: > > if p: > > if p*p > maximum: break > > start = (p*p-2)//2 > > nums[start::p] = [False]*(1+((maximum-3)//2-start)//p) > > return [2] + filter(None, nums) > > > > Perhaps not very elegant. But approximately twice as fast as > > the former version. > > ------------------------------ > > Message: 11 > Date: Tue, 22 Mar 2005 13:30:09 -0500 > From: Kent Johnson <kent37@tds.net> > Subject: Re: [Tutor] Looking for a Pythonic way to pass variable > Cc: tutor@python.org > Message-ID: <42406431.2040103@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > C Smith wrote: > > > > On Tuesday, Mar 22, 2005, at 05:01 America/Chicago, > > tutor-request@python.org wrote: > > > >> I met a similar question. > >> what if one has L = [[1,2],[3,4]], K = [100, 200] > >> How to 'zip' a List like [[1,2,100], [3,4,200]]? > >> > > I would do something like: > > > > ### > > for i in range(len(L)): > > L[i].append(K[i]) > > ### > > Oh, the light goes on :-) Thanks C Smith! > > Here is another way: > >>> L = [[1,2],[3,4]] > >>> K = [100, 200] > >>> [ x+[y] for x, y in zip(L, K) ] > [[1, 2, 100], [3, 4, 200]] > > Note C Smith's approach modifies L to include the items in K; my approach makes a new list. > > Kent > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > End of Tutor Digest, Vol 13, Issue 65 > ************************************* > From Christian.Wyglendowski at greenville.edu Tue Mar 22 22:47:19 2005 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Tue Mar 22 22:47:31 2005 Subject: [Tutor] iterating through large dictionary Message-ID: <CE1475C007B563499EDBF8CDA30AB45B028B4418@empex.greenville.edu> > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of jeff > > Hi, Hey Jeff, > I'm trying to print out all the attributes of a user account in active > directory. I got a script from: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303348 > /index_txt Hhhmm... I have some code that does basically the same thing, sans the printing. Mine looks up the user based on the sAMAccountName instead of the distinguishedName, though. > Now I'd like it to print pretty. [SNIP function] > user='LDAP://cn=Wardlaw\, Jeff,OU=IS Department,OU=IT > department,DC=acpdom,DC=acp,DC=edu' > for k, v in ad_dict(user): > print "%s=%s" % (k, v) > > I get the following error when I try this: > > D:\Python24>ad-attr.py > Traceback (most recent call last): > File "D:\Python24\ad-attr.py", line 32, in ? > for k, v in ad_dict(user): > ValueError: too many values to unpack Try this instead ... I think it should help: <code> for k,v in ad_dict(user).items(): </code> HTH, Christian http://www.dowski.com From garnaez at gmail.com Tue Mar 22 22:51:08 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Tue Mar 22 22:51:14 2005 Subject: [Tutor] Apology In-Reply-To: <20050322213234.D55F61E4010@bag.python.org> References: <20050322213234.D55F61E4010@bag.python.org> Message-ID: <148eea7105032213515e09da6f@mail.gmail.com> I apologize to the group for the dupes and not cutting the extended tail of my previous messages From smaug9 at gmail.com Tue Mar 22 23:00:13 2005 From: smaug9 at gmail.com (jeff) Date: Tue Mar 22 23:00:19 2005 Subject: [Tutor] iterating through large dictionary In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B028B4418@empex.greenville.edu> References: <CE1475C007B563499EDBF8CDA30AB45B028B4418@empex.greenville.edu> Message-ID: <267a4b3105032214002e9925e@mail.gmail.com> On Tue, 22 Mar 2005 15:47:19 -0600, Christian Wyglendowski <Christian.Wyglendowski@greenville.edu> wrote: > > -----Original Message----- > > From: tutor-bounces@python.org > > [mailto:tutor-bounces@python.org] On Behalf Of jeff > > > > Hi, > > Hey Jeff, > > > I'm trying to print out all the attributes of a user account in active > > directory. I got a script from: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303348 > > /index_txt > > Hhhmm... I have some code that does basically the same thing, sans the > printing. Mine looks up the user based on the sAMAccountName instead of > the distinguishedName, though. > > > Now I'd like it to print pretty. > > [SNIP function] > > > user='LDAP://cn=Wardlaw\, Jeff,OU=IS Department,OU=IT > > department,DC=acpdom,DC=acp,DC=edu' > > for k, v in ad_dict(user): > > print "%s=%s" % (k, v) > > > > I get the following error when I try this: > > > > D:\Python24>ad-attr.py > > Traceback (most recent call last): > > File "D:\Python24\ad-attr.py", line 32, in ? > > for k, v in ad_dict(user): > > ValueError: too many values to unpack > > Try this instead ... I think it should help: > > <code> > > for k,v in ad_dict(user).items(): > > </code> yup, that was it. now i've got to make it pretty. -- --Jeff From shaleh at speakeasy.net Tue Mar 22 23:04:10 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 22 23:06:03 2005 Subject: [Tutor] iterating through large dictionary In-Reply-To: <CE1475C007B563499EDBF8CDA30AB45B028B4418@empex.greenville.edu> References: <CE1475C007B563499EDBF8CDA30AB45B028B4418@empex.greenville.edu> Message-ID: <4240965A.9090204@speakeasy.net> >>D:\Python24>ad-attr.py >>Traceback (most recent call last): >> File "D:\Python24\ad-attr.py", line 32, in ? >> for k, v in ad_dict(user): >>ValueError: too many values to unpack > > > Try this instead ... I think it should help: > > <code> > > for k,v in ad_dict(user).items(): > > </code> in 2.3 and newer, the preferred function is 'iteritems()' instead of 'items()'. Faster, less mem use, etc. From shaleh at speakeasy.net Tue Mar 22 23:05:37 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 22 23:07:19 2005 Subject: [Tutor] Apology In-Reply-To: <148eea7105032213515e09da6f@mail.gmail.com> References: <20050322213234.D55F61E4010@bag.python.org> <148eea7105032213515e09da6f@mail.gmail.com> Message-ID: <424096B1.8090002@speakeasy.net> gerardo arnaez wrote: > I apologize to the group for the dupes and not cutting the extended > tail of my previous messages apology accepted. Your penance is to rewrite one of your python programs in Perl. (-: From cyresse at gmail.com Tue Mar 22 23:17:03 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Mar 22 23:17:07 2005 Subject: [Tutor] OT - SQL methodolgy In-Reply-To: <1111518624.25406.73.camel@laptop.venix.com> References: <1111518624.25406.73.camel@laptop.venix.com> Message-ID: <f2ff2d05032214172ca22c5@mail.gmail.com> Hi Lloyd, it's a SQLite database, with only one app connecting, so I'm not worried about concurrency right here, ( I think SQLite locks when you connect anyway), but it's always good to get pointers on best practise. Thanks to all. On Tue, 22 Mar 2005 14:10:24 -0500, Lloyd Kvam <python@venix.com> wrote: > > > In the SQL books I've got, they always seem to have an optional > select > > > statement on the end of inserts/updates, and I was thinking maybe I > > > could do it that way also, but I can't figure out a logical way of > > > putting > > > > > > 'select primary_key from foo where primary_key value > every other > > > primary_key value' > > > > > > > select max(primary_key) from foo? > > select max will NOT work reliably when you have concurrent database > inserts. You could obtain the number from someone else's insert. > > You need to use the function provided by the RDBMS that is tied to your > connection/cursor so that you retrieve the primary_key that was assigned > to *your* record. > > (I understood your request to be looking for the primary_key > auto-assigned to your insert statement) > > -- > Lloyd Kvam > Venix Corp > > _______________________________________________ > 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. From guadaluperdg at aol.com Tue Mar 22 23:49:45 2005 From: guadaluperdg at aol.com (guadaluperdg@aol.com) Date: Tue Mar 22 23:50:04 2005 Subject: [Tutor] Livewires Help Message-ID: <8C6FD4893F6272F-684-23E80@mblk-r16.sysops.aol.com> Does python tutor cover livewires w.s help? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050322/e9802551/attachment.html From alan.gauld at freenet.co.uk Tue Mar 22 23:59:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 22 23:58:23 2005 Subject: [Tutor] Fwd: Math Question References: <20050322183017.19D451E400F@bag.python.org><148eea71050322133257986b32@mail.gmail.com><148eea7105032213331051b83a@mail.gmail.com> <148eea7105032213335c7666b2@mail.gmail.com> Message-ID: <012c01c52f32$bcc36740$93c28651@xp> OK, No fancy math here, so thee might be a cleaner way, but here is how I'd do it. > (Note the patient only has 5mg tabs, which they can split to make dose > adjust my 2.5) OK< so we are dealing with a unit size of 2.5mg. Convert the total dosage into 2.5mg units. 35mg = 35/2.5 = 14 units Divide the number of units by the number of days using integer division: divmod(14,7) -> 2,0 that tells us you need 2 units per day and no adjustment Add 10% => 14 + 1.4 = 15.4 units. YOu must decide to either round up or down, lets say you round up to 16 units divide the doze as before divmod(16,7) -> 2,2 that says 2 units per day and on 2 days an extra unit. (Which was your guestimate) If you rounded down to 15 divmoid(15,7) -> 2,1 which is 2 units/day and 1 day with an extra unit. > How would I solve this using math instead of geustimating it. > What kind of math am I talking about here? integer math with a hint of quantum techniques thrown in If the above didn't make sense just shout and we can explain in more detail. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From michael.hall at critterpixstudios.com Wed Mar 23 02:10:43 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 23 02:10:31 2005 Subject: [Tutor] .readlines() condensing multiple lines Message-ID: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> 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...? From cappy2112 at gmail.com Wed Mar 23 03:28:24 2005 From: cappy2112 at gmail.com (Tony C) Date: Wed Mar 23 03:28:27 2005 Subject: [Tutor] What does Python gain by having immutable types? In-Reply-To: <20050322213503.3FD6A1E4018@bag.python.org> References: <20050322213503.3FD6A1E4018@bag.python.org> Message-ID: <8249c4ac0503221828789bf59b@mail.gmail.com> A friend recently asked my this didn't modify his original string variable s1="this is a string" s1.replace("is a", "is a short") "this is a short string" print s1 "this is a string" After showing him to change it to this s1 = s1.replace("is a", "is a short") print s1 "this is a short string" He then asked Why is it that the sort operation modfies the original list variable? l1=[] l1.append(3) l1.append(44) l1.append(1) l1.append(22) 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. 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? Does it really matter if s1 is a different object, so long as it contains the expected modified string? The list variable is the same object, and contains the sorted list, so why bother with the complexity of immutable types at all? From shaleh at speakeasy.net Wed Mar 23 03:40:21 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 23 03:42:07 2005 Subject: [Tutor] What does Python gain by having immutable types? In-Reply-To: <8249c4ac0503221828789bf59b@mail.gmail.com> References: <20050322213503.3FD6A1E4018@bag.python.org> <8249c4ac0503221828789bf59b@mail.gmail.com> Message-ID: <4240D715.8040800@speakeasy.net> Tony C wrote: > > The list variable is the same object, and contains the sorted list, so > why bother with the complexity of immutable types at all? * only immutable objects can be dictionary keys * specifically immutable strings are a performance optimization From garnaez at gmail.com Wed Mar 23 03:47:43 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Wed Mar 23 03:47:46 2005 Subject: [Tutor] Fwd: Math Question In-Reply-To: <012c01c52f32$bcc36740$93c28651@xp> References: <20050322183017.19D451E400F@bag.python.org> <148eea71050322133257986b32@mail.gmail.com> <148eea7105032213331051b83a@mail.gmail.com> <148eea7105032213335c7666b2@mail.gmail.com> <012c01c52f32$bcc36740$93c28651@xp> Message-ID: <148eea71050322184740304a2c@mail.gmail.com> On Tue, 22 Mar 2005 22:59:00 -0000, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > OK, No fancy math here, so thee might be a cleaner way, but here > is how I'd do it. > Yikes. Thanks for insight and solving it, Btw, I bought your book a while ago and it was the first that explained classes to me in a a a way I got it, by explaining exactly what *self* stood for in all the examples. All the other books just went on, and never even thought of explaining leaving me for months in a dizzy on what the heck *self* meant in making classes Thanks for that and the help here > > (Note the patient only has 5mg tabs, which they can split to make > dose > > adjust my 2.5) > > OK< so we are dealing with a unit size of 2.5mg. Convert the total > dosage into 2.5mg units. 35mg = 35/2.5 = 14 units > > Divide the number of units by the number of days using integer > division: > > divmod(14,7) -> 2,0 > > that tells us you need 2 units per day and no adjustment > > Add 10% => 14 + 1.4 = 15.4 units. YOu must decide to either > round up or down, lets say you round up to 16 units > > divide the doze as before > > divmod(16,7) -> 2,2 > > that says 2 units per day and on 2 days an extra unit. > (Which was your guestimate) > > If you rounded down to 15 > > divmoid(15,7) -> 2,1 > > which is 2 units/day and 1 day with an extra unit. > > > How would I solve this using math instead of geustimating it. > > What kind of math am I talking about here? > > integer math with a hint of quantum techniques thrown in > > If the above didn't make sense just shout and we can explain > in more detail. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From cyresse at gmail.com Wed Mar 23 04:15:51 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 23 04:15:54 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> Message-ID: <f2ff2d05032219152d0de75e@mail.gmail.com> >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 <michael.hall@critterpixstudios.com> 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. From kent37 at tds.net Wed Mar 23 06:03:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 06:04:10 2005 Subject: [Tutor] Livewires Help In-Reply-To: <8C6FD4893F6272F-684-23E80@mblk-r16.sysops.aol.com> References: <8C6FD4893F6272F-684-23E80@mblk-r16.sysops.aol.com> Message-ID: <4240F8BE.3080103@tds.net> guadaluperdg@aol.com wrote: > Does python tutor cover livewires w.s help? We will try to answer any questions except direct homework questions. Do you have a specific question or problem? Kent From kent37 at tds.net Wed Mar 23 06:12:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 06:12:16 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <f2ff2d05032219152d0de75e@mail.gmail.com> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <f2ff2d05032219152d0de75e@mail.gmail.com> Message-ID: <4240FAAC.10002@tds.net> Liam Clarke wrote: > Worse come to worse, you could always do - > x = file(myFile, 'r').read() > listX = x.split('\r') This will leave the \n in the strings. Reading with universal newlines is a better solution. Kent From cyresse at gmail.com Wed Mar 23 06:19:37 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 23 06:19:40 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <4240FAAC.10002@tds.net> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <f2ff2d05032219152d0de75e@mail.gmail.com> <4240FAAC.10002@tds.net> Message-ID: <f2ff2d0503222119172a007e@mail.gmail.com> Oh right, From his email, I got the impression he was getting a list like - [[abc\rdef\rghi\r]] On Wed, 23 Mar 2005 00:12:12 -0500, Kent Johnson <kent37@tds.net> wrote: > Liam Clarke wrote: > > Worse come to worse, you could always do - > > x = file(myFile, 'r').read() > > listX = x.split('\r') > > This will leave the \n in the strings. Reading with universal newlines is a better solution. > > Kent > > _______________________________________________ > 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. From alan.gauld at freenet.co.uk Wed Mar 23 09:49:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 23 09:49:19 2005 Subject: [Tutor] Livewires Help References: <8C6FD4893F6272F-684-23E80@mblk-r16.sysops.aol.com> Message-ID: <016201c52f85$4ab9bed0$93c28651@xp> 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: <guadaluperdg@aol.com> To: <tutor@python.org> Sent: Tuesday, March 22, 2005 10:49 PM Subject: [Tutor] Livewires Help > Does python tutor cover livewires w.s help? > From alan.gauld at freenet.co.uk Wed Mar 23 09:53:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 23 09:53:11 2005 Subject: [Tutor] .readlines() condensing multiple lines References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> Message-ID: <016901c52f85$d4578af0$93c28651@xp> > 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 From alan.gauld at freenet.co.uk Wed Mar 23 09:59:48 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 23 09:59:05 2005 Subject: [Tutor] What does Python gain by having immutable types? References: <20050322213503.3FD6A1E4018@bag.python.org> <8249c4ac0503221828789bf59b@mail.gmail.com> Message-ID: <017201c52f86$ab38b2b0$93c28651@xp> > 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. From glingl at aon.at Wed Mar 23 09:59:31 2005 From: glingl at aon.at (Gregor Lingl) Date: Wed Mar 23 09:59:22 2005 Subject: [Tutor] primes - sieve of odds In-Reply-To: <BAY101-DAV12AFBD9B03492E7EE99D82C14E0@phx.gbl> References: <BAY101-DAV12AFBD9B03492E7EE99D82C14E0@phx.gbl> Message-ID: <42412FF3.2040102@aon.at> 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 From davholla2002 at yahoo.co.uk Wed Mar 23 10:20:16 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed Mar 23 10:20:18 2005 Subject: [Tutor] Livewires Message-ID: <20050323092016.68340.qmail@web25405.mail.ukl.yahoo.com> 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050323/74b68291/attachment.htm From dianahawks at optusnet.com.au Wed Mar 23 10:59:02 2005 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Wed Mar 23 11:00:30 2005 Subject: [Tutor] blocking user access Message-ID: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> 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! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050323/dc2bf1ac/attachment.htm From cyresse at gmail.com Wed Mar 23 11:21:35 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 23 11:21:40 2005 Subject: [Tutor] blocking user access In-Reply-To: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> References: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> Message-ID: <f2ff2d050323022145258072@mail.gmail.com> 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 <dianahawks@optusnet.com.au> 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. From cyresse at gmail.com Wed Mar 23 11:43:39 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 23 11:43:42 2005 Subject: [Tutor] List comprehensions Message-ID: <f2ff2d0503230243374c4079@mail.gmail.com> 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. From kent37 at tds.net Wed Mar 23 12:17:08 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 12:17:12 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <f2ff2d0503222119172a007e@mail.gmail.com> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <f2ff2d05032219152d0de75e@mail.gmail.com> <4240FAAC.10002@tds.net> <f2ff2d0503222119172a007e@mail.gmail.com> Message-ID: <42415034.1060403@tds.net> 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 From kent37 at tds.net Wed Mar 23 12:20:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 12:21:02 2005 Subject: [Tutor] Livewires Help In-Reply-To: <016201c52f85$4ab9bed0$93c28651@xp> References: <8C6FD4893F6272F-684-23E80@mblk-r16.sysops.aol.com> <016201c52f85$4ab9bed0$93c28651@xp> Message-ID: <42415118.30908@tds.net> 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 From kent37 at tds.net Wed Mar 23 12:26:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 12:26:34 2005 Subject: [Tutor] blocking user access In-Reply-To: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> References: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> Message-ID: <42415266.1030805@tds.net> 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 From kent37 at tds.net Wed Mar 23 12:30:35 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 12:30:40 2005 Subject: [Tutor] List comprehensions In-Reply-To: <f2ff2d0503230243374c4079@mail.gmail.com> References: <f2ff2d0503230243374c4079@mail.gmail.com> Message-ID: <4241535B.9050108@tds.net> 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 From ryan at acceleration.net Wed Mar 23 16:15:53 2005 From: ryan at acceleration.net (Ryan Davis) Date: Wed Mar 23 16:15:57 2005 Subject: [Tutor] List comprehensions In-Reply-To: <f2ff2d0503230243374c4079@mail.gmail.com> Message-ID: <20050323151555.C45CE1E4005@bag.python.org> 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: tutor-bounces@python.org [mailto:tutor-bounces@python.org] 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 From shaleh at speakeasy.net Wed Mar 23 18:35:53 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 23 18:37:47 2005 Subject: [Tutor] List comprehensions In-Reply-To: <f2ff2d0503230243374c4079@mail.gmail.com> References: <f2ff2d0503230243374c4079@mail.gmail.com> Message-ID: <4241A8F9.9030001@speakeasy.net> 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 (-: From kent37 at tds.net Wed Mar 23 18:52:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 18:52:17 2005 Subject: [Tutor] List comprehensions In-Reply-To: <f2ff2d0503230243374c4079@mail.gmail.com> References: <f2ff2d0503230243374c4079@mail.gmail.com> Message-ID: <4241ACCD.5030604@tds.net> Liam Clarke wrote: > Is there any guides to this (possibly obtuse) tool? http://docs.python.org/tut/node7.html#SECTION007140000000000000000 http://www.amk.ca/python/2.0/index.html#SECTION000600000000000000000 Kent From vicki at stanfield.net Wed Mar 23 19:06:59 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Wed Mar 23 19:08:36 2005 Subject: [Tutor] Getting error that calendar is underfined when importing calendar module Message-ID: <3845.216.37.46.162.1111601219.squirrel@216.37.46.162> 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 "<html><head></head><body>\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 = <module 'calendar' from '/var/www/cgi-bin/calendar.py'>, calendar.prmonth undefined, builtin int = <type '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 From kent37 at tds.net Wed Mar 23 19:30:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 19:30:32 2005 Subject: [Tutor] Getting error that calendar is underfined when importing calendar module In-Reply-To: <3845.216.37.46.162.1111601219.squirrel@216.37.46.162> References: <3845.216.37.46.162.1111601219.squirrel@216.37.46.162> Message-ID: <4241B5C5.4040409@tds.net> 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 "<html><head></head><body>\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 = <module 'calendar' from '/var/www/cgi-bin/calendar.py'>, > calendar.prmonth undefined, builtin int = <type '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 > From michael.hall at critterpixstudios.com Wed Mar 23 19:35:29 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 23 19:35:17 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <f2ff2d05032219152d0de75e@mail.gmail.com> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <f2ff2d05032219152d0de75e@mail.gmail.com> Message-ID: <bc6b8b5096f9319b9ade85efbf029b3b@critterpixstudios.com> 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 > <michael.hall@critterpixstudios.com> 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. > -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 2264 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050323/6db9a553/attachment-0001.bin From vicki at stanfield.net Wed Mar 23 19:34:56 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Wed Mar 23 19:36:35 2005 Subject: [Tutor] Getting error that calendar is underfined when importing calendar module In-Reply-To: <4241B5C5.4040409@tds.net> References: <3845.216.37.46.162.1111601219.squirrel@216.37.46.162> <4241B5C5.4040409@tds.net> Message-ID: <4793.216.37.46.162.1111602896.squirrel@216.37.46.162> > 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. From michael.hall at critterpixstudios.com Wed Mar 23 19:40:32 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 23 19:40:28 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <016901c52f85$d4578af0$93c28651@xp> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <016901c52f85$d4578af0$93c28651@xp> Message-ID: <136fe8cdb7b28269c5e61523bcc115c7@critterpixstudios.com> 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 :) From michael.hall at critterpixstudios.com Wed Mar 23 19:44:38 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Wed Mar 23 19:44:17 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <42415034.1060403@tds.net> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <f2ff2d05032219152d0de75e@mail.gmail.com> <4240FAAC.10002@tds.net> <f2ff2d0503222119172a007e@mail.gmail.com> <42415034.1060403@tds.net> Message-ID: <e708856ffc4d226a568c05d40f8e0d63@critterpixstudios.com> 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. From kent37 at tds.net Wed Mar 23 20:01:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 23 20:01:39 2005 Subject: [Tutor] .readlines() condensing multiple lines In-Reply-To: <e708856ffc4d226a568c05d40f8e0d63@critterpixstudios.com> References: <fd8e7129f7b285d38d5dc799c5058404@critterpixstudios.com> <f2ff2d05032219152d0de75e@mail.gmail.com> <4240FAAC.10002@tds.net> <f2ff2d0503222119172a007e@mail.gmail.com> <42415034.1060403@tds.net> <e708856ffc4d226a568c05d40f8e0d63@critterpixstudios.com> Message-ID: <4241BD10.2020100@tds.net> 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 From jfouhy at paradise.net.nz Wed Mar 23 21:12:33 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Wed Mar 23 21:15:23 2005 Subject: [Tutor] List comprehensions In-Reply-To: <20050323151555.C45CE1E4005@bag.python.org> References: <20050323151555.C45CE1E4005@bag.python.org> Message-ID: <4241CDB1.8080700@paradise.net.nz> 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. From jfouhy at paradise.net.nz Wed Mar 23 21:17:13 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Wed Mar 23 21:17:15 2005 Subject: [Tutor] blocking user access In-Reply-To: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> References: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> Message-ID: <4241CEC9.8080601@paradise.net.nz> 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 '<Key>' to nothing in the entry widget. eg: self.answer = Tkinter.Entry(master) def noop(e): return 'break' self.answer.bind('<Key>', 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. From alan.gauld at freenet.co.uk Wed Mar 23 21:24:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 23 21:23:47 2005 Subject: [Tutor] List comprehensions References: <f2ff2d0503230243374c4079@mail.gmail.com> Message-ID: <01b201c52fe6$535ec330$93c28651@xp> > 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. From igor.r at vodafone.net Wed Mar 23 21:49:11 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Wed Mar 23 21:49:28 2005 Subject: [Tutor] problems with dictionary Message-ID: <000e01c52fe9$c4ae9b70$c000a8c0@ARCISDESKTOP> 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('<Key>', 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050323/0ca3347f/attachment.html From bill.mill at gmail.com Wed Mar 23 21:55:56 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed Mar 23 21:55:59 2005 Subject: [Tutor] problems with dictionary In-Reply-To: <000e01c52fe9$c4ae9b70$c000a8c0@ARCISDESKTOP> References: <000e01c52fe9$c4ae9b70$c000a8c0@ARCISDESKTOP> Message-ID: <797fe3d4050323125547053150@mail.gmail.com> On Wed, 23 Mar 2005 20:49:11 -0000, Igor Riabtchuk <igor.r@vodafone.net> 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('<Key>', 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 From cyresse at gmail.com Wed Mar 23 21:56:37 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 23 21:56:41 2005 Subject: [Tutor] List comprehensions In-Reply-To: <01b201c52fe6$535ec330$93c28651@xp> References: <f2ff2d0503230243374c4079@mail.gmail.com> <01b201c52fe6$535ec330$93c28651@xp> Message-ID: <f2ff2d05032312567037b79f@mail.gmail.com> 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 -0000, Alan Gauld <alan.gauld@freenet.co.uk> 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. From igor.r at vodafone.net Wed Mar 23 23:00:22 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Wed Mar 23 23:00:37 2005 Subject: [Tutor] Dictionary blues... Message-ID: <003101c52ff3$b622a790$c000a8c0@ARCISDESKTOP> I posted the wrong code before. The code is: from Tkinter import * D={a:"tom", b:"dick", c:"harry"} text.bind('<Key>', 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 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050323/e796be00/attachment.html From dyoo at hkn.eecs.berkeley.edu Wed Mar 23 23:18:02 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Mar 23 23:18:09 2005 Subject: [Tutor] Dictionary blues... In-Reply-To: <003101c52ff3$b622a790$c000a8c0@ARCISDESKTOP> Message-ID: <Pine.LNX.4.44.0503231415330.4085-100000@hkn.eecs.berkeley.edu> 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('<Key>', 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. From alan.gauld at freenet.co.uk Wed Mar 23 23:37:53 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 23 23:38:01 2005 Subject: [Tutor] problems with dictionary References: <000e01c52fe9$c4ae9b70$c000a8c0@ARCISDESKTOP> Message-ID: <01fb01c52ff8$f459d510$93c28651@xp> > D={a:"tom", b:"dick", c:"harry"} You don't have quotes around the keys. > > text.bind('<Key>', 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. From maxnoel_fr at yahoo.fr Wed Mar 23 23:41:07 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Mar 23 23:41:13 2005 Subject: [Tutor] problems with dictionary In-Reply-To: <797fe3d4050323125547053150@mail.gmail.com> References: <000e01c52fe9$c4ae9b70$c000a8c0@ARCISDESKTOP> <797fe3d4050323125547053150@mail.gmail.com> Message-ID: <514e053024c39da91ebc0c8b49cbbbcf@yahoo.fr> 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?" From alan.gauld at freenet.co.uk Thu Mar 24 00:17:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 00:17:35 2005 Subject: [Tutor] Dictionary blues... References: <003101c52ff3$b622a790$c000a8c0@ARCISDESKTOP> Message-ID: <022401c52ffe$7e0172f0$93c28651@xp> 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('<Key>', 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('<Key>', 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 From smichr at hotmail.com Thu Mar 24 00:17:06 2005 From: smichr at hotmail.com (C Smith) Date: Thu Mar 24 00:18:20 2005 Subject: [Tutor] primes - sieve of odds In-Reply-To: <20050323100046.86B961E4014@bag.python.org> Message-ID: <BAY101-DAV2DD275E3F901B9D6B29C2C14F0@phx.gbl> On Wednesday, Mar 23, 2005, at 04:00 America/Chicago, tutor-request@python.org 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 ### From igor.r at vodafone.net Thu Mar 24 00:51:21 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Thu Mar 24 00:51:34 2005 Subject: [Tutor] Dictionary blues... References: <003101c52ff3$b622a790$c000a8c0@ARCISDESKTOP> <022401c52ffe$7e0172f0$93c28651@xp> Message-ID: <003c01c53003$36ee01d0$c000a8c0@ARCISDESKTOP> 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('<Key>', 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" <alan.gauld@freenet.co.uk> To: "Igor Riabtchuk" <igor.r@vodafone.net>; <tutor@python.org> 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('<Key>', 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('<Key>', 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 > > From igor.r at vodafone.net Thu Mar 24 00:58:39 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Thu Mar 24 00:58:51 2005 Subject: [Tutor] Dictionary blues... References: <003101c52ff3$b622a790$c000a8c0@ARCISDESKTOP><022401c52ffe$7e0172f0$93c28651@xp> <003c01c53003$36ee01d0$c000a8c0@ARCISDESKTOP> Message-ID: <004001c53004$3c508700$c000a8c0@ARCISDESKTOP> 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" <igor.r@vodafone.net> To: <tutor@python.org> 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('<Key>', 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" <alan.gauld@freenet.co.uk> > To: "Igor Riabtchuk" <igor.r@vodafone.net>; <tutor@python.org> > 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('<Key>', 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('<Key>', 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 > From vicki at stanfield.net Thu Mar 24 01:01:30 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Thu Mar 24 01:03:09 2005 Subject: [Tutor] Passing data from html to py Message-ID: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> 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 "<html><head></head><body>\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 "</body></html>\n\n" --------------------------- From jfouhy at paradise.net.nz Thu Mar 24 01:14:18 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu Mar 24 01:14:23 2005 Subject: [Tutor] Passing data from html to py In-Reply-To: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> References: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> Message-ID: <1111623258.4242065ad80ff@www.paradise.net.nz> Quoting Vicki Stanfield <vicki@stanfield.net>: > 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. From jeannot18 at hotmail.com Thu Mar 24 01:30:22 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu Mar 24 01:30:25 2005 Subject: [Tutor] I need some guidance Message-ID: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> 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 From jfouhy at paradise.net.nz Thu Mar 24 01:55:34 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu Mar 24 01:55:39 2005 Subject: [Tutor] Passing data from html to py In-Reply-To: <1298.192.168.11.11.1111624823.squirrel@192.168.11.11> References: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> <1111623258.4242065ad80ff@www.paradise.net.nz> <1298.192.168.11.11.1111624823.squirrel@192.168.11.11> Message-ID: <1111625734.4242100653c26@www.paradise.net.nz> Quoting Vicki Stanfield <vicki@stanfield.net>: > > 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<br>' % (key, form[key].value). -- John. From askoose at sandia.gov Thu Mar 24 01:53:15 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Mar 24 01:57:02 2005 Subject: [Tutor] I need some guidance Message-ID: <A0CE32554BD73A4481FE85C3F39DB6FC0AEEB2@ES21SNLNT.srn.sandia.gov> 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. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050323/34b6945a/attachment.htm From amonroe at columbus.rr.com Thu Mar 24 01:59:59 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Mar 24 02:00:55 2005 Subject: [Tutor] I need some guidance In-Reply-To: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> References: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> Message-ID: <1062005393.20050323195959@columbus.rr.com> > 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 From jfouhy at paradise.net.nz Thu Mar 24 02:04:23 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu Mar 24 02:04:51 2005 Subject: [Tutor] I need some guidance In-Reply-To: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> References: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> Message-ID: <1111626263.424212178a51a@www.paradise.net.nz> Quoting John Carmona <jeannot18@hotmail.com>: > 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. From vicki at stanfield.net Thu Mar 24 02:04:58 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Thu Mar 24 02:06:38 2005 Subject: [Tutor] Passing data from html to py In-Reply-To: <1111625734.4242100653c26@www.paradise.net.nz> References: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> <1111623258.4242065ad80ff@www.paradise.net.nz> <1298.192.168.11.11.1111624823.squirrel@192.168.11.11> <1111625734.4242100653c26@www.paradise.net.nz> Message-ID: <1343.192.168.11.11.1111626298.squirrel@192.168.11.11> > > 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<br>' % (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 From cyresse at gmail.com Thu Mar 24 02:22:01 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Mar 24 02:22:05 2005 Subject: [Tutor] I need some guidance In-Reply-To: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> References: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> Message-ID: <f2ff2d050323172215423eb2@mail.gmail.com> On Thu, 24 Mar 2005 00:30:22 +0000, John Carmona <jeannot18@hotmail.com> 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. From vicki at stanfield.net Thu Mar 24 03:28:47 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Thu Mar 24 03:30:27 2005 Subject: [Tutor] Passing data from html to py In-Reply-To: <1111625734.4242100653c26@www.paradise.net.nz> References: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> <1111623258.4242065ad80ff@www.paradise.net.nz> <1298.192.168.11.11.1111624823.squirrel@192.168.11.11> <1111625734.4242100653c26@www.paradise.net.nz> Message-ID: <1467.192.168.11.11.1111631327.squirrel@192.168.11.11> 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<br>" % (key, form[key].value) It works fine except for when the key is to a list object made by the following select statement: <select id="prod[]" name="prod[]" multiple="multiple" size="4"> <option id="MB" name="MB">Motherboards</option> <option id="CPU" name="CPU">Processors</option> <option id="Case" name="Case">Cases</option> <option id="Power" name="Power">Power Supplies</option> <option id="Mem" name="Mem">Memory</option> <option id="HD" name="HD">Hard Drives</option> <option id="Periph" name="Periph">Peripherals</option> </select> 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 From kent37 at tds.net Thu Mar 24 04:07:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 24 04:08:02 2005 Subject: [Tutor] Passing data from html to py In-Reply-To: <1467.192.168.11.11.1111631327.squirrel@192.168.11.11> References: <1135.192.168.11.11.1111622490.squirrel@192.168.11.11> <1111623258.4242065ad80ff@www.paradise.net.nz> <1298.192.168.11.11.1111624823.squirrel@192.168.11.11> <1111625734.4242100653c26@www.paradise.net.nz> <1467.192.168.11.11.1111631327.squirrel@192.168.11.11> Message-ID: <42422F0D.3070704@tds.net> 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<br>" % (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<br>" % (key, value) Kent > > It works fine except for when the key is to a list object made by the > following select statement: > > <select id="prod[]" name="prod[]" multiple="multiple" size="4"> > <option id="MB" name="MB">Motherboards</option> > <option id="CPU" name="CPU">Processors</option> > <option id="Case" name="Case">Cases</option> > <option id="Power" name="Power">Power Supplies</option> > <option id="Mem" name="Mem">Memory</option> > <option id="HD" name="HD">Hard Drives</option> > <option id="Periph" name="Periph">Peripherals</option> > </select> > > 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 > From keridee at jayco.net Thu Mar 24 04:12:25 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Mar 24 04:11:45 2005 Subject: [Tutor] I need some guidance References: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> <f2ff2d050323172215423eb2@mail.gmail.com> Message-ID: <002601c5301f$53071660$625328cf@JSLAPTOP> 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 From tegmine at gmail.com Thu Mar 24 04:31:03 2005 From: tegmine at gmail.com (Luis N) Date: Thu Mar 24 04:31:06 2005 Subject: [Tutor] xmlrpc server Message-ID: <77bfa81a05032319317e967a1c@mail.gmail.com> 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? From smichr at hotmail.com Thu Mar 24 06:44:31 2005 From: smichr at hotmail.com (C Smith) Date: Thu Mar 24 06:45:39 2005 Subject: [Tutor] primes - sieve of odds Message-ID: <BAY101-DAV753C6E5362F9D2E2C33ACC1400@phx.gbl> >> 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 From alan.gauld at freenet.co.uk Thu Mar 24 09:35:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 09:35:36 2005 Subject: [Tutor] Dictionary blues... References: <003101c52ff3$b622a790$c000a8c0@ARCISDESKTOP> <022401c52ffe$7e0172f0$93c28651@xp> Message-ID: <023b01c5304c$76139610$93c28651@xp> > > 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. Oops, that should say remove 'self.' not text. Alan G. From alan.gauld at freenet.co.uk Thu Mar 24 09:45:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 09:46:08 2005 Subject: [Tutor] I need some guidance References: <BAY20-F15464567D305618A8A8125B3400@phx.gbl> Message-ID: <025101c5304d$e6b82510$93c28651@xp> > Hi to everyone first, this is my first posting and I hope that I won't make > a mess. Hello and welcome. > I have started by reading the excellent "Non-ProgrammersTutorial For Python" > by Josh Cogliati. I like it a lot. It's a fine intro to Python and programming. > 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, understanding often comes with use. Just follow the template in the examples and make changes. Watch the effect of the changes and see how it works. It will usually drop into place. If you have specifoc questions send an email to this list. > field of programming is there a specific technique to learn other than just > read everything I put my hand on? Read a lot and experiment a lot. Thats where Pythons >>> prompt really helps. You can build quite sophisticated programs very quickly just by typing at the >>> prompt. The only snag being that you can't then save them! > 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. With a little bit of skill you can join one of the open source projects on source forge. Maybe writing documentation initially and later fixing bugs and finally adding features. Find a project you find interesting, download the application and get familiar with using it, then sign up to join the project... most are desparate for volunteers! > I apologise for my English as it is not my first language and thank in > advance anybody that will help me with my queries. Good enough to fool me. I'd never have guessed if you hadn't told us. Alan G. From dianahawks at optusnet.com.au Thu Mar 24 10:27:40 2005 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Thu Mar 24 10:30:07 2005 Subject: [Tutor] blocking user access References: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> <f2ff2d050323022145258072@mail.gmail.com> Message-ID: <000801c53053$d9061340$c608a4cb@dianahawks> Liam, I am using IDLE - and Tkinter, John and Liam. I have been working through the book "Python Programming" by Michael Dawson. One of his programs calls for the entry of a password, then reveals a message. What I would like to do is make the Text widget that reveals the message, unusable by a user! I tried the state = DISABLED in the 2nd line of code below, where the widget to display the text is created - and it did disable the Text widget - to the extent that it wouldn't reveal the message! I have tried multiple other places to put the DISABLED - at the end of this code for instance, but it doesn't seem to work there! Where can I place it so that it will prevent a user access to that Text widget? Also - assuming I can get it to work - what is the term I need to use to enable to Text widget again so that it will continue to work the next time around. I tried ENABLED - but was told that global name is not defined! Any ideas? Thanks in advance for suggestions. Diana Here is the code: # create text widget to display message self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD) self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W) def reveal(self): """ Display message based on password. """ contents = self.pw_ent.get() if contents == "secret": message = "Here's the secret to living to 100: live to 99 " \ "and then be VERY careful." else: message = "That's not the correct password, so I can't share " \ "the secret with you." self.secret_txt.delete(0.0, END) self.secret_txt.insert(0.0, message) > 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 > <dianahawks@optusnet.com.au> 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. From sigurd at 12move.de Thu Mar 24 12:49:17 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Thu Mar 24 12:53:36 2005 Subject: [Tutor] List comprehensions In-Reply-To: <4241CDB1.8080700@paradise.net.nz> (John Fouhy's message of "Thu, 24 Mar 2005 08:12:33 +1200") References: <20050323151555.C45CE1E4005@bag.python.org> <4241CDB1.8080700@paradise.net.nz> Message-ID: <uis3hb72y.fsf@hamster.pflaesterer.de> On 23 Mrz 2005, jfouhy@paradise.net.nz wrote: > map is (probably) going to be removed in Python3000 :-( So it's > probably better to not get into the habit of using it. Au contraire. If enough people use it and are used using it the risk for `map' getting removed will be a lot lower. Furthermore there will also be a functional module which will perhaps include `map' (also it's better to have it as a builtin). The same is true IMO e.g. `filter' or `reduce'. Karl -- Please do *not* send copies of replies to me. I read the list From kent37 at tds.net Thu Mar 24 13:51:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 24 13:51:41 2005 Subject: [Tutor] blocking user access In-Reply-To: <000801c53053$d9061340$c608a4cb@dianahawks> References: <003501c52f8e$f22994c0$5ec41dd3@dianahawks> <f2ff2d050323022145258072@mail.gmail.com> <000801c53053$d9061340$c608a4cb@dianahawks> Message-ID: <4242B7D9.70102@tds.net> Diana Hawksworth wrote: > Liam, I am using IDLE - and Tkinter, John and Liam. I have been working > through the book "Python Programming" by Michael Dawson. One of his > programs calls for the entry of a password, then reveals a message. What I > would like to do is make the Text widget that reveals the message, unusable > by a user! > > I tried the state = DISABLED in the 2nd line of code below, where the widget > to display the text is created - and it did disable the Text widget - to the > extent that it wouldn't reveal the message! I have tried multiple other > places to put the DISABLED - at the end of this code for instance, but it > doesn't seem to work there! Where can I place it so that it will prevent a > user access to that Text widget? > > Also - assuming I can get it to work - what is the term I need to use to > enable to Text widget again so that it will continue to work the next time > around. I tried ENABLED - but was told that global name is not defined! Here is a snippet from Fredrik Lundh's "An Introduction to Tkinter" that shows how to enable the widget, insert some text, then disable it again: text.config(state=NORMAL) text.delete(1.0, END) text.insert(END, text) text.config(state=DISABLED) from http://www.pythonware.com/library/tkinter/introduction/x8309-patterns.htm Kent > > Any ideas? Thanks in advance for suggestions. > > Diana > > Here is the code: > > # create text widget to display message > self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD) > self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = > W) > > def reveal(self): > """ Display message based on password. """ > contents = self.pw_ent.get() > if contents == "secret": > message = "Here's the secret to living to 100: live to 99 " \ > "and then be VERY careful." > > else: > message = "That's not the correct password, so I can't share " \ > "the secret with you." > > self.secret_txt.delete(0.0, END) > self.secret_txt.insert(0.0, message) > > > > > >>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 >><dianahawks@optusnet.com.au> 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 > From vicki at stanfield.net Thu Mar 24 16:51:15 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Thu Mar 24 16:52:54 2005 Subject: [Tutor] Mysqldb module - where ????? Message-ID: <1895.216.37.46.162.1111679475.squirrel@216.37.46.162> I am googling for a slackware package containing the Mysqldb module, but all I am coming up with is MySQLdb. I am not hallucinating right? They are indeed two separate modules? Vicki From jeannot18 at hotmail.com Thu Mar 24 17:50:21 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu Mar 24 17:50:27 2005 Subject: [Tutor] I need some guidance In-Reply-To: <f2ff2d050323172215423eb2@mail.gmail.com> Message-ID: <BAY20-F2330731998F8FF9EBF37A0B3400@phx.gbl> Thanks everybody for their input. It is great to know that there are some people ready to help. Ara Kooser, what I meant by this "science", I have meant programming, sorry if I was not too clear. Alan, I will check those programming contests you were talking about, but only when I will feel ready for it. Liam thanks for all the advices, I have started to read Alan's tutorial also (so much to read and not enough time). Thanks Jacob for the tips also. Alan, I am a bit lost when you wrote: " Read a lot and experiment a lot. Thats where Pythons >>> prompt really helps. You can build quite sophisticated programs very quickly just by typing at the >>> prompt. The only snag being that you can't then save them! So far I have been using IDLE Python GUY apps, working on some of the examples from the tutorials, saving them and pressing F5 to run them. (I use by the way Windows XP and the Python v2.4). Do you mean writing from the Command Line windows instead to use the IDLE one? Thanks also for pointing out about the Open Source Projects, i will check that out once I feel confident enough (probably will take a while) From ismaelgf at adinet.com.uy Thu Mar 24 18:07:31 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Thu Mar 24 18:07:37 2005 Subject: [Tutor] Changing a class into a subclass Message-ID: <4242F3D3.9000501@adinet.com.uy> Hello. I have a program that saves/loads to/from XML. I have a main class Building, and a subclass House(Building). When I save the code I instruct each object to save itself to XML (using ElementTree), so House adds itself to the XML tree. My problem is when I load the XML. Before having subclasses what I did was to send the XML object (again in ElementTree) to the object and let itself load. Now, with subclasses, if I send the House XML to Building I get a Building instance, when I need a House instance. I couldn't figure out a way to make a Building instance turn into a House instance. Is there any way? Or I'll just have to rewrite the whole XML loading scheme and have a particular function doing all the loading? Thanks for any help. Ismael From igor.r at vodafone.net Thu Mar 24 19:05:25 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Thu Mar 24 19:05:45 2005 Subject: [Tutor] Tkinter and keyboard output Message-ID: <000901c5309c$0e423aa0$c000a8c0@ARCISDESKTOP> Hi, I was playing around with Tkinter bindings and I got a question which is probably not particularly bright. If I have the following code, it works because I specifically code a function for <Alt-p> keypress: from Tkinter import * class CRED(Frame): def __init__(self): Frame.__init__(self) self.txt=Text(self) self.txt.bind('<Alt-p>', self.conv) self.txt.pack() self.pack() self.txt.focus() def conv(self,event): self.txt.insert(END,'t') return 'break' app=CRED() app.mainloop() What if instead of coding <Alt-p>, I coded <Alt-Key> - how would I implement the function which would allow the code to determine which 'Key' was pressed after Alt? Thank you. Igor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050324/3e6b0b5c/attachment.html From john.ertl at fnmoc.navy.mil Thu Mar 24 19:10:16 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Mar 24 19:07:45 2005 Subject: [Tutor] re question Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C5B6@lanexc107p.fnmoc.navy.mil> All I have a string that has a bunch of numbers with the units attached to them. I want to strip off the units. I am using a regular expression and sub to do this. This works great for almost all of the cases. These are the type of lines: SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts SigWind: 850hPa?, , , , 205 @ 11kts Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts I am using the following cleanstring = re.compile( '(hPa|hPa\xb1|m|C|kts)' ). And then the cleanstring.sub("",line). I have tried using numerous \ to escape the \xb1. I also tried replacing all non numeric characters that are part of a number-character string but I could not make that work. The idea was replace all non-number characters in a "word" that is made up of numbers followed by numbers. I then split the line at the commas so in the current thinking I need the commas for the split. How do I deal with the hPa?? When I print it out it looks like it is a hexadecimal escape character (\xb1) but I am note sure how to deal with this. Any ideas? Thanks From maxnoel_fr at yahoo.fr Thu Mar 24 19:30:34 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Mar 24 19:30:38 2005 Subject: [Tutor] Changing a class into a subclass In-Reply-To: <4242F3D3.9000501@adinet.com.uy> References: <4242F3D3.9000501@adinet.com.uy> Message-ID: <8a50240d2251124e842a9d327a85917b@yahoo.fr> On Mar 24, 2005, at 18:07, Ismael Garrido wrote: > Hello. > > I have a program that saves/loads to/from XML. I have a main class > Building, and a subclass House(Building). When I save the code I > instruct each object to save itself to XML (using ElementTree), so > House adds itself to the XML tree. > My problem is when I load the XML. Before having subclasses what I did > was to send the XML object (again in ElementTree) to the object and > let itself load. Now, with subclasses, if I send the House XML to > Building I get a Building instance, when I need a House instance. You can't make an object transform into an object of a different class. You need to identify what class the object will be an instance of before loading it. Which, if you're using XML tags like <Building type="House"> or <House>, shouldn't be very difficult to do. -- 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?" From kent37 at tds.net Thu Mar 24 19:55:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 24 19:55:17 2005 Subject: [Tutor] Changing a class into a subclass In-Reply-To: <8a50240d2251124e842a9d327a85917b@yahoo.fr> References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr> Message-ID: <42430D12.1050502@tds.net> Max Noel wrote: > > On Mar 24, 2005, at 18:07, Ismael Garrido wrote: > >> Hello. >> >> I have a program that saves/loads to/from XML. I have a main class >> Building, and a subclass House(Building). When I save the code I >> instruct each object to save itself to XML (using ElementTree), so >> House adds itself to the XML tree. >> My problem is when I load the XML. Before having subclasses what I did >> was to send the XML object (again in ElementTree) to the object and >> let itself load. Now, with subclasses, if I send the House XML to >> Building I get a Building instance, when I need a House instance. > > > You can't make an object transform into an object of a different > class. Amazingly enough, you actually can do this just by rebinding self.__class__! This thread has an example: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/15afbbcd502b5450/fa111e6ea9ee4cc4 You need to identify what class the object will be an instance of > before loading it. Which, if you're using XML tags like <Building > type="House"> or <House>, shouldn't be very difficult to do. This is a better approach than changing __class__ after the fact. Kent From bgailer at alum.rpi.edu Thu Mar 24 20:02:29 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Mar 24 19:59:34 2005 Subject: [Tutor] Changing a class into a subclass In-Reply-To: <8a50240d2251124e842a9d327a85917b@yahoo.fr> References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr> Message-ID: <6.1.2.0.0.20050324105846.03869198@pop.sbcglobal.yahoo.com> At 10:30 AM 3/24/2005, Max Noel wrote: >On Mar 24, 2005, at 18:07, Ismael Garrido wrote: > >>Hello. >> >>I have a program that saves/loads to/from XML. I have a main class >>Building, and a subclass House(Building). When I save the code I instruct >>each object to save itself to XML (using ElementTree), so House adds >>itself to the XML tree. >>My problem is when I load the XML. Before having subclasses what I did >>was to send the XML object (again in ElementTree) to the object and let >>itself load. Now, with subclasses, if I send the House XML to Building I >>get a Building instance, when I need a House instance. > > You can't make an object transform into an object of a different > class Are you referring to a Python object? If so you may assign a class to the object's __class__ attribute. class A:pass class B:pass b = b() print b.__class__ # displays <class __main__.B at 0x011BB9C0> b.__class__ = A print b.__class__ # displays <class __main__.A at 0x011BBA20> [snip] Bob Gailer mailto:bgailer@alum.rpi.edu 510 558 3275 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050324/feec2d7f/attachment.html From alan.gauld at freenet.co.uk Thu Mar 24 22:24:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 22:24:20 2005 Subject: [Tutor] I need some guidance References: <BAY20-F2330731998F8FF9EBF37A0B3400@phx.gbl> Message-ID: <028f01c530b7$df1bd9e0$93c28651@xp> > Alan, I am a bit lost when you wrote: > " > Read a lot and experiment a lot. Thats where Pythons >>> prompt really > helps. You can build quite sophisticated programs very quickly > by the way Windows XP and the Python v2.4). Do you mean writing from the > Command Line windows instead to use the IDLE one? No, I mean any >>> prompt whether in IDLE or the command line. The point is, you can experiment at the >>> prompt before typing the code into a file. Calling a function lots of times with different values for example is a great way to learn how to use it, and much faster than writing a full program, saving it, then running it and then changing it, and repeating. Just type the command in at the >>> prompt and hit Enter. Then hit up arrow or CTRL P to bring the line back, change the values and hit Enter again... Once you've got it just how you want it, type the line into a real program. That's still how I get to grips with any new modules that I haven't used before. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Mar 24 22:31:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 22:31:48 2005 Subject: [Tutor] Tkinter and keyboard output References: <000901c5309c$0e423aa0$c000a8c0@ARCISDESKTOP> Message-ID: <029d01c530b8$df578de0$93c28651@xp> > What if instead of coding <Alt-p>, I coded <Alt-Key> - how would > I implement the function which would allow the code to determine > which 'Key' was pressed after Alt? There is probably a more correct way of doing it but I'd simply write a small test application that printed out the key values, then type in the Alt-Key combinations and write down whatever gets displayed... I'd then check for the values in my real program. But as I said, there is probably a more scientific approach! :-) Alan G. From alan.gauld at freenet.co.uk Thu Mar 24 22:41:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 22:41:52 2005 Subject: [Tutor] Changing a class into a subclass References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr> Message-ID: <02a401c530ba$4fb5c510$93c28651@xp> > > let itself load. Now, with subclasses, if I send the House XML to > > Building I get a Building instance, when I need a House instance. > > You can't make an object transform into an object of a different > class. You need to identify what class the object will be an instance > of before loading it. Which, if you're using XML tags like <Building > type="House"> or <House>, shouldn't be very difficult to do. Absolutely, looks like you answered your own question... :-) But if you want an OOP approach thre are some things to try. First you can create a BuildingFactory class that has a single instance (or indeed no instances because you could use a static method... or get really fancy and create a meta-class!). The factory class then takes the XML string fragment and figures out which subclass of Building to create and returns the required object. You can avoid having to recode the factory class each time by using a dictionary object and each subclass definition adds an entry to the Factory class dictionary - possibly by calling a class method of Building in the __init__() code class Shack(Building): def __init__(self,p1,p2...): Building.__init__(self,...) Building.register(self,'Shack', Shack) ...rest of init... Now the factory code can go name = self.getClassName(xmlString) obj = self.classList[name]() and instantiate a Shack object. But unless you expect to create an awful lot of subclasses, or just want to be purist in approach its probably overkill! Alan G. From alan.gauld at freenet.co.uk Thu Mar 24 23:10:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 24 23:10:33 2005 Subject: [Tutor] Changing a class into a subclass References: <4242F3D3.9000501@adinet.com.uy><8a50240d2251124e842a9d327a85917b@yahoo.fr> <6.1.2.0.0.20050324105846.03869198@pop.sbcglobal.yahoo.com> Message-ID: <02b201c530be$427db020$93c28651@xp> > Are you referring to a Python object? If so you may assign a class to the > object's __class__ attribute. > class A:pass > class B:pass > b = b() > print b.__class__ # displays <class __main__.B at 0x011BB9C0> > b.__class__ = A > print b.__class__ # displays <class __main__.A at 0x011BBA20> Interesting Bob, but presumably that doesn't change the internal state so the OP would need to run an initialise method using the XML? Or no, I suppose if he did this inside the class's init method, as the first step, it would then initialise as usual? I feel a spell at the >>> coming on... The problem is you still need to identify the class itself (not the class name) before you can do this, but I guess you might get that from either the builtins dictionary or the Building module if it has all the Building subclasses in? But it certainly does allow you to 'convert' from one class to another, much like the C++ cast operator. Alan g. Learning something new every day. From kent37 at tds.net Thu Mar 24 23:45:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 24 23:46:09 2005 Subject: [Tutor] Changing a class into a subclass In-Reply-To: <02a401c530ba$4fb5c510$93c28651@xp> References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr> <02a401c530ba$4fb5c510$93c28651@xp> Message-ID: <42434327.8070302@tds.net> Alan Gauld wrote: > But if you want an OOP approach thre are some things to try. > First you can create a BuildingFactory class that has a > single instance (or indeed no instances because you could > use a static method... or get really fancy and create a > meta-class!). or make it a static method of Building or get really simple and use a module-level function... The factory class then takes the XML string > fragment and figures out which subclass of Building to > create and returns the required object. You can avoid > having to recode the factory class each time by using a > dictionary object and each subclass definition adds an entry > to the Factory class dictionary - possibly by calling a > class method of Building in the __init__() code > > > class Shack(Building): > def __init__(self,p1,p2...): > Building.__init__(self,...) > Building.register(self,'Shack', Shack) > ...rest of init... I think you want to register Shack before you ever create one. You could do it after Shack is defined: class Shack(Building): def __init__(self,p1,p2...): Building.__init__(self,...) ...rest of init... Building.register('Shack', Shack) or you could probably get tricky and do it in a metaclass...but I'm not that tricky. Kent From jeannot18 at hotmail.com Thu Mar 24 23:52:06 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu Mar 24 23:52:09 2005 Subject: [Tutor] Defining functions Message-ID: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> Hi there, I have written (well almost as I copied some lines from an existing example) this little programme - part of an exercise. #By J Carmona #Programme that compute area for #circle, square, rectangle def area_rect(): length = input("Length: ") width = input ("Width: ") print "The area is: ",length*width def area_circ(): radius = input("What is the radius?: ") print "The area is approximately: ", 3.14159*(radius**2) def area_squ(): side = input ("What is the length of one side?: ") print "The area is: ", side*side def print_options(): print "------------------------------" print "Options:" print "1. print options" print "2. calculate circle area" print "3. calculate square area" print "4. calculate rectangle area" print "5. quit the programme" print "------------------------------" choice = input("Choose an option: ") if choice == 1: print_options() elif choice == 2: area_circ() elif choice == 3: area_squ() elif choice == 4: area_rect() elif choice == 5: print_options() #Call starting menu print_options() If I try to change the 1, 2, 3, 4 or 5 by a letter i.e. a, b, c, d, e the programme stop functionning. I get an error message saying that Traceback (most recent call last): File "C:/Python24/Example/area_cir_squ_regt.py", line 39, in -toplevel- print_options() File "C:/Python24/Example/area_cir_squ_regt.py", line 27, in print_options choice = input("Choose an option: ") File "<string>", line 0, in -toplevel- NameError: name 'c' is not defined What am I missing? Thanks JC From ryan at acceleration.net Fri Mar 25 00:10:40 2005 From: ryan at acceleration.net (Ryan Davis) Date: Fri Mar 25 00:10:44 2005 Subject: [Tutor] Defining functions In-Reply-To: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> Message-ID: <20050324231043.95DA71E4005@bag.python.org> Did you put them in quotes? # If choice == 'c': ... # Thanks, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of John Carmona Sent: Thursday, March 24, 2005 5:52 PM To: tutor@python.org Subject: [Tutor] Defining functions Hi there, I have written (well almost as I copied some lines from an existing example) this little programme - part of an exercise. #By J Carmona #Programme that compute area for #circle, square, rectangle def area_rect(): length = input("Length: ") width = input ("Width: ") print "The area is: ",length*width def area_circ(): radius = input("What is the radius?: ") print "The area is approximately: ", 3.14159*(radius**2) def area_squ(): side = input ("What is the length of one side?: ") print "The area is: ", side*side def print_options(): print "------------------------------" print "Options:" print "1. print options" print "2. calculate circle area" print "3. calculate square area" print "4. calculate rectangle area" print "5. quit the programme" print "------------------------------" choice = input("Choose an option: ") if choice == 1: print_options() elif choice == 2: area_circ() elif choice == 3: area_squ() elif choice == 4: area_rect() elif choice == 5: print_options() #Call starting menu print_options() If I try to change the 1, 2, 3, 4 or 5 by a letter i.e. a, b, c, d, e the programme stop functionning. I get an error message saying that Traceback (most recent call last): File "C:/Python24/Example/area_cir_squ_regt.py", line 39, in -toplevel- print_options() File "C:/Python24/Example/area_cir_squ_regt.py", line 27, in print_options choice = input("Choose an option: ") File "<string>", line 0, in -toplevel- NameError: name 'c' is not defined What am I missing? Thanks JC _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From misha.dunn at gmail.com Fri Mar 25 00:24:57 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Fri Mar 25 00:24:59 2005 Subject: [Tutor] Defining functions In-Reply-To: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> Message-ID: <e95c92e005032415244109db7f@mail.gmail.com> Hi John, when you want user input, you almost always need raw_input(), not input(). Michael From kent37 at tds.net Fri Mar 25 00:43:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 25 00:43:30 2005 Subject: [Tutor] Defining functions In-Reply-To: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> Message-ID: <42435086.6050705@tds.net> John Carmona wrote: > Hi there, > > I have written (well almost as I copied some lines from an existing > example) this little programme - part of an exercise. > def print_options(): > print "------------------------------" > print "Options:" > print "1. print options" > print "2. calculate circle area" > print "3. calculate square area" > print "4. calculate rectangle area" > print "5. quit the programme" > print "------------------------------" > choice = input("Choose an option: ") > if choice == 1: > print_options() > elif choice == 2: > area_circ() > elif choice == 3: > area_squ() > elif choice == 4: > area_rect() > elif choice == 5: > print_options() > > If I try to change the 1, 2, 3, 4 or 5 by a letter i.e. a, b, c, d, e > the programme stop functionning. I get an error message saying that > > Traceback (most recent call last): > File "C:/Python24/Example/area_cir_squ_regt.py", line 39, in -toplevel- > print_options() > File "C:/Python24/Example/area_cir_squ_regt.py", line 27, in print_options > choice = input("Choose an option: ") > File "<string>", line 0, in -toplevel- > NameError: name 'c' is not defined The input() function evaluates the input as if it is Python code. So you can type 1+2 to input and it will return 3, for example: >>> print input('type a valid expression: ') type a valid expression: 1+2 3 If you type a bare string, Python expects this to be a variable name: >>> print input('type a valid expression: ') type a valid expression: a Traceback (most recent call last): File "<stdin>", line 1, in ? File "<string>", line 0, in ? NameError: name 'a' is not defined This is exactly the same error you would get if you just typed a bare 'a' at the interpreter prompt: >>> a Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'a' is not defined To get a string from input(), you have to type it with quotes: >>> print input('type a valid expression: ') type a valid expression: 'abcd' abcd raw_input() will return the literal string the user typed. If you input is a string, this is what you want: >>> print raw_input('type anything: ') type anything: 1+2 1+2 >>> print raw_input('type anything: ') type anything: abcd abcd In general, raw_input() is safer than input(), which is vulnerable to abuse. Even if you want an integer input, you can use raw_input() and int(): >>> print int(raw_input('type a number: ')) type a number: 35 35 Kent PS you do need to quote the letters in your if / elif also. From project5 at redrival.net Fri Mar 25 02:36:29 2005 From: project5 at redrival.net (Andrei) Date: Fri Mar 25 02:37:50 2005 Subject: [Tutor] Re: xmlrpc server References: <77bfa81a05032319317e967a1c@mail.gmail.com> Message-ID: <eo234c0y241m$.1ni5il5dfjttm$.dlg@40tude.net> Luis N wrote on Thu, 24 Mar 2005 05:31:03 +0200: <snip> > 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. Unless you are aware right now of certain limitations which make one of the solutions a priori unusable for whatever you want to do, I'd say just go with the one which you find easiest to use and try to code in such a way that it's reasonably easy to replace it with something else later. For example 20 MB memory use doesn't sound like much to me on a modern computer, but I'd leave Nevow out of the choice of your XMLRPC server. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From ismaelgf at adinet.com.uy Fri Mar 25 03:43:54 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Fri Mar 25 03:43:58 2005 Subject: [Tutor] Changing a class into a subclass In-Reply-To: <02a401c530ba$4fb5c510$93c28651@xp> References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr> <02a401c530ba$4fb5c510$93c28651@xp> Message-ID: <42437AEA.4020701@adinet.com.uy> Alan Gauld wrote: > >Absolutely, looks like you answered your own question... :-) > >But if you want an OOP approach thre are some things to try. >First you can create a BuildingFactory class that has a >single instance (or indeed no instances because you could >use a static method... or get really fancy and create a >meta-class!). The factory class then takes the XML string >fragment and figures out which subclass of Building to >create and returns the required object. You can avoid >having to recode the factory class each time by using a >dictionary object and each subclass definition adds an entry >to the Factory class dictionary - possibly by calling a >class method of Building in the __init__() code > > My current aproach is something like that. I subclassed Building(Building) :-) and wrote there the "factory" which returns self of the created instance. But that didn't go with all my other classes that have, as a design rule, that they manage the loading and saving from/to XML. That meant that Building was different to the other classes, and instead of doing: a = Ship() a.fromXML(xml) listOfA.append(a) I had to do: a = Building() listOfBuildings.append(a.fromXML(xml)) When I wrote my "factory" I thought about the dictionary approach, but I didn't write it because I hoped I could find something like the __class__ thing. Which, btw, is pure magic :-) But there's something that I couldn't understand. In the following code, my guess would be that "I'm back from the death" would never get printed... but it is... and twice! Why? >>> class A: def pong(self): print self.__class__ print "Ping!" self.times -=1 if self.times >= 0: self.__class__ = B self.pong() >>> class B: def pong(self): print self.__class__ print "Pong!" self.times -=1 self.__class__ = A self.pong() print "I'm back from the death" >>> a = A() >>> a.times = 3 >>> a.pong() __main__.A Ping! __main__.B Pong! __main__.A Ping! __main__.B Pong! __main__.A Ping! I'm back from the death ##Weird! I'm back from the death >>> a.__class__ <class __main__.A at 0x00C1AF00> Thanks, Ismael From kent37 at tds.net Fri Mar 25 04:19:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 25 04:19:46 2005 Subject: [Tutor] Changing a class into a subclass In-Reply-To: <42437AEA.4020701@adinet.com.uy> References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr> <02a401c530ba$4fb5c510$93c28651@xp> <42437AEA.4020701@adinet.com.uy> Message-ID: <4243834D.1020401@tds.net> Ismael Garrido wrote: > But there's something that I couldn't understand. In the following code, > my guess would be that "I'm back from the death" would never get > printed... but it is... and twice! Why? It's printed every time B.pong() is called, just as "Pong" is. You print each one twice - no mystery! Kent > > >>> class A: > def pong(self): > print self.__class__ > print "Ping!" > self.times -=1 > if self.times >= 0: > self.__class__ = B > self.pong() > > >>> class B: > def pong(self): > print self.__class__ > print "Pong!" > self.times -=1 > self.__class__ = A > self.pong() > print "I'm back from the death" > > >>> a = A() > >>> a.times = 3 > >>> a.pong() > __main__.A > Ping! > __main__.B > Pong! > __main__.A > Ping! > __main__.B > Pong! > __main__.A > Ping! > I'm back from the death ##Weird! > I'm back from the death > >>> a.__class__ > <class __main__.A at 0x00C1AF00> > > > Thanks, > Ismael > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From vicki at stanfield.net Fri Mar 25 04:27:37 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Fri Mar 25 04:29:17 2005 Subject: [Tutor] Trying to use MySQLdb.cursor Message-ID: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> I finally gave up and used MySQLdb to connect to my database. It connects okay, and returns data, but now I have a new question. I use the code below to print the data returned from my query, but I would like to make labels at the top of the columns. How do I do this dynamically? I would like to get the fieldnames as defined by mysql and print them before printing each column. Is there a way to do this? Here is the relevant portion of the code: def getdata(): conn = MySQLdb.Connect( host='localhost', user='user', passwd='password', db='sample',compress=1, cursorclass=MySQLdb.cursors.DictCursor) cursor = conn.cursor() cursor.execute("""SELECT computers.comp_location FROM computers, mice WHERE mice.mouse_type = "USB" AND computers.comp_location like "A%" AND mice.mouse_comp = computers.comp_id;""") rows = cursor.fetchall() cursor.close() conn.close() print ''' <table border="1" cellpadding="5"> ''' for row in rows: print "<tr>" for cell in row: print "<td> %s </td>" % row[cell] print "</tr>" Thanks for helping me get going. Vicki From dyoo at hkn.eecs.berkeley.edu Fri Mar 25 05:14:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 25 05:14:39 2005 Subject: [Tutor] Getting "file sizes" (fwd) Message-ID: <Pine.LNX.4.44.0503242014320.15331-100000@hkn.eecs.berkeley.edu> ---------- Forwarded message ---------- Date: Wed, 18 Feb 2004 16:44:49 -0800 From: Joshua Banks <syn_ack@comcast.net> To: slyskawa@gmail.com Cc: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] Getting "file sizes" On Wednesday 18 February 2004 01:22 pm, you wrote: > Ah, a Gentoo fan. *grin* Yes, I luv Gentoo... :P > Ah, you know about os.path.getsize() already then. getsize() is > actually more versatile than you might think: have you tried applying > it on an individual file path? Yes, I can get the file size of an individual file by specifying the complete path. But if I have a directory with 60 files then I would have to manually put the path in for each file in that directory that I wish to know the size of. Example: The following gives me a list of the files in the directory specified below. There's a total of 12 files listed for examples sake. >>> os.listdir('/var/log/portage') ['1782-openmotif-2.1.30-r3.log', '1781-iptables-1.2.8-r1.log', '1756-slocate-2.7-r5.log', '1763-xloadimage-4.1- r1.log', '1773-iproute-20010824-r4.log', '1757-gentoo-sources-2.4.22-r5.log', '1788-tcl-8.3.4.log', '1797-libpe rl-5.8.0.log', '1769-python-2.3.3.log', '1776-xfree-drm-4.3.0-r6.log', '1806-ymessenger-1.0.4.1.log', '1766-win e-20031118-r1.log'] I also understand that I can do the following 12 times, specifying a different file each time and get the "file size answers that I'm looking for. So I understand how to do this the HardWay. >>> os.path.getsize('/var/log/portage/1782-openmotif-2.1.30-r3.log') 39L What I don't understand is how to get Python to use the "getsize()" function for each file that the "os.listdir('/var/log/portage')" function lists. I've read and read and read. I don't understand, what seems, would be a simple task. Having to manually input each file, one at a time seems backwards to the progamming moto. Do more with less so to say. I'm I not making any sense? Any idea's on how I can get this to work? Thanks, Joshua Banks _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Fri Mar 25 05:28:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 25 05:28:46 2005 Subject: [Tutor] Trying to use MySQLdb.cursor In-Reply-To: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> Message-ID: <Pine.LNX.4.44.0503242022270.15331-100000@hkn.eecs.berkeley.edu> On Fri, 25 Mar 2005, Vicki Stanfield wrote: > I finally gave up and used MySQLdb to connect to my database. It > connects okay, and returns data, but now I have a new question. I use > the code below to print the data returned from my query, but I would > like to make labels at the top of the columns. How do I do this > dynamically? Hi Vicki, Yes, there's a special cursor type that, instead of returning rows of tuples, returns rows of dictionaries. Here's an example: ###### >>> import MySQLdb >>> import MySQLdb.cursors >>> conn = MySQLdb.connect(db='test_adb', ... cursorclass=MySQLdb.cursors.DictCursor) >>> >>> cursor = conn.cursor() >>> cursor.execute("select * from Locus limit 10") 10L >>> cursor.fetchone() {'orientation_is_5': 1, 'last_updated': <DateTime object for '2005-03-24 13:48:06.00' at 402faad8>, 'is_deleted': 0, 'name': 'At1g08520', 'representative_model': None, 'is_pseudogene': 0, 'last_updated_by': 1L, 'assigned_to': None, 'update_needed': None, 'gene_model_type': 0L, 'id': 1L, 'chromosome': 1L, 'locked_for_pasa': 0} ###### Hmmm.. that's a little messy. Let me clean up the output of that a bit with the pretty printing module 'pprint': ###### >>> import pprint >>> pprint.pprint(cursor.fetchone()) {'assigned_to': None, 'chromosome': 1L, 'gene_model_type': 0L, 'id': 2L, 'is_deleted': 0, 'is_pseudogene': 0, 'last_updated': <DateTime object for '2005-03-24 13:48:02.00' at 403104b8>, 'last_updated_by': 1L, 'locked_for_pasa': 0, 'name': 'At1g08530', 'orientation_is_5': 1, 'representative_model': None, 'update_needed': None} ###### The output's content itself is probably a bit bizarre to you (It's a gene from the Arabidopsis plant database) But I hope the code is clear. *grin* If you have more questions, please feel free to ask! From dyoo at hkn.eecs.berkeley.edu Fri Mar 25 05:32:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 25 05:32:47 2005 Subject: [Tutor] Getting "file sizes" (fwd) [oops, old message!] In-Reply-To: <Pine.LNX.4.44.0503242014320.15331-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0503242029140.15331-100000@hkn.eecs.berkeley.edu> Hi everyone, My apologies about the repeated message; I just got an old message from last year, and didn't look closely enough to see that it was a repeat from last year! The mail queue of some folks is really ancient; I wonder why that bounced to me today. Odd. Anyway, sorry about that! From alan.gauld at freenet.co.uk Fri Mar 25 10:02:03 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Mar 25 10:02:28 2005 Subject: [Tutor] Changing a class into a subclass References: <4242F3D3.9000501@adinet.com.uy> <8a50240d2251124e842a9d327a85917b@yahoo.fr><02a401c530ba$4fb5c510$93c28651@xp> <42434327.8070302@tds.net> Message-ID: <02ee01c53119$509e4420$93c28651@xp> > > single instance (or indeed no instances because you could > > use a static method... or get really fancy and create a > > meta-class!). > > or make it a static method of Building Yes that's actually what I meant, but reading it back it sounds like I meant static Factory method.... Ho hum. > or get really simple and use a module-level function... Yeah., but I did say if he wanted to be OOPish. > > class Shack(Building): > > def __init__(self,p1,p2...): > > Building.__init__(self,...) > > Building.register(self,'Shack', Shack) > > ...rest of init... > > I think you want to register Shack before you ever create one. Yeah, you are right. My way you register it every time you create an instance. A single registration call right after the class definition is probably better. > or you could probably get tricky and do it in a metaclass... I would do in Smalltalk but meta classes in Python are somewhere that I haven't visited yet! :-) Alan G. From alan.gauld at freenet.co.uk Fri Mar 25 10:07:45 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Mar 25 10:07:29 2005 Subject: [Tutor] Defining functions References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> Message-ID: <02f301c5311a$1c7c3520$93c28651@xp> > If I try to change the 1, 2, 3, 4 or 5 by a letter i.e. a, b, c, d, e the > programme stop functionning. I get an error message saying that > > Traceback (most recent call last): > File "C:/Python24/Example/area_cir_squ_regt.py", line 39, in -toplevel- > print_options() > File "C:/Python24/Example/area_cir_squ_regt.py", line 27, in print_options > choice = input("Choose an option: ") > File "<string>", line 0, in -toplevel- > NameError: name 'c' is not defined > > What am I missing? Thanks Some quote signs... You need to use raw_input(). input tries to evaluate what the user types, so if they type c, input looks for a variable called c and tries to return its value. But you don't have a variable called c.... and if you had, things would be even more confusing! Using input is useful occasionally but potentially dangerous because a malicious user could type python code into your program and break it. Use raw_input() instead and convert the result as you need it (using int(), float(), str(), or whatever...). Alan G. From misha.dunn at gmail.com Fri Mar 25 10:21:14 2005 From: misha.dunn at gmail.com (Michael Dunn) Date: Fri Mar 25 10:21:18 2005 Subject: [Tutor] Defining functions In-Reply-To: <42435086.6050705@tds.net> References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> <42435086.6050705@tds.net> Message-ID: <e95c92e005032501219b8163f@mail.gmail.com> Something I've always wondered: if input() is so dangerous, why is it there? What valid uses does it have in the wild? I ask this because this confusion comes up a lot: people expect input() to return a string and it throws them when it doesn't. We all just learn to use raw_input(), and to forget about input(). But if you really needed the current input() function, isn't eval(raw_input()) the same thing? And it leaves you space to check the input string for anything stupid or dangerous before you feed it to eval(). Perplexed, Michael From glingl at aon.at Fri Mar 25 11:01:43 2005 From: glingl at aon.at (Gregor Lingl) Date: Fri Mar 25 11:08:11 2005 Subject: [Tutor] SORRY (wrong adress) - (appearance of old postings) Message-ID: <4243E187.10006@aon.at> Ooops, I put the wrong address into my recent posting, which was intended to go to the edu-sig list. Forget it! Sorry for the inconvenience, Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From glingl at aon.at Fri Mar 25 10:56:40 2005 From: glingl at aon.at (Gregor Lingl) Date: Fri Mar 25 11:23:08 2005 Subject: [Tutor] appearance of old postings Message-ID: <4243E058.6090803@aon.at> Hi, there just appeared a couple of postings from a Jan 2004 thread (on primes) on this list again. (two of them by me) To me it's completely unclear why and how this could happen. Does anybody know ...? Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Website: python4kids.net From kent37 at tds.net Fri Mar 25 12:25:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 25 12:25:57 2005 Subject: [Tutor] Trying to use MySQLdb.cursor In-Reply-To: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> References: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> Message-ID: <4243F540.8090607@tds.net> Vicki Stanfield wrote: > I finally gave up and used MySQLdb to connect to my database. It connects > okay, and returns data, but now I have a new question. I use the code > below to print the data returned from my query, but I would like to make > labels at the top of the columns. How do I do this dynamically? I would > like to get the fieldnames as defined by mysql and print them before > printing each column. Is there a way to do this? > > Here is the relevant portion of the code: > > def getdata(): > conn = MySQLdb.Connect( > host='localhost', user='user', > passwd='password', db='sample',compress=1, > cursorclass=MySQLdb.cursors.DictCursor) > cursor = conn.cursor() > cursor.execute("""SELECT computers.comp_location FROM computers, mice > WHERE mice.mouse_type = "USB" > AND computers.comp_location like "A%" > AND mice.mouse_comp = computers.comp_id;""") In this case you know the name as it is in the query (comp_location). In general you can use cursor.description. From the DB-API docs (http://www.python.org/peps/pep-0249.html): This read-only attribute is a sequence of 7-item sequences. Each of these sequences contains information describing one result column: (name, type_code, display_size, internal_size, precision, scale, null_ok). The first two items (name and type_code) are mandatory, the other five are optional and must be set to None if meaningfull values are not provided. So to output a row with the column names something like this should work: print "<tr>" for col in cursor.description: print '<td>%s</td>' % col[0] print "</tr>" Kent > rows = cursor.fetchall() > cursor.close() > conn.close() > > print ''' > <table border="1" cellpadding="5"> > ''' > > for row in rows: > print "<tr>" > for cell in row: > print "<td> %s </td>" % row[cell] > > print "</tr>" > > Thanks for helping me get going. > Vicki > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Mar 25 12:32:40 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 25 12:32:45 2005 Subject: [Tutor] Defining functions In-Reply-To: <e95c92e005032501219b8163f@mail.gmail.com> References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> <42435086.6050705@tds.net> <e95c92e005032501219b8163f@mail.gmail.com> Message-ID: <4243F6D8.6040709@tds.net> Michael Dunn wrote: > Something I've always wondered: if input() is so dangerous, why is it > there? What valid uses does it have in the wild? It's a mistake planned to be removed in Python 3.0, the "hypothetical future release of Python that can break backwards compatibility with the existing body of Python code." Python tries very hard to maintain backward compatibility so things like input() are not removed. http://www.python.org/peps/pep-3000.html#built-ins Kent From cyresse at gmail.com Fri Mar 25 12:35:32 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Mar 25 12:35:36 2005 Subject: [Tutor] Trying to use MySQLdb.cursor In-Reply-To: <4243F540.8090607@tds.net> References: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> <4243F540.8090607@tds.net> Message-ID: <f2ff2d05032503355117143e@mail.gmail.com> mySQL also has it's own metadata commands - http://dev.mysql.com/doc/mysql/en/getting-information.html Looks like you want to use the DESCRIBE <table> command. On Fri, 25 Mar 2005 06:25:52 -0500, Kent Johnson <kent37@tds.net> wrote: > Vicki Stanfield wrote: > > I finally gave up and used MySQLdb to connect to my database. It connects > > okay, and returns data, but now I have a new question. I use the code > > below to print the data returned from my query, but I would like to make > > labels at the top of the columns. How do I do this dynamically? I would > > like to get the fieldnames as defined by mysql and print them before > > printing each column. Is there a way to do this? > > > > Here is the relevant portion of the code: > > > > def getdata(): > > conn = MySQLdb.Connect( > > host='localhost', user='user', > > passwd='password', db='sample',compress=1, > > cursorclass=MySQLdb.cursors.DictCursor) > > cursor = conn.cursor() > > cursor.execute("""SELECT computers.comp_location FROM computers, mice > > WHERE mice.mouse_type = "USB" > > AND computers.comp_location like "A%" > > AND mice.mouse_comp = computers.comp_id;""") > > In this case you know the name as it is in the query (comp_location). In general you can use > cursor.description. From the DB-API docs (http://www.python.org/peps/pep-0249.html): > > This read-only attribute is a sequence of 7-item > sequences. Each of these sequences contains information > describing one result column: (name, type_code, > display_size, internal_size, precision, scale, > null_ok). The first two items (name and type_code) are > mandatory, the other five are optional and must be set to > None if meaningfull values are not provided. > > So to output a row with the column names something like this should work: > print "<tr>" > for col in cursor.description: > print '<td>%s</td>' % col[0] > print "</tr>" > > Kent > > > rows = cursor.fetchall() > > cursor.close() > > conn.close() > > > > print ''' > > <table border="1" cellpadding="5"> > > ''' > > > > for row in rows: > > print "<tr>" > > for cell in row: > > print "<td> %s </td>" % row[cell] > > > > print "</tr>" > > > > Thanks for helping me get going. > > 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 > -- '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. From nbbalane at gmail.com Fri Mar 25 15:50:38 2005 From: nbbalane at gmail.com (jrlen balane) Date: Fri Mar 25 15:50:40 2005 Subject: [Tutor] max. range of list Message-ID: <2cad209005032506501e10bffa@mail.gmail.com> how many is the maximum member can a list have??? From maxnoel_fr at yahoo.fr Fri Mar 25 15:59:15 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Mar 25 15:59:20 2005 Subject: [Tutor] max. range of list In-Reply-To: <2cad209005032506501e10bffa@mail.gmail.com> References: <2cad209005032506501e10bffa@mail.gmail.com> Message-ID: <d2ca1a31cecad86cec207f648f08f810@yahoo.fr> On Mar 25, 2005, at 15:50, jrlen balane wrote: > how many is the maximum member can a list have??? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor As far as I know, there is no limit hard-coded in the language. So I guess the maximum number of elements in a list is either (2^63 - 1) or the available space in your computer's memory (RAM + swapfile), whichever is the smallest. In other words, enough that you don't have to worry about it. -- 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?" From kent37 at tds.net Fri Mar 25 16:26:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 25 16:26:04 2005 Subject: [Tutor] max. range of list In-Reply-To: <2cad209005032506501e10bffa@mail.gmail.com> References: <2cad209005032506501e10bffa@mail.gmail.com> Message-ID: <42442D88.7090007@tds.net> jrlen balane wrote: > how many is the maximum member can a list have??? According to this thread http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ddae82bb2c1b871/e00b7903bc887a73 the number of element in a list is stored in an int, so most likely the hard limit is 2**31-1. The practical limit is the available memory. Kent From keridee at jayco.net Fri Mar 25 17:02:43 2005 From: keridee at jayco.net (Jacob S.) Date: Fri Mar 25 17:02:02 2005 Subject: [Tutor] Defining functions References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> <42435086.6050705@tds.net><e95c92e005032501219b8163f@mail.gmail.com> <4243F6D8.6040709@tds.net> Message-ID: <001b01c53154$1c054b10$575428cf@JSLAPTOP> Yeah. And they're thinking of removing raw_input() too. I think it's good to have a __builtin__ user input function. Why should we have to import sys everytime we want user input? Almost every program that newbies write uses it, and advanced programmers also if they're using console programs. IMHO, I see no reason to remove it. ## end rant Jacob > Michael Dunn wrote: >> Something I've always wondered: if input() is so dangerous, why is it >> there? What valid uses does it have in the wild? > > It's a mistake planned to be removed in Python 3.0, the "hypothetical > future release of Python that can break backwards compatibility with the > existing body of Python code." > > Python tries very hard to maintain backward compatibility so things like > input() are not removed. > > http://www.python.org/peps/pep-3000.html#built-ins > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From nbbalane at gmail.com Fri Mar 25 17:33:20 2005 From: nbbalane at gmail.com (jrlen balane) Date: Fri Mar 25 17:33:24 2005 Subject: [Tutor] max. range of list In-Reply-To: <42442D88.7090007@tds.net> References: <2cad209005032506501e10bffa@mail.gmail.com> <42442D88.7090007@tds.net> Message-ID: <2cad2090050325083365bd34b0@mail.gmail.com> thanks for the information... On Fri, 25 Mar 2005 10:26:00 -0500, Kent Johnson <kent37@tds.net> wrote: > jrlen balane wrote: > > how many is the maximum member can a list have??? > > According to this thread > http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ddae82bb2c1b871/e00b7903bc887a73 > the number of element in a list is stored in an int, so most likely the hard limit is 2**31-1. The > practical limit is the available memory. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From srini_iyyer_bio at yahoo.com Fri Mar 25 18:15:10 2005 From: srini_iyyer_bio at yahoo.com (Srinivas Iyyer) Date: Fri Mar 25 18:15:14 2005 Subject: [Tutor] Unique elements mapping In-Reply-To: 6667 Message-ID: <20050325171510.95287.qmail@web53503.mail.yahoo.com> Hi all: I have a question and I request groups help please. My list has two columns: Name State Drew Virginia Noel Maryland Niki Virginia Adams Maryland Jose Florida Monica Virginia Andrews Maryland I would like to have my ouput like this: Virginia : Drew,Niki,Monica Maryland: Noel,Adams, Andrews Florida: Jose Can you help how should I code : for line in my_list: key = line.split('\t')[0] val = line.split('\t')[1] dict = dict(zip(key,val)) this was my strategy ... but I could not make it work.. Please help srini __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From gsf at panix.com Fri Mar 25 19:28:06 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri Mar 25 19:28:08 2005 Subject: [Tutor] Defining functions In-Reply-To: <001b01c53154$1c054b10$575428cf@JSLAPTOP> References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl> <4243F6D8.6040709@tds.net> <001b01c53154$1c054b10$575428cf@JSLAPTOP> Message-ID: <20050325182806.GC2263@panix.com> So, as a newbie, I see this thread and I check out the PEP and I see that for future compatibility we should use sys.stdin.readline(). So I import sys to see how it works. Of course, sys.stdin.readline('type anything: ') doesn't work in quite the same way as raw_input('type anything: ') does. The closest I can get after a few newbie stabs is: >>>print 'type anything: ', sys.stdin.readline() type anything: hello hello >>> What is the easiest way to get the exact functionality of raw_input() (i.e. a prompt, no whitespace at the front, and no trailing \n) using sys.stdin.readline()? gabe On Fri, Mar 25, 2005 at 11:02:43AM -0500, Jacob S. wrote: > Yeah. And they're thinking of removing raw_input() too. I think it's good > to have a __builtin__ user input function. Why should we have to import > sys everytime we want user input? Almost every program that newbies write > uses it, and advanced programmers also if they're using console programs. > IMHO, I see no reason to remove it. > ## end rant > > Jacob > > > >Michael Dunn wrote: > >>Something I've always wondered: if input() is so dangerous, why is it > >>there? What valid uses does it have in the wild? > > > >It's a mistake planned to be removed in Python 3.0, the "hypothetical > >future release of Python that can break backwards compatibility with the > >existing body of Python code." > > > >Python tries very hard to maintain backward compatibility so things like > >input() are not removed. > > > >http://www.python.org/peps/pep-3000.html#built-ins > > > >Kent > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From shaleh at speakeasy.net Fri Mar 25 19:42:06 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Mar 25 19:44:01 2005 Subject: [Tutor] Unique elements mapping In-Reply-To: <20050325171510.95287.qmail@web53503.mail.yahoo.com> References: <20050325171510.95287.qmail@web53503.mail.yahoo.com> Message-ID: <42445B7E.3060503@speakeasy.net> Srinivas Iyyer wrote: > Hi all: > > I have a question and I request groups help please. > > My list has two columns: > > Name State > Drew Virginia > Noel Maryland > Niki Virginia > Adams Maryland > Jose Florida > Monica Virginia > Andrews Maryland > > > I would like to have my ouput like this: > > Virginia : Drew,Niki,Monica > Maryland: Noel,Adams, Andrews > Florida: Jose > > > Can you help how should I code : > > > for line in my_list: > key = line.split('\t')[0] > val = line.split('\t')[1] > > > dict = dict(zip(key,val)) > > this was my strategy ... but I could not make it > work.. You have the right idea. Just bad implementation (-: uniques = {} # never name them 'dict', that is a type name in python for line in my_list: key, val = line.split('\t') uniques.setdefault(val, []).append(key) # in Python 2.4 the following two lines can be shortened to # sorted_keys = sorted(unique.keys()) sorted_keys = unique.keys() sorted_keys.sort() for item in sort_keys: print "%s: %s" % (item, ",".join(unique[item])) So what we are doing is making a dict for which each element is a list of names. The setdefault trick above is a neater way of saying: if not uniques.has_key(val): uniques[val] = [] uniques[val].append(key) From nbbalane at gmail.com Fri Mar 25 20:02:34 2005 From: nbbalane at gmail.com (jrlen balane) Date: Fri Mar 25 20:02:38 2005 Subject: [Tutor] a shorter way to write this Message-ID: <2cad2090050325110251ae5b1e@mail.gmail.com> basically, i'm going to create a list with 96 members but with only one value: list1[1,1,1,1...,1] is there a shorter way to write this one??? From peterm at ccs.neu.edu Fri Mar 25 20:09:07 2005 From: peterm at ccs.neu.edu (Peter Markowsky) Date: Fri Mar 25 20:09:15 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <2cad2090050325110251ae5b1e@mail.gmail.com> References: <2cad2090050325110251ae5b1e@mail.gmail.com> Message-ID: <73a1a1192abe134819d68128c6f2aa64@ccs.neu.edu> Hi, On Mar 25, 2005, at 2:02 PM, jrlen balane wrote: > basically, i'm going to create a list with 96 members but with only > one value: > > list1[1,1,1,1...,1] > You might want to use a list comprehension like: [1 for i in range(96)] -Pete From gsf at panix.com Fri Mar 25 20:10:41 2005 From: gsf at panix.com (Gabriel Farrell) Date: Fri Mar 25 20:10:44 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <2cad2090050325110251ae5b1e@mail.gmail.com> References: <2cad2090050325110251ae5b1e@mail.gmail.com> Message-ID: <20050325191041.GA14215@panix.com> how about manyones = [ 1 for x in range(96) ] On Sat, Mar 26, 2005 at 03:02:34AM +0800, jrlen balane wrote: > basically, i'm going to create a list with 96 members but with only one value: > > list1[1,1,1,1...,1] > > is there a shorter way to write this one??? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From ryan at acceleration.net Fri Mar 25 20:12:27 2005 From: ryan at acceleration.net (Ryan Davis) Date: Fri Mar 25 20:12:31 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <2cad2090050325110251ae5b1e@mail.gmail.com> Message-ID: <20050325191230.14FD11E4005@bag.python.org> A comprehension and range? # >>> list1 = [1 for x in range(0,96)] >>> len(list1) 96 # Thanks, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of jrlen balane Sent: Friday, March 25, 2005 2:03 PM To: Tutor Tutor Subject: [Tutor] a shorter way to write this basically, i'm going to create a list with 96 members but with only one value: list1[1,1,1,1...,1] is there a shorter way to write this one??? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From nbbalane at gmail.com Fri Mar 25 20:12:52 2005 From: nbbalane at gmail.com (jrlen balane) Date: Fri Mar 25 20:12:55 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <20050325191041.GA14215@panix.com> References: <2cad2090050325110251ae5b1e@mail.gmail.com> <20050325191041.GA14215@panix.com> Message-ID: <2cad2090050325111264e289d2@mail.gmail.com> ahhhh, so thats the way to do it, a list comprehension, thanks for the info... On Fri, 25 Mar 2005 14:10:41 -0500, Gabriel Farrell <gsf@panix.com> wrote: > how about > > manyones = [ 1 for x in range(96) ] > > > On Sat, Mar 26, 2005 at 03:02:34AM +0800, jrlen balane wrote: > > basically, i'm going to create a list with 96 members but with only one value: > > > > list1[1,1,1,1...,1] > > > > is there a shorter way to write this one??? > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Mar 25 20:17:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Mar 25 20:17:26 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <2cad2090050325110251ae5b1e@mail.gmail.com> References: <2cad2090050325110251ae5b1e@mail.gmail.com> Message-ID: <424463C1.8000108@tds.net> jrlen balane wrote: > basically, i'm going to create a list with 96 members but with only one value: > > list1[1,1,1,1...,1] > > is there a shorter way to write this one??? [1] * 96 From michael.hall at critterpixstudios.com Fri Mar 25 20:17:31 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 25 20:17:40 2005 Subject: [Tutor] Python and Javascript Message-ID: <6fad24637222996d109030374d8795fb@critterpixstudios.com> I'm curious on whether or not JavaScript and Python can talk to each other. Specifically, can a python function be called from within a JS function? Admittedly this is probably more of a JavaScript than Python question, but I'd love to know if anyone can at least point me in a direction to research this. -MH From shaleh at speakeasy.net Fri Mar 25 20:19:55 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Mar 25 20:22:00 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <2cad2090050325110251ae5b1e@mail.gmail.com> References: <2cad2090050325110251ae5b1e@mail.gmail.com> Message-ID: <4244645B.8060208@speakeasy.net> jrlen balane wrote: > basically, i'm going to create a list with 96 members but with only one value: > > list1[1,1,1,1...,1] > > is there a shorter way to write this one??? def generateN(n): while 1: yield n I'll leave the actual list creation up to you (-: From jsmith at medplus.com Fri Mar 25 20:26:01 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Mar 25 20:26:10 2005 Subject: [Tutor] a shorter way to write this Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C031C3BC1@medexch1.medplus.com> For all the talk of Python only having one way to do something which is why it's so much better than Perl, I've counted about 10 ways to do this :-) Jeff -----Original Message----- From: Sean Perry [mailto:shaleh@speakeasy.net] Sent: Friday, March 25, 2005 2:20 PM To: Tutor Tutor Subject: Re: [Tutor] a shorter way to write this jrlen balane wrote: > basically, i'm going to create a list with 96 members but with only > one value: > > list1[1,1,1,1...,1] > > is there a shorter way to write this one??? def generateN(n): while 1: yield n I'll leave the actual list creation up to you (-: _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Fri Mar 25 20:28:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 25 20:28:13 2005 Subject: [Tutor] Unique elements mapping In-Reply-To: <20050325171510.95287.qmail@web53503.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0503251054030.13200-100000@hkn.eecs.berkeley.edu> On Fri, 25 Mar 2005, Srinivas Iyyer wrote: > Name State > Drew Virginia > Noel Maryland > Niki Virginia > Adams Maryland > Jose Florida > Monica Virginia > Andrews Maryland > > > I would like to have my ouput like this: > > Virginia : Drew,Niki,Monica > Maryland: Noel,Adams, Andrews > Florida: Jose Hi Srinivas, Sean showed you how to fix the bugs in the program; I wanted to highlight one particular bug that you were running into: Let's look at your program again: > for line in my_list: > key = line.split('\t')[0] > val = line.split('\t')[1] This code is trying to extract a key and value out of every line in my_list. This part actually looks ok. One of the bugs, though, is that the code doesn't collect those keys and values up: it's only holding on to one particular key and one particular value at a time. When we say 'key' or 'val', we're only talking about one particular name or state. And this means that we're probably dropping things on the floor. One way we can fix this is to use a container for all the keys and all the values. We can plunk each new key and value into their respective containers: ###### keys = [] vals = [] for line in my_list: key = line.split('\t')[0] val = line.split('\t')[1] keys.append(key) vals.append(val) ###### By the way, we can make this into a function, to make it easier to test out: ###### def getKeysAndValues(my_list): keys = [] vals = [] for line in my_list: key = line.split('\t')[0] val = line.split('\t')[1] keys.append(key) vals.append(val) return keys, vals ###### As a function, this is easier to test since we can feed the function some sample data, and see if it breaks: ### >>> assert (getKeysAndValues(["hello\tworld", "goodbye\tworld"]) == ... (["hello", "goodbye"], ["world", "world"])) >>> ### And since Python doesn't complain here, we're reasonably sure that it's doing the right thing. I want to emphasize that getKeysAndValues() is probably not exactly what you want: Sean's solution with the dictionary's setdefault() stuff in his previous post sounds right. But keeping things in functions is nice because we can later just test specific parts of a program to make sure they're happily working. Please feel free to ask more questions about this; we'll be happy to help. From dyoo at hkn.eecs.berkeley.edu Fri Mar 25 20:32:32 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 25 20:32:35 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C031C3BC1@medexch1.medplus.com> Message-ID: <Pine.LNX.4.44.0503251129070.13200-100000@hkn.eecs.berkeley.edu> > jrlen balane wrote: > > basically, i'm going to create a list with 96 members but with only > > one value: > > > > list1[1,1,1,1...,1] > > > > is there a shorter way to write this one??? Hi Jrlen Balana, I wanted to ask: why do we want to make a list of 96 members, with the same value? This seems awfully hardcoded. *grin* Can you explain why you're doing this? Just curious. From ryan at acceleration.net Fri Mar 25 21:01:52 2005 From: ryan at acceleration.net (Ryan Davis) Date: Fri Mar 25 21:01:56 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <6fad24637222996d109030374d8795fb@critterpixstudios.com> Message-ID: <20050325200154.DF9711E4005@bag.python.org> Depends on your environment. If your js is on a webpage, you can have it make http calls to a python web service. Look for articles on XMLHttpRequest in javascript to see some examples. I don't know how else that could be done, but I imagine there are other ways. Thanks, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Mike Hall Sent: Friday, March 25, 2005 2:18 PM To: tutor@python.org Subject: [Tutor] Python and Javascript I'm curious on whether or not JavaScript and Python can talk to each other. Specifically, can a python function be called from within a JS function? Admittedly this is probably more of a JavaScript than Python question, but I'd love to know if anyone can at least point me in a direction to research this. -MH _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Fri Mar 25 21:11:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Mar 25 21:10:43 2005 Subject: [Tutor] Trying to use MySQLdb.cursor References: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> Message-ID: <031f01c53176$c5db1b20$93c28651@xp> > below to print the data returned from my query, but I would like to make > labels at the top of the columns. How do I do this dynamically? You shouldn't, it makes your code very vulnarable to changes in the database! Its the same principle as using 'select * from...', a bad idea in production code. And if you know which columns you are selecting you by definition know what labels to use. And another reason why its a bsad idea is that databvase columns often have weird abbreviated names that you don't want to expose users to. Alan G. From alan.gauld at freenet.co.uk Fri Mar 25 21:41:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Mar 25 21:42:05 2005 Subject: [Tutor] Python and Javascript References: <6fad24637222996d109030374d8795fb@critterpixstudios.com> Message-ID: <036d01c5317a$f9651690$93c28651@xp> > I'm curious on whether or not JavaScript and Python can talk to each > other. Specifically, can a python function be called from within a JS > function? Admittedly this is probably more of a JavaScript than Python > question, but I'd love to know if anyone can at least point me in a > direction to research this. As ever, it depends. If you are using WSH on Windows and have the Python active scripting installed then yes. Similarly if you use IE as web browser then it can be done in a web page too. If however it's server-side JavaScript the answer is probably no unless you count using web services such as SOAP and XML/RPC. Alan G. From michael.hall at critterpixstudios.com Fri Mar 25 21:46:21 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 25 21:46:31 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <6fad24637222996d109030374d8795fb@critterpixstudios.com> Message-ID: <46e624c67d0cedc89fe9c99742a6102d@critterpixstudios.com> Ryan, I should clarify that what I'd like to do here is unrelated to the web. I'm actually just interested in using a local html page as a simple gui to launch python calls. So a JS event handler, say a button click, would then call a JS function which inside of it would call a Python function while handing it arguments (say a path that the JS queried from a field in the html page.) That kind of thing. It seems like it should be possible, and hopefully easy, but I have no experience in calling Python functions from other languages so I'm just looking for some input on that. Thanks, -MH On Mar 25, 2005, at 12:01 PM, Ryan Davis wrote: > Depends on your environment. > > If your js is on a webpage, you can have it make http calls to a > python web service. Look for articles on XMLHttpRequest in > javascript to see some examples. > > I don't know how else that could be done, but I imagine there are > other ways. > > Thanks, > Ryan > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On > Behalf Of Mike Hall > Sent: Friday, March 25, 2005 2:18 PM > To: tutor@python.org > Subject: [Tutor] Python and Javascript > > I'm curious on whether or not JavaScript and Python can talk to each > other. Specifically, can a python function be called from within a JS > function? Admittedly this is probably more of a JavaScript than Python > question, but I'd love to know if anyone can at least point me in a > direction to research this. > > > -MH > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From ryan at acceleration.net Fri Mar 25 22:00:04 2005 From: ryan at acceleration.net (Ryan Davis) Date: Fri Mar 25 22:00:08 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <46e624c67d0cedc89fe9c99742a6102d@critterpixstudios.com> Message-ID: <20050325210006.2080E1E4005@bag.python.org> Ok, that explains a lot, but I don't know of any easy way to do have javascript talk to python. I can think of some horrible ways to do it, though. 1. Make a python web service running locally, and build up SOAP calls or HTTP posts to it. (same as I suggested earlier) 2. Use XUL and pyXPCOM to make a firefox extension that talks to python. This is probably much more of a pain in the ass than you want to do, but that's the only way I know of to directly call python functions from javascript. 3. Look into web framework Zope, that might have some of this plumbing done already. 4. Check out Sajax, http://www.modernmethod.com/sajax/, a framework to automate javascript calling your server-side functions. It was made for PHP, but looks to have a python version as well. All of those but #2 require you to set up some kind of server. Is there a reason it has to be an HTML page? If not, making a GUI might be an alternative that sidesteps this altogether. Thanks, Ryan -----Original Message----- From: Mike Hall [mailto:michael.hall@critterpixstudios.com] Sent: Friday, March 25, 2005 3:46 PM To: Ryan Davis Cc: tutor@python.org Subject: Re: [Tutor] Python and Javascript Ryan, I should clarify that what I'd like to do here is unrelated to the web. I'm actually just interested in using a local html page as a simple gui to launch python calls. So a JS event handler, say a button click, would then call a JS function which inside of it would call a Python function while handing it arguments (say a path that the JS queried from a field in the html page.) That kind of thing. It seems like it should be possible, and hopefully easy, but I have no experience in calling Python functions from other languages so I'm just looking for some input on that. Thanks, -MH On Mar 25, 2005, at 12:01 PM, Ryan Davis wrote: > Depends on your environment. > > If your js is on a webpage, you can have it make http calls to a > python web service. Look for articles on XMLHttpRequest in > javascript to see some examples. > > I don't know how else that could be done, but I imagine there are > other ways. > > Thanks, > Ryan > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On > Behalf Of Mike Hall > Sent: Friday, March 25, 2005 2:18 PM > To: tutor@python.org > Subject: [Tutor] Python and Javascript > > I'm curious on whether or not JavaScript and Python can talk to each > other. Specifically, can a python function be called from within a JS > function? Admittedly this is probably more of a JavaScript than Python > question, but I'd love to know if anyone can at least point me in a > direction to research this. > > > -MH > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From michael.hall at critterpixstudios.com Fri Mar 25 22:05:22 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 25 22:05:34 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <036d01c5317a$f9651690$93c28651@xp> References: <6fad24637222996d109030374d8795fb@critterpixstudios.com> <036d01c5317a$f9651690$93c28651@xp> Message-ID: <2f5f7a936b8d5fac88bb6ac09b8beb44@critterpixstudios.com> On Mar 25, 2005, at 12:41 PM, Alan Gauld wrote: > If you are using WSH on Windows and have the Python active scripting > installed then yes. Similarly if you use IE as web browser then it > can be done in a web page too. I'm on OSX, and would be doing this through Safari most likely. -MH From michael.hall at critterpixstudios.com Fri Mar 25 22:12:08 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 25 22:12:13 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <46e624c67d0cedc89fe9c99742a6102d@critterpixstudios.com> Message-ID: <7fdd189f1a85d1edc73b0c47aab3d4e7@critterpixstudios.com> On Mar 25, 2005, at 1:00 PM, Ryan Davis wrote: > Ok, that explains a lot, but I don't know of any easy way to do have > javascript talk to python. > > I can think of some horrible ways to do it, though. > > 1. Make a python web service running locally, and build up SOAP calls > or HTTP posts to it. (same as I suggested earlier) > 2. Use XUL and pyXPCOM to make a firefox extension that talks to > python. This is probably much more of a pain in the ass than you > want to do, but that's the only way I know of to directly call python > functions from javascript. > 3. Look into web framework Zope, that might have some of this plumbing > done already. > 4. Check out Sajax, http://www.modernmethod.com/sajax/, a framework to > automate javascript calling your server-side functions. It > was made for PHP, but looks to have a python version as well. > > All of those but #2 require you to set up some kind of server. Is > there a reason it has to be an HTML page? > > If not, making a GUI might be an alternative that sidesteps this > altogether. Yikes, that sounds pretty hairy. Maybe this kind of thing is not as straight forward as anticipated. Why HTML you say? Well I've been intrigued by Dashboard, which will be in the next OSX release. It allows you to create "widgets" which are essentially little html pages that do things. This got me thinking how I'd like to tie a small Python script I wrote into an html front end (ideally becoming a widget). It's looking like this may be trickier than anticipated. In any case, thanks. -MH From kedart at gmail.com Fri Mar 25 22:34:00 2005 From: kedart at gmail.com (kedar thangudu) Date: Fri Mar 25 22:34:03 2005 Subject: [Tutor] readline module Message-ID: <f3c4328a05032513343d3a0f5@mail.gmail.com> hi, I hav been working on python in developing pyshell... I am using python readline module to for the command line.. Can u help me with how to replace or erase the current readline line-buffer.. the readline module just provides a insert_text func which is appending the text to the line-buffer.. but i want to replace the contents of the line-buffer to something else.. how can i do this ? regards, kedar From dyoo at hkn.eecs.berkeley.edu Fri Mar 25 22:40:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Mar 25 22:40:54 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <7fdd189f1a85d1edc73b0c47aab3d4e7@critterpixstudios.com> Message-ID: <Pine.LNX.4.44.0503251325250.14581-100000@hkn.eecs.berkeley.edu> > Yikes, that sounds pretty hairy. Maybe this kind of thing is not as > straight forward as anticipated. Why HTML you say? Well I've been > intrigued by Dashboard, which will be in the next OSX release. It allows > you to create "widgets" which are essentially little html pages that do > things. This got me thinking how I'd like to tie a small Python script I > wrote into an html front end (ideally becoming a widget). It's looking > like this may be trickier than anticipated. In any case, thanks. Hi Mike, Interesting! You probably know about this already, but PyObjC allows you to write Mac OS X Cocoa applications in Python: http://pyobjc.sourceforge.net/ and this is a well tested bridge to make Python classes integrate into Cocoa applications. For example, http://www.pycs.net/bbum/2004/12/10/#200412101 mentions the use of PyObjC to make a Mac OS X screensaver. So it appears to embed very well. According to the documentation from Apple's Dashboard developer site, we can embed Cocoa bundles into Javascript (there's a brief mention of it under "Custom Code Plug-ins": http://developer.apple.com/macosx/tiger/dashboard.html So in theory, we should be able to inject a Pythonified Cocoa bundle into Dashboard, but then again, I've never tried this before. *grin* I haven't dived into doing Mac OS X development yet, but perhaps someone on the PyObjC list might be able to cook up a quick-and-dirty example of this for you. Try asking on their list and see if you get some useful responses: http://lists.sourceforge.net/lists/listinfo/pyobjc-dev Best of wishes to you! From terryusa at comcast.net Fri Mar 25 22:55:51 2005 From: terryusa at comcast.net (Terry Johnson) Date: Fri Mar 25 22:55:56 2005 Subject: [Tutor] How to include Python Script Message-ID: <000801c53185$69e3b7f0$0202a8c0@terryanita> How does one go about including Python scripts in html documents. I have been looking it up on google but can't seem to find a suitable answer!!?? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050325/82e24a42/attachment.html From michael.hall at critterpixstudios.com Fri Mar 25 23:26:57 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Fri Mar 25 23:27:02 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <Pine.LNX.4.44.0503251325250.14581-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503251325250.14581-100000@hkn.eecs.berkeley.edu> Message-ID: <615a64e66e43d1e6362e787dd675aa56@critterpixstudios.com> Danny, great reply. I have looked a bit at pyObjC, and it does indeed look cool. I was however hoping to bypass that route altogether and go for the simplicity (I thought) that came with the html/js route. Perhaps a cocoa bundle is the only way to get what I'm after. Thanks, -MH On Mar 25, 2005, at 1:40 PM, Danny Yoo wrote: > > >> Yikes, that sounds pretty hairy. Maybe this kind of thing is not as >> straight forward as anticipated. Why HTML you say? Well I've been >> intrigued by Dashboard, which will be in the next OSX release. It >> allows >> you to create "widgets" which are essentially little html pages that >> do >> things. This got me thinking how I'd like to tie a small Python >> script I >> wrote into an html front end (ideally becoming a widget). It's looking >> like this may be trickier than anticipated. In any case, thanks. > > Hi Mike, > > Interesting! > > You probably know about this already, but PyObjC allows you to write > Mac > OS X Cocoa applications in Python: > > http://pyobjc.sourceforge.net/ > > and this is a well tested bridge to make Python classes integrate into > Cocoa applications. For example, > > http://www.pycs.net/bbum/2004/12/10/#200412101 > > mentions the use of PyObjC to make a Mac OS X screensaver. So it > appears > to embed very well. > > > According to the documentation from Apple's Dashboard developer site, > we > can embed Cocoa bundles into Javascript (there's a brief mention of it > under "Custom Code Plug-ins": > > http://developer.apple.com/macosx/tiger/dashboard.html > > So in theory, we should be able to inject a Pythonified Cocoa bundle > into > Dashboard, but then again, I've never tried this before. *grin* > > > I haven't dived into doing Mac OS X development yet, but perhaps > someone > on the PyObjC list might be able to cook up a quick-and-dirty example > of > this for you. > > Try asking on their list and see if you get some useful responses: > > http://lists.sourceforge.net/lists/listinfo/pyobjc-dev > > > Best of wishes to you! > > -MH From klappnase at freenet.de Sat Mar 26 01:15:12 2005 From: klappnase at freenet.de (Michael Lange) Date: Sat Mar 26 01:15:20 2005 Subject: [Tutor] Tkinter and keyboard output In-Reply-To: <000901c5309c$0e423aa0$c000a8c0@ARCISDESKTOP> References: <000901c5309c$0e423aa0$c000a8c0@ARCISDESKTOP> Message-ID: <20050326011512.07b57bce.klappnase@freenet.de> On Thu, 24 Mar 2005 18:05:25 -0000 "Igor Riabtchuk" <igor.r@vodafone.net> wrote: > Hi, > > I was playing around with Tkinter bindings and I got a question which is probably not particularly bright. > > If I have the following code, it works because I specifically code a function for <Alt-p> keypress: > > from Tkinter import * > > class CRED(Frame): > def __init__(self): > Frame.__init__(self) > self.txt=Text(self) > self.txt.bind('<Alt-p>', self.conv) > self.txt.pack() > self.pack() > self.txt.focus() > > def conv(self,event): > self.txt.insert(END,'t') > return 'break' > > app=CRED() > app.mainloop() > > What if instead of coding <Alt-p>, I coded <Alt-Key> - how would I implement the function which would allow the code to determine which 'Key' was pressed after Alt? > > Thank you. > Igor Do you mean something like this: >>> from Tkinter import * >>> r=Tk() >>> t=Text(r) >>> t.pack() >>> >>> def test(event): ... print event.keysym ... >>> t.bind('<Alt-Key>', test) '1077686180test' >>> x # Alt-x was pressed ? Michael From alan.gauld at freenet.co.uk Sat Mar 26 01:49:18 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Mar 26 01:48:48 2005 Subject: [Tutor] Python and Javascript References: <6fad24637222996d109030374d8795fb@critterpixstudios.com> <036d01c5317a$f9651690$93c28651@xp> <2f5f7a936b8d5fac88bb6ac09b8beb44@critterpixstudios.com> Message-ID: <037401c5319d$a4ed5190$93c28651@xp> > > If you are using WSH on Windows and have the Python active scripting > > I'm on OSX, and would be doing this through Safari most likely. oca might be capable of doing it but I know very little about oca, maybe some other Mac users can help? But I don't think it can be done inside Safari. Alan G. From alan.gauld at freenet.co.uk Sat Mar 26 01:51:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Mar 26 01:50:57 2005 Subject: [Tutor] Python and Javascript References: <46e624c67d0cedc89fe9c99742a6102d@critterpixstudios.com> Message-ID: <038d01c5319d$eda8db20$93c28651@xp> > Ryan, I should clarify that what I'd like to do here is unrelated to > the web. I'm actually just interested in using a local html page as a > simple gui to launch python calls. So a JS event handler, say a button > click, would then call a JS function which inside of it would call a > Python function while handing it arguments In that case an http call to a Python web service is probably the easiest solution. Have it all running locally. Alan G. From alan.gauld at freenet.co.uk Sat Mar 26 01:53:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Mar 26 01:52:58 2005 Subject: [Tutor] Python and Javascript References: <7fdd189f1a85d1edc73b0c47aab3d4e7@critterpixstudios.com> Message-ID: <039401c5319e$388dad50$93c28651@xp> > intrigued by Dashboard, which will be in the next OSX release. It > allows you to create "widgets" which are essentially little html pages There is an API for Dashboard and I'm pretty sure MacPython will support it - it covers most of the cocoa type stuff. You might be better checking out the Apple developer site for the Dashboard hooks and loooking at MacPythons options. Alan G. From alan.gauld at freenet.co.uk Sat Mar 26 01:56:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Mar 26 01:56:03 2005 Subject: [Tutor] How to include Python Script References: <000801c53185$69e3b7f0$0202a8c0@terryanita> Message-ID: <03a401c5319e$a89c3350$93c28651@xp> > How does one go about including Python scripts in html documents. You can only do it on Windows based IE pages. Even then theres little real advantage. The snag is the person reading your pages has to have both Python installed and active scripting enabled. Very few regular users have that. > I have been looking it up on google but can't seem to find a > suitable answer!!?? There is a sample in Mark Hammonds book on Python for win32. But in general its a bad idea, better to stivck to JavaScript for html scripting if you want any kind of portability. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From vicki at stanfield.net Sat Mar 26 02:57:45 2005 From: vicki at stanfield.net (Vicki Stanfield) Date: Sat Mar 26 02:59:29 2005 Subject: [Tutor] Trying to use MySQLdb.cursor In-Reply-To: <031f01c53176$c5db1b20$93c28651@xp> References: <1438.192.168.11.11.1111721257.squirrel@192.168.11.11> <031f01c53176$c5db1b20$93c28651@xp> Message-ID: <1068.192.168.11.11.1111802265.squirrel@192.168.11.11> >> below to print the data returned from my query, but I would like to > make >> labels at the top of the columns. How do I do this dynamically? > > You shouldn't, it makes your code very vulnarable to changes in the > database! > Its the same principle as using 'select * from...', a bad idea in > production code. And if you know which columns you are selecting you > by definition know what labels to use. > > And another reason why its a bsad idea is that databvase columns often > have weird abbreviated names that you don't want to expose users to. > > Alan G. > I am just trying to write code to demonstrate this capability in Python. If I am actually in a position where I have access to the database schema, I would not do so. I agree with your comments. Vicki From michael.hall at critterpixstudios.com Sat Mar 26 03:43:59 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Sat Mar 26 03:44:06 2005 Subject: [Tutor] Python and Javascript In-Reply-To: <039401c5319e$388dad50$93c28651@xp> References: <7fdd189f1a85d1edc73b0c47aab3d4e7@critterpixstudios.com> <039401c5319e$388dad50$93c28651@xp> Message-ID: <b607fded02ab8cf29fce643eeee9a592@critterpixstudios.com> On Mar 25, 2005, at 4:53 PM, Alan Gauld wrote: >> intrigued by Dashboard, which will be in the next OSX release. It >> allows you to create "widgets" which are essentially little html > pages > > There is an API for Dashboard and I'm pretty sure MacPython will > support it - it covers most of the cocoa type stuff. You might be > better checking out the Apple developer site for the Dashboard > hooks and loooking at MacPythons options. > > Alan G. > > Alan, thanks for pointing me towards a few good approaches to look at. Going through some of the developer information I've come across mention of JS extensions which allow for system calls within a JS function, which should pretty much do what I want. Thanks, -MH From shaleh at speakeasy.net Sat Mar 26 03:50:13 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sat Mar 26 03:52:19 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C031C3BC1@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C031C3BC1@medexch1.medplus.com> Message-ID: <4244CDE5.5020709@speakeasy.net> Smith, Jeff wrote: > For all the talk of Python only having one way to do something which is > why it's so much better than Perl, I've counted about 10 ways to do this > :-) > Knowing you said this at least half in jest, I still feel the need to comment. In any programming language, you have flexibility in how to define an algorithm. Think about how many different ways you can ask "is this string a in that string b?". The Python motto is actually better stated: there is one obvious way and it is often the right one. In the Python 1.5 days, choices were much fewer. With the new versions have come a more rich selection of features. Python's "only one way" is often brought up as a counterpoint to Perls TIMTOWTDI. Remembering which Perl idiom is the right one, for the right situation *AND* matches the rest of the project can be a real nightmare. Not to mention that choosing the wrong one often kills your performance (-: This is a big reason why I stick to Python. We may have choices, but they are often clear and obvious once you know the language. From cyresse at gmail.com Sat Mar 26 12:46:17 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Mar 26 12:46:23 2005 Subject: [Tutor] Dates and databases, and blobs and Python. Message-ID: <f2ff2d050326034676cf2946@mail.gmail.com> Hi, Just a quick query. I want to store dates and work with them in my SQLite database. There's no specific need for any calculations to done on one side or another (i.e. it's a single user database). I googled how to work with dates in SQL, and I got one like this - SELECT * FROM totp WHERE wk BETWEEN '1980/05/20' AND '1980/05/26' as an example of finding a range for a date. I'm not too sure about how SQL works with dates (and times for that matter), so I'm tempted to stick to what I know and just store dates/times as strings in the db, and then use them to create datetime objects when needed. i.e. >>>cx.execute('select date, time from foo where c_id = 10') >>>dat = cx.next() >>>tim = cx.next() >>>print dat, time 2005-12-31, 7:00 >>>splitD = dat.split('-') >>>splitT = time.split(':') >>>intD = [int(i) for item in splitD] >>>intT = [int(i) for item in splitT] >>> theDateTime = datetime.datetime(intD[0], intD[1], intD[2], intT[0], intT[1]) Although working with dates like that doesn't seem that flash either. Alternatively, I was thinking of storing the actual datetime object in the database (this is a blob I believe?), and that's a whole new kettle of fish. So far I've tried this - >>> import datetime >>> theDT = datetime.datetime(2004, 12, 31, 7, 30) >>> print theDT 2004-12-31 07:30:00 >>> import sqlite >>> c = sqlite.connect('foo.db') >>> cx = c.cursor() >>> import pickle >>> j = pickle.dumps(theDT) >>> cx.execute('insert into bob values(%s)', j) >>> cx.execute('select A from bob') >>> q = cx.next() >>> print q ("cdatetime\ndatetime\np0\n(S'\\x07\\xd4\\x0c\\x1f\\x07\\x1e\\x00\\x00\\x00\\x00'\np1\ntp2\nRp3\n.",) >>> w = pickle.loads(q[0]) >>> print w 2004-12-31 07:30:00 So, it works, but I'm not too sure. I tend to have a random approach to using the standard library, as I don't fully understand what all of the modules do. This provokes the following questions - 1. Should I be using StringIO for this instead? 2. Would my retrieved unpickled datetime object still work if datetime hadn't been imported? 3. Is there a better way to work with blobs and Python? And then there's the overall question - What would be the least fiddly & least error prone way of working with dates and times? Python or SQL? Thank you for your time. 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. From kent37 at tds.net Sat Mar 26 12:51:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 26 12:51:33 2005 Subject: [Tutor] re question In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C5B6@lanexc107p.fnmoc.navy.mil> References: <E338ADD616B66043824B9ABF5CA6EF2332C5B6@lanexc107p.fnmoc.navy.mil> Message-ID: <42454CC0.7080103@tds.net> I don't know why this isn't working for you but this worked for me at a DOS console: >>> s='850hPa?' >>> s '850hPa\xf1' >>> import re >>> re.sub('\xf1', '*', s) '850hPa*' >>> import sys >>> sys.stdout.encoding 'cp437' and also in IDLE with a different encoding: >>> s='850hPa?' >>> s '850hPa\xb1' >>> import re >>> re.sub('\xb1', '*', s) '850hPa*' >>> import sys >>> sys.stdout.encoding 'cp1252' So one guess is that the data is in a different encoding than what you expect? When you print the string and get '\xb1', is that in the same program that is doing the regex? Another approach would be to just pull out the numbers and ignore everything else: >>> s='Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts' >>> l=s.split(',') >>> l ['Std Lvl: 850hPa', ' 1503m', ' 16.8C', ' 15.7C', ' 205 @ 11kts'] >>> [ re.search(r'[\d\.]+', i).group() for i in l] ['850', '1503', '16.8', '15.7', '205'] Kent Ertl, John wrote: > All > > I have a string that has a bunch of numbers with the units attached to them. > I want to strip off the units. I am using a regular expression and sub to > do this. This works great for almost all of the cases. > > These are the type of lines: > > SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts > SigWind: 850hPa?, , , , 205 @ 11kts > Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts > > I am using the following cleanstring = re.compile( '(hPa|hPa\xb1|m|C|kts)' > ). And then the cleanstring.sub("",line). I have tried using numerous \ to > escape the \xb1. > > I also tried replacing all non numeric characters that are part of a > number-character string but I could not make that work. The idea was replace > all non-number characters in a "word" that is made up of numbers followed by > numbers. > > I then split the line at the commas so in the current thinking I need the > commas for the split. How do I deal with the hPa?? When I print it out it > looks like it is a hexadecimal escape character (\xb1) but I am note sure > how to deal with this. > > Any ideas? > > Thanks > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jmillr at umich.edu Sat Mar 26 17:23:13 2005 From: jmillr at umich.edu (John Miller) Date: Sat Mar 26 17:23:23 2005 Subject: [Tutor] primes - sieve of odds In-Reply-To: <20050324110110.4FEAF1E401D@bag.python.org> References: <20050324110110.4FEAF1E401D@bag.python.org> Message-ID: <40fe754fe9870e87c4889f5087030399@umich.edu> On Mar 24, 2005, at 6:01 AM, C Smith <smichr@hotmail.com> wrote: >> 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 How does one actually use this module? For example: >>> import eratosthenes >>> eratosthenes.primes() <generator object at 0x640d0> >>> eratosthenes.primes().next() 2 >>> eratosthenes.primes().next() 2 >>> eratosthenes.primes().next() 2 How does one get beyond the first prime? Thanks, John From shaleh at speakeasy.net Sat Mar 26 17:42:15 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sat Mar 26 17:44:13 2005 Subject: [Tutor] Dates and databases, and blobs and Python. In-Reply-To: <f2ff2d050326034676cf2946@mail.gmail.com> References: <f2ff2d050326034676cf2946@mail.gmail.com> Message-ID: <424590E7.7090608@speakeasy.net> Liam Clarke wrote: > > And then there's the overall question - > > What would be the least fiddly & least error prone way of working with > dates and times? Python or SQL? > Liam, SQL is another language. You need to learn it like you are learning Python. It has pretty decent support for dates and times as part of the ANSI SQL spec. There are defined types, SQL functions, etc. week(date) = week(mydate) for instance. I tend to prefer to write programming language agnostic databases because that way I can interact with them from any random language I need to. Sometimes things go bad and a quick little script which does: rows = exec("select * from table") exec("begin transaction") for row in rows: row[3] = row[2] + row[4] - 5 # we decided on a new value exec("update fields in table") can be handy. From shaleh at speakeasy.net Sat Mar 26 17:47:49 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Sat Mar 26 17:49:55 2005 Subject: [Tutor] primes - sieve of odds In-Reply-To: <40fe754fe9870e87c4889f5087030399@umich.edu> References: <20050324110110.4FEAF1E401D@bag.python.org> <40fe754fe9870e87c4889f5087030399@umich.edu> Message-ID: <42459235.1030107@speakeasy.net> John Miller wrote: > How does one actually use this module? For example: > > >>> import eratosthenes > >>> eratosthenes.primes() > <generator object at 0x640d0> > >>> eratosthenes.primes().next() > 2 > >>> eratosthenes.primes().next() > 2 > >>> eratosthenes.primes().next() > 2 > > How does one get beyond the first prime? > it = eratosthenes.primes() it.next() it.next() or # 'it' is shorthand for iterator def primesToN(n): it = eratosthenes.primes() return [ x for x in it if x <= n ] You were running into problems because the primes() function returns a new generator. The values are in the generator not the function primes(). From davholla2002 at yahoo.co.uk Sat Mar 26 19:12:52 2005 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Mar 26 19:12:54 2005 Subject: [Tutor] Using python to write games Message-ID: <20050326181252.53878.qmail@web25404.mail.ukl.yahoo.com> Is there any material anyone knows about how to use pure python without pygame to write games ? The reason for asking, is that although pygame is good it has the disadvantage of that your users must have pygame. It is also harder to create a stand alone .exe with python ? Send instant messages to your online friends http://uk.messenger.yahoo.com From kent37 at tds.net Sat Mar 26 21:15:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Mar 26 21:15:27 2005 Subject: [Tutor] Using python to write games In-Reply-To: <20050326181252.53878.qmail@web25404.mail.ukl.yahoo.com> References: <20050326181252.53878.qmail@web25404.mail.ukl.yahoo.com> Message-ID: <4245C2D9.3060004@tds.net> David Holland wrote: > Is there any material anyone knows about how to use > pure python without pygame to write games ? The > reason for asking, is that although pygame is good it > has the disadvantage of that your users must have > pygame. It is also harder to create a stand alone > .exe with python ? What kind of games, for what platform? Obviously you could write a text-based game without PyGame. You can do simple animations in Tkinter - see http://effbot.org/zone/tkinter-animation.htm and http://www.astro.washington.edu/owen/TkinterSummary.html#After. You can play sounds with WinSound. My guess is that for a complex game you will want things that pygame supplies like double-buffered drawing and an event system. Just a guess though, I haven't done this myself. Kent From jfouhy at paradise.net.nz Sat Mar 26 22:06:39 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Sat Mar 26 22:06:43 2005 Subject: [Tutor] Using python to write games In-Reply-To: <20050326181252.53878.qmail@web25404.mail.ukl.yahoo.com> References: <20050326181252.53878.qmail@web25404.mail.ukl.yahoo.com> Message-ID: <4245CEDF.1090509@paradise.net.nz> David Holland wrote: > Is there any material anyone knows about how to use > pure python without pygame to write games ? The > reason for asking, is that although pygame is good it > has the disadvantage of that your users must have > pygame. It is also harder to create a stand alone > .exe with python ? Why not distribute pygame with your game? (I assume that would be allowed) I mean, you could write your own game library, but then you'd just have to distribute that instead... Also, in terms of creating standalone executables, have a look at py2exe. -- John. From jfouhy at paradise.net.nz Sat Mar 26 22:09:36 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Sat Mar 26 22:09:38 2005 Subject: [Tutor] a shorter way to write this In-Reply-To: <424463C1.8000108@tds.net> References: <2cad2090050325110251ae5b1e@mail.gmail.com> <424463C1.8000108@tds.net> Message-ID: <4245CF90.50806@paradise.net.nz> Kent Johnson wrote: > jrlen balane wrote: >> basically, i'm going to create a list with 96 members but with only >> one value: >> is there a shorter way to write this one??? > [1] * 96 Just a note on this --- This will work fine for immutable types (such as integers or strings). But you can get into trouble if you do this with mutable types. eg: >>> l = [[]] * 10 # A list of ten empty lists >>> l [[], [], [], [], [], [], [], [], [], []] >>> l[3].append(2) >>> l [[2], [2], [2], [2], [2], [2], [2], [2], [2], [2]] -- John. From missive at hotmail.com Sun Mar 27 00:57:08 2005 From: missive at hotmail.com (Lee Harr) Date: Sun Mar 27 00:57:13 2005 Subject: [Tutor] Re: Dates and databases, and blobs and Python. Message-ID: <BAY2-F24157AEF6691EFD620607FB1420@phx.gbl> >Just a quick query. I want to store dates and work with them in my >SQLite database. >There's no specific need for any calculations to done on one side or >another (i.e. it's a single user database). > >I googled how to work with dates in SQL, and I got one like this - > >SELECT * FROM totp >WHERE wk BETWEEN '1980/05/20' > AND '1980/05/26' > >as an example of finding a range for a date. I'm not too sure about >how SQL works with dates (and times for that matter), so I'm tempted >to stick to what I know and just store dates/times as strings in the >db, and then use them to create datetime objects when needed. > I have not worked much with sqlite, but from this page: http://www.sqlite.org/datatype3.html it appears that sqlite does not have a date datatype. >>>>theDateTime = datetime.datetime(intD[0], intD[1], intD[2], intT[0], >>>>intT[1]) > >Although working with dates like that doesn't seem that flash either. Well... create a wrapper function to clean it up, right? >Alternatively, I was thinking of storing the actual datetime object in >the database (this is a blob I believe?), and that's a whole new >kettle of fish. > I have heard a lot of really good things about SQLObject: http://sqlobject.org/ However, that requires a more full-featured database, like postgresql. _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kent37 at tds.net Sun Mar 27 01:43:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 27 01:43:31 2005 Subject: [Tutor] Re: Dates and databases, and blobs and Python. In-Reply-To: <BAY2-F24157AEF6691EFD620607FB1420@phx.gbl> References: <BAY2-F24157AEF6691EFD620607FB1420@phx.gbl> Message-ID: <424601AD.4000905@tds.net> Lee Harr wrote: > I have heard a lot of really good things about SQLObject: > http://sqlobject.org/ > > However, that requires a more full-featured database, like postgresql. According to the docs SQLObject supports SQLite: http://sqlobject.org/docs/SQLObject.html#requirements Kent From garnaez at gmail.com Sun Mar 27 01:44:22 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Sun Mar 27 01:44:25 2005 Subject: [Tutor] Why cant I return more than once here? Message-ID: <148eea710503261644258f3014@mail.gmail.com> Hi all, I am working a simple function and want it return a a float a list and a dictionary But it seems that I can only use return once in the function cant see to figure out why I can return more than once? Thanks for the help! ---------------------------------------------------------- #!/usr/bin/env python def AddItUp(): # #Note I had to force the raw_input to become integers or else reduce doesnt work # Monday = raw_input("Monday: ") # Tuesday = raw_input("Tuesday: ") # Wednesday = raw_input("Wednesday: ") # Thursday = raw_input("Thursday: ") # Friday = raw_input("Friday: ") # Saturday = raw_input("Saturday: ") # Sunday = raw_input("Sunday: ") InitalCoumadinWeekRegimen = {"Monday":float(Monday), "Tuesday":float(Tuesday), "Wednesday":float(Wednesday), "Thursday":float(Thursday), "Friday":float(Friday), "Saturday":float(Saturday), "Sunday":float(Sunday) } CoumadinValuesList = InitalCoumadinWeekRegimen.values() return InitalCoumadinWeekRegimen return reduce ((lambda x,y: x+y), CoumadinValuesList), CoumadinValuesList From kent37 at tds.net Sun Mar 27 03:09:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 27 03:09:37 2005 Subject: [Tutor] Why cant I return more than once here? In-Reply-To: <148eea710503261644258f3014@mail.gmail.com> References: <148eea710503261644258f3014@mail.gmail.com> Message-ID: <424607CC.9060705@tds.net> gerardo arnaez wrote: > Hi all, I am working a simple function > and want it return a > a float > a list > and a dictionary > > But it seems that I can only use > return once in the function > cant see to figure out why I can return more than once? > Thanks for the help! 'return' does two things - it specifies what values to return, and it exits the function. You can return as many values as you want but it has to be all from one return statement. > return InitalCoumadinWeekRegimen > return reduce ((lambda x,y: x+y), CoumadinValuesList), CoumadinValuesList Just put all the values in one return: return InitalCoumadinWeekRegimen, reduce ((lambda x,y: x+y), CoumadinValuesList), CoumadinValuesList BTW reduce ((lambda x,y: x+y), CoumadinValuesList) is the same as sum(CoumadinValuesList) Kent From cyresse at gmail.com Sun Mar 27 03:53:16 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Mar 27 03:53:22 2005 Subject: [Tutor] Dates and databases, and blobs and Python. In-Reply-To: <4245BD27.9020001@tds.net> References: <f2ff2d050326034676cf2946@mail.gmail.com> <4245BD27.9020001@tds.net> Message-ID: <f2ff2d05032617531028a821@mail.gmail.com> Hi Kent, > Most databases have a DATE type and you can directly store and retrieve date objects. Looking at the > pysqlite code I see it uses mxDateTime for date support - it doesn't use the Python datetime module. > > So the first step is to install mxDateTime from > http://www.egenix.com/files/python/mxDateTime.html > > OK, now let's create a table with a DATE column: > >>> import sqlite > >>> con = sqlite.connect('mydatabase.db') > >>> cur = con.cursor() > >>> cur.execute('CREATE TABLE foo (aDate DATE)') > > The sqlite Date class is called sqlite.main.Date. (According to the DB-API this should be exposed as > sqlite.Date but whatever...). Let's create a Date: > >>> d=sqlite.main.Date(2005, 3, 26) > >>> d > <DateTime object for '2005-03-26 00:00:00.00' at a31f20> > > insert it into the table: > >>> cur.execute('insert into foo (aDate) values (%s)', d) > > and read it back: > >>> cur.execute('select * from foo') > >>> cur.fetchall() > [(<DateTime object for '2005-03-26 00:00:00.00' at 9bf660>,)] > > Note how the data returned from fetchall() contains a Date object. > > BTW there doesn't seem to be much available in the way of pysqlite docs. You should probably become > familiar with the DB-API spec (http://www.python.org/peps/pep-0249.html) and the pysqlite source... Thanks for that, I've installed mxDateTime, and just playing around at the >>> with it, I can see that it's very useful, and being able to pass it as a parameter is just what I needed. And yeah, I'm familiar with the (lack of) documentation for pysqlite. Apparently a whole new version is in the works, based around the latest SQLite release, and it's a one man show as far as I can tell, so perhaps I should get my skills up to speed and write the docs. : ) 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. From missive at hotmail.com Sun Mar 27 04:02:27 2005 From: missive at hotmail.com (Lee Harr) Date: Sun Mar 27 04:02:31 2005 Subject: [Tutor] Re: Dates and databases, and blobs and Python. Message-ID: <BAY2-F336D527A829EDDA22E4627B1430@phx.gbl> >>I have heard a lot of really good things about SQLObject: >>http://sqlobject.org/ >> >>However, that requires a more full-featured database, like postgresql. > >According to the docs SQLObject supports SQLite: >http://sqlobject.org/docs/SQLObject.html#requirements > Wups. I even looked at that page before posting.... SQLObject is even better than I thought! _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar - get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From keridee at jayco.net Sun Mar 27 05:54:17 2005 From: keridee at jayco.net (Jacob S.) Date: Sun Mar 27 05:54:48 2005 Subject: [Tutor] Defining functions References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl><4243F6D8.6040709@tds.net><001b01c53154$1c054b10$575428cf@JSLAPTOP> <20050325182806.GC2263@panix.com> Message-ID: <001d01c53280$d7b8eab0$d75428cf@JSLAPTOP> Try this. import sys def my_raw_input(prompt): sys.stdout.write(prompt) ## Since they're thinking of bonking off print as well. a = sys.stdin.readline() if a.startswith(prompt): return a[:len(prompt)] return a It leaves the '\n' on the end... so it sucks. I know there is a better way... Someone else-help? Jacob > So, as a newbie, I see this thread and I check out the PEP and I see > that for future compatibility we should use sys.stdin.readline(). So > I import sys to see how it works. Of course, sys.stdin.readline('type > anything: ') doesn't work in quite the same way as raw_input('type > anything: ') does. The closest I can get after a few newbie stabs is: > >>>>print 'type anything: ', sys.stdin.readline() > type anything: hello > hello > >>>> > > What is the easiest way to get the exact functionality of raw_input() > (i.e. a prompt, no whitespace at the front, and no trailing \n) using > sys.stdin.readline()? > > gabe > > > On Fri, Mar 25, 2005 at 11:02:43AM -0500, Jacob S. wrote: >> Yeah. And they're thinking of removing raw_input() too. I think it's >> good >> to have a __builtin__ user input function. Why should we have to import >> sys everytime we want user input? Almost every program that newbies write >> uses it, and advanced programmers also if they're using console programs. >> IMHO, I see no reason to remove it. >> ## end rant >> >> Jacob >> >> >> >Michael Dunn wrote: >> >>Something I've always wondered: if input() is so dangerous, why is it >> >>there? What valid uses does it have in the wild? >> > >> >It's a mistake planned to be removed in Python 3.0, the "hypothetical >> >future release of Python that can break backwards compatibility with the >> >existing body of Python code." >> > >> >Python tries very hard to maintain backward compatibility so things like >> >input() are not removed. >> > >> >http://www.python.org/peps/pep-3000.html#built-ins >> > >> >Kent >> > >> >_______________________________________________ >> >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 maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From sinan at orun.org Thu Mar 24 19:47:41 2005 From: sinan at orun.org (M.Sinan ORUN) Date: Sun Mar 27 09:11:24 2005 Subject: [Tutor] Running a python script from another python script Message-ID: <42430B4D.9060501@orun.org> Hello, I am a newbee in python and trying to make a small script for my school project . I try to run a python cgi script from another phyton script as a result of an action . What is the neccesary command for this action and is there a special class have to be imported for this command. below i am giving so for what i have writen and what am i trying to do. Thant you for your help this is my first script for a basic log in action. i want to run the second script from this script as a result of login action ##### index.cgi##### login script #!/usr/bin/python import cgi print "Content-Type: text/html\n\n" # Define function to generate HTML form. def generate_form(): print "<HTML>\n" print "<HEAD>\n" print "\t<TITLE>Info Form</TITLE>\n" print "</HEAD>\n" print "<BODY BGCOLOR = white>\n" print "\t<H3>Please, enter your UserName and Password.</H3>\n" print "\t<TABLE BORDER = 0>\n" print "\t\t<FORM METHOD = post ACTION = \"index.cgi\">\n" print "\t\t<TR><TH>UserName:</TH><TD><INPUT type = text name = \"UserName\"></TD><TR>\n" print "\t\t<TR><TH>Password:</TH><TD><INPUT type = password name = \ \"Password\"></TD></TR>\n" print "\t</TABLE>\n" print "\t<INPUT TYPE = hidden NAME = \"action\" VALUE = \"display\">\n" print "\t<INPUT TYPE = submit VALUE = \"Enter\">\n" print "\t</FORM>\n" print "</BODY>\n" print "</HTML>\n" # Define main function. def main(): form = cgi.FieldStorage() if (form.has_key("action") and form.has_key("UserName") and form.has_key("Password")): if (form["UserName"].value == "sinan" and form["Password"].value== "666"): print "Welcome Boss !!" #### here i need a command to move on my second script (index1.cgi)######### else: print " You are not recognized !!" generate_form() else: print " You are not recognized !!" generate_form() main() ########## index1.cgi ############# this is my second script whish has to be runned from the first script #### as a result of login action##### #!/usr/bin/python import cgi print "Content-Type: text/html\n\n" # Define function to generate HTML form. #menulist def menulist(): print "<HTML>\n" print "<HEAD>\n" print "\t<TITLE>Menu List</TITLE>\n" print "</HEAD>\n" print "<BODY BGCOLOR = white>\n" print "\t<H3>Please choice a operation.</H3>\n" print "<FORM METHOD = post ACTION = \"index1.cgi\">\n" print "<select name=\"operations\">" print "<option value=\"People\">People" print "<option value=\"Lessons\">Lessons" print "<option value=\"Projects\">Projects" print "</SELECT>" print "<BR>" print "<INPUT TYPE=\"reset\">" print "<INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Submit\">" print "</FORM>" print "</BODY>\n" print "</HTML>\n" def Menu(): form = cgi.FieldStorage() if (form.has_key("operations")): if (form["operations"].value == "People"): print "people menu" elif (form["operations"].value == "Lessons"): print "lesson menu" elif (form["operations"].value == "Projects"): print "project menu" else: print "error" else: menulist() Menu() From kent37 at tds.net Sun Mar 27 14:07:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 27 14:07:58 2005 Subject: [Tutor] Defining functions In-Reply-To: <001d01c53280$d7b8eab0$d75428cf@JSLAPTOP> References: <BAY20-F30E22CBF1D30F3738DF36FB3400@phx.gbl><4243F6D8.6040709@tds.net><001b01c53154$1c054b10$575428cf@JSLAPTOP> <20050325182806.GC2263@panix.com> <001d01c53280$d7b8eab0$d75428cf@JSLAPTOP> Message-ID: <4246A214.9050107@tds.net> - print is just being changed to a function (instead of a statement), it's not going away entirely. But for complete future compatibility I guess you would avoid it. - I don't think you will ever get the prompt as part of the input unless the user actually types it - You can strip the trailing newline easily So here is my version: import sys def my_raw_input(prompt): sys.stdout.write(prompt) value = sys.stdin.readline()[:-1] return value BTW, this is an interesting exercise but I wouldn't actually code this way. Python 3.0 is a long ways off and Python 2.x isn't going to go away when 3.0 arrives. (You can still download six-year-old Python 1.5.2 from python.org!) Here is a quote from a report of Guido van Rossum's keynote speech last week at PyCon: "Guido started talking about Python 3000 in 2000. He said he always imagined it as a release that was three years off, and it still feels that way." http://pycon.blogspot.com/ I don't need raw_input() much in my code, but I use print without a second thought. Kent Jacob S. wrote: > Try this. > > import sys > > def my_raw_input(prompt): > sys.stdout.write(prompt) ## Since they're thinking of bonking > off print as well. > a = sys.stdin.readline() > if a.startswith(prompt): > return a[:len(prompt)] > return a > > It leaves the '\n' on the end... so it sucks. > > I know there is a better way... Someone else-help? > > Jacob > >> So, as a newbie, I see this thread and I check out the PEP and I see >> that for future compatibility we should use sys.stdin.readline(). So >> I import sys to see how it works. Of course, sys.stdin.readline('type >> anything: ') doesn't work in quite the same way as raw_input('type >> anything: ') does. The closest I can get after a few newbie stabs is: >> >>>>> print 'type anything: ', sys.stdin.readline() >> >> type anything: hello >> hello >> >>>>> >> >> What is the easiest way to get the exact functionality of raw_input() >> (i.e. a prompt, no whitespace at the front, and no trailing \n) using >> sys.stdin.readline()? >> >> gabe >> >> >> On Fri, Mar 25, 2005 at 11:02:43AM -0500, Jacob S. wrote: >> >>> Yeah. And they're thinking of removing raw_input() too. I think it's >>> good >>> to have a __builtin__ user input function. Why should we have to import >>> sys everytime we want user input? Almost every program that newbies >>> write >>> uses it, and advanced programmers also if they're using console >>> programs. >>> IMHO, I see no reason to remove it. >>> ## end rant >>> >>> Jacob >>> >>> >>> >Michael Dunn wrote: >>> >>Something I've always wondered: if input() is so dangerous, why is it >>> >>there? What valid uses does it have in the wild? >>> > >>> >It's a mistake planned to be removed in Python 3.0, the "hypothetical >>> >future release of Python that can break backwards compatibility with >>> the >>> >existing body of Python code." >>> > >>> >Python tries very hard to maintain backward compatibility so things >>> like >>> >input() are not removed. >>> > >>> >http://www.python.org/peps/pep-3000.html#built-ins >>> > >>> >Kent >>> > >>> >_______________________________________________ >>> >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 maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sun Mar 27 14:23:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Mar 27 14:23:50 2005 Subject: [Tutor] Running a python script from another python script In-Reply-To: <42430B4D.9060501@orun.org> References: <42430B4D.9060501@orun.org> Message-ID: <4246A5D1.9010202@tds.net> M.Sinan ORUN wrote: > Hello, > > I am a newbee in python and trying to make a small script for my school > project . I try to run a python cgi script from another phyton script > as a result of an action . What is the neccesary command for this action > and is there a special class have to be imported for this command. One way to do this is to put a redirect in the response to the login page. This will make the browser go to the second page. This page tells how: http://www.instant-web-site-tools.com/html-redirect.html Note that you are not actually password protecting your second page; there is nothing to prevent a user from navigating directly to the second page. For real protection the second page needs to check if the user is logged in using some kind of session mechanism, and redirect to the login page if the user is not authenticated. There are many Python web frameworks that can help with this. BTW you should try using triple-quoted strings for your blocks of HTML, then you can just type literally what you want, no embedded 'print' or '\n' or escaped quotes, e.g. print """\ <HTML> <HEAD> <TITLE>Menu List</TITLE> </HEAD> <BODY BGCOLOR = white> <H3>Please choice a operation.</H3> <FORM METHOD = post ACTION = "index1.cgi"> """ etc. Kent > > below i am giving so for what i have writen and what am i trying to do. > Thant you for your help > > this is my first script for a basic log in action. i want to run the > second script from this script as a result of login action > > > ##### index.cgi##### login script > #!/usr/bin/python > import cgi > print "Content-Type: text/html\n\n" > > # Define function to generate HTML form. > def generate_form(): > print "<HTML>\n" > print "<HEAD>\n" > print "\t<TITLE>Info Form</TITLE>\n" > print "</HEAD>\n" > print "<BODY BGCOLOR = white>\n" > print "\t<H3>Please, enter your UserName and Password.</H3>\n" > print "\t<TABLE BORDER = 0>\n" > print "\t\t<FORM METHOD = post ACTION = \"index.cgi\">\n" > print "\t\t<TR><TH>UserName:</TH><TD><INPUT type = text name = > \"UserName\"></TD><TR>\n" > print "\t\t<TR><TH>Password:</TH><TD><INPUT type = password name = \ > \"Password\"></TD></TR>\n" > print "\t</TABLE>\n" > print "\t<INPUT TYPE = hidden NAME = \"action\" VALUE = \"display\">\n" > print "\t<INPUT TYPE = submit VALUE = \"Enter\">\n" > print "\t</FORM>\n" > print "</BODY>\n" > print "</HTML>\n" > > # Define main function. > def main(): > > form = cgi.FieldStorage() > if (form.has_key("action") and form.has_key("UserName") and > form.has_key("Password")): > if (form["UserName"].value == "sinan" and form["Password"].value== "666"): > print "Welcome Boss !!" > #### here i need a command to move on my second script > (index1.cgi)######### > > else: > print " You are not recognized !!" > generate_form() > else: > print " You are not recognized !!" > generate_form() > main() > > > > > ########## index1.cgi ############# this is my second script whish has > to be runned from the first script > #### as a result of login action##### > #!/usr/bin/python > import cgi > print "Content-Type: text/html\n\n" > > # Define function to generate HTML form. > > #menulist > def menulist(): > print "<HTML>\n" > print "<HEAD>\n" > print "\t<TITLE>Menu List</TITLE>\n" > print "</HEAD>\n" > print "<BODY BGCOLOR = white>\n" > print "\t<H3>Please choice a operation.</H3>\n" > print "<FORM METHOD = post ACTION = \"index1.cgi\">\n" > print "<select name=\"operations\">" > print "<option value=\"People\">People" > print "<option value=\"Lessons\">Lessons" > print "<option value=\"Projects\">Projects" > print "</SELECT>" > print "<BR>" > print "<INPUT TYPE=\"reset\">" > print "<INPUT TYPE=\"submit\" NAME=\"submit\" VALUE=\"Submit\">" > print "</FORM>" > print "</BODY>\n" > print "</HTML>\n" > > def Menu(): > form = cgi.FieldStorage() > if (form.has_key("operations")): > if (form["operations"].value == "People"): > print "people menu" > elif (form["operations"].value == "Lessons"): > print "lesson menu" > elif (form["operations"].value == "Projects"): > print "project menu" > else: > print "error" > else: > menulist() > Menu() > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From singingxduck at gmail.com Sun Mar 27 19:21:34 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Sun Mar 27 19:21:38 2005 Subject: [Tutor] hash()ing a list Message-ID: <3449428f05032709216c60f4dd@mail.gmail.com> Hello all, While I do not have a pressing need to hash a list, I am curious as to why, if lists are unhashable, there is a __hash__() method in the list class, which also does not work on lists, but results in a 'TypeError: list objects are unhashable'. What's the point of including a __hash__() method in the list class if lists are unhashable? Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From keridee at jayco.net Sun Mar 27 22:22:16 2005 From: keridee at jayco.net (Jacob S.) Date: Sun Mar 27 22:21:44 2005 Subject: [Tutor] re question References: <E338ADD616B66043824B9ABF5CA6EF2332C5B6@lanexc107p.fnmoc.navy.mil> <42454CC0.7080103@tds.net> Message-ID: <002e01c5330a$bc3f6d10$115328cf@JSLAPTOP> Kent -- when pulling out just the numbers, why go to the trouble of splitting by "," first? import re pat = re.compile(r"[^\d.]*") t = """SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts SigWind: 850hPa?, , , , 205 @ 11kts Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts""" result = pat.split(t) print result yields ['', '857', '21.0', '20.1', '210', '9', '850', '205', '11', '850', '1503', '16.8', '15.7', '205', '11', ''] IDLE pops up with a dialog that says Non-ASCII found, yet no encoding declared. Add a line like # -*- coding: cp1252 -*- to your file Choose OK to save this file as cp1252 Edit your general options to silence this warning It has buttons: Ok, Edit my file Edit my file adds the commented line above to the top of the script. Could this possibly be causing his problem? HTH, Jacob >I don't know why this isn't working for you but this worked for me at a DOS >console: > >>> s='850hPa?' > >>> s > '850hPa\xf1' > >>> import re > >>> re.sub('\xf1', '*', s) > '850hPa*' > >>> import sys > >>> sys.stdout.encoding > 'cp437' > > and also in IDLE with a different encoding: > >>> s='850hPa?' > >>> s > '850hPa\xb1' > >>> import re > >>> re.sub('\xb1', '*', s) > '850hPa*' > >>> import sys > >>> sys.stdout.encoding > 'cp1252' > > So one guess is that the data is in a different encoding than what you > expect? When you print the string and get '\xb1', is that in the same > program that is doing the regex? > > Another approach would be to just pull out the numbers and ignore > everything else: > >>> s='Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts' > >>> l=s.split(',') > >>> l > ['Std Lvl: 850hPa', ' 1503m', ' 16.8C', ' 15.7C', ' 205 @ 11kts'] > >>> [ re.search(r'[\d\.]+', i).group() for i in l] > ['850', '1503', '16.8', '15.7', '205'] > > Kent > > Ertl, John wrote: >> All >> >> I have a string that has a bunch of numbers with the units attached to >> them. >> I want to strip off the units. I am using a regular expression and sub >> to >> do this. This works great for almost all of the cases. These are the >> type of lines: >> >> SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts >> SigWind: 850hPa?, , , , 205 @ 11kts >> Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts >> >> I am using the following cleanstring = re.compile( >> '(hPa|hPa\xb1|m|C|kts)' >> ). And then the cleanstring.sub("",line). I have tried using numerous \ >> to >> escape the \xb1. >> >> I also tried replacing all non numeric characters that are part of a >> number-character string but I could not make that work. The idea was >> replace >> all non-number characters in a "word" that is made up of numbers followed >> by >> numbers. >> >> I then split the line at the commas so in the current thinking I need the >> commas for the split. How do I deal with the hPa?? When I print it out >> it >> looks like it is a hexadecimal escape character (\xb1) but I am note sure >> how to deal with this. >> >> Any ideas? >> >> Thanks >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Sun Mar 27 22:38:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Mar 27 22:38:14 2005 Subject: [Tutor] hash()ing a list In-Reply-To: <3449428f05032709216c60f4dd@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503271137040.20418-100000@hkn.eecs.berkeley.edu> On Sun, 27 Mar 2005, Orri Ganel wrote: > While I do not have a pressing need to hash a list, I am curious as to > why, if lists are unhashable, there is a __hash__() method in the list > class, which also does not work on lists, but results in a 'TypeError: > list objects are unhashable'. What's the point of including a > __hash__() method in the list class if lists are unhashable? [warning: my post is long. Sorry!] Hi Orri, This is an interesting question! Let's check something: ###### >>> [].__hash__() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: list objects are unhashable ###### Yes, lists have a __hash__() function that isn't really meant to be called. Let's imagine that our list object didn't have a __hash__() function. If we try our expermient again, we can imagine that we might get something like this: ###### (thought experiment) --- not real Python! >>> [].__hash__() Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'list' object has no attribute '__hash__' ###### The error message here, in our thought experiment, is slightly less informative: rather than knowing that lists aren't meant to be hashed, we can imagine that we'd get a more generic AttributeError about lists not having a __hash__() method. So one possible explanation is that lists have a __hash__() to make sure we get good error messages when we misuse them. *grin* I have to admit that I'm making all this up as a story: I'm not sure if "better error message" is the real reason that lists have a customized __hash__(), although, from looking at the list implementation, this seems reasonable. [some time passes with Danny fiddling with CPython] >From my explorations below, my best story is that all Python objects must have a __hash__(), so list.__hash__ exists so that it errors out deliberately and early. I kept running notes of what I was trying, so if you're interested, read below. [The material below is for folks who are familiar with C, and goes into this in more rambling depth. Skip this if it starts looking weird. *grin*] In the C implementation of hash(), the implementation in Object.c appears to do the following: 1. Check to see if the object implements its own __hash__. 2. If it doesn't, check to see if it's allowed to just use the pointer address as a hash number --- basically check if the object type doesn't define an __eq__. 3. Finally, throw up its hands and just say "TypeError: unhashable type". (See PyObject_Hash() in Objects/object.c for the details) >From Objects/typeobject.c, it appears that all the base types in Python get a default implementation of __hash__ under a certain set of conditions: /******/ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) { if (type->tp_compare == NULL && type->tp_richcompare == NULL && type->tp_hash == NULL) { type->tp_compare = base->tp_compare; type->tp_richcompare = base->tp_richcompare; type->tp_hash = base->tp_hash; } } /******/ but because the Python list type does define its own rich comparison operators, no default hash function should be set. If I go ahead and munge up listobject.c so that it no longer has a tp_hash: /******/ mumak:~/Desktop/downloads/Python-2.4/Objects dyoo$ !diff diff -u listobject.c listobject.c2 --- listobject.c Sun Mar 27 12:12:11 2005 +++ listobject.c2 Sun Mar 27 12:11:52 2005 @@ -2660,7 +2660,8 @@ 0, /* tp_as_number */ &list_as_sequence, /* tp_as_sequence */ &list_as_mapping, /* tp_as_mapping */ - list_nohash, /* tp_hash */ + 0, /* tp_hash */ + /* list_nohash, */ /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ /******/ and recompile the interpreter, I'd expect that we'd end up with an object and who would respond to a hash() call with a "TypeError: unhashable type" error. Let's check that: ###### Warning: locally munged Python interpreter ###### mumak:~/local/Python-2.4 dyoo$ bin/python Python 2.4 (#1, Mar 27 2005, 12:18:24) [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> [].__hash__ <method-wrapper object at 0x38ac30> >>> [].__hash__() 3720536 >>> hash([]) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unhashable type ###### Weird. *grin* Ok, some of that was expected, and some of that was very unexpected. There must be some code path in the interpreter that still defines a default __hash__() somewhere, even if an implementation isn't given. But at least we do get an 'unhashable type' error if we use the builtin hash() function. So my best guess for Orri's question is: better error message. *grin* Anyway, I hope this helps! From kent37 at tds.net Mon Mar 28 00:31:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 28 00:31:22 2005 Subject: [Tutor] re question In-Reply-To: <002e01c5330a$bc3f6d10$115328cf@JSLAPTOP> References: <E338ADD616B66043824B9ABF5CA6EF2332C5B6@lanexc107p.fnmoc.navy.mil> <42454CC0.7080103@tds.net> <002e01c5330a$bc3f6d10$115328cf@JSLAPTOP> Message-ID: <42473434.5090306@tds.net> Jacob S. wrote: > Kent -- when pulling out just the numbers, why go to the trouble of > splitting by "," first? Good question. It made sense at the time :-) Here is another way using re.findall(): >>> import re >>> s='Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts' >>> re.findall(r'[\d\.]+', s) ['850', '1503', '16.8', '15.7', '205', '11'] Kent > > import re > pat = re.compile(r"[^\d.]*") > > t = """SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts > SigWind: 850hPa?, , , , 205 @ 11kts > Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts""" > > result = pat.split(t) > print result > > yields > > ['', '857', '21.0', '20.1', '210', '9', '850', '205', '11', '850', > '1503', '16.8', '15.7', '205', '11', ''] > > IDLE pops up with a dialog that says Non-ASCII found, yet no encoding > declared. Add a line like > # -*- coding: cp1252 -*- > to your file > Choose OK to save this file as cp1252 > Edit your general options to silence this warning > > It has buttons: Ok, Edit my file > Edit my file adds the commented line above to the top of the script. > > Could this possibly be causing his problem? > > HTH, > Jacob > >> I don't know why this isn't working for you but this worked for me at >> a DOS console: >> >>> s='850hPa?' >> >>> s >> '850hPa\xf1' >> >>> import re >> >>> re.sub('\xf1', '*', s) >> '850hPa*' >> >>> import sys >> >>> sys.stdout.encoding >> 'cp437' >> >> and also in IDLE with a different encoding: >> >>> s='850hPa?' >> >>> s >> '850hPa\xb1' >> >>> import re >> >>> re.sub('\xb1', '*', s) >> '850hPa*' >> >>> import sys >> >>> sys.stdout.encoding >> 'cp1252' >> >> So one guess is that the data is in a different encoding than what you >> expect? When you print the string and get '\xb1', is that in the same >> program that is doing the regex? >> >> Another approach would be to just pull out the numbers and ignore >> everything else: >> >>> s='Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts' >> >>> l=s.split(',') >> >>> l >> ['Std Lvl: 850hPa', ' 1503m', ' 16.8C', ' 15.7C', ' 205 @ 11kts'] >> >>> [ re.search(r'[\d\.]+', i).group() for i in l] >> ['850', '1503', '16.8', '15.7', '205'] >> >> Kent >> >> Ertl, John wrote: >> >>> All >>> >>> I have a string that has a bunch of numbers with the units attached >>> to them. >>> I want to strip off the units. I am using a regular expression and >>> sub to >>> do this. This works great for almost all of the cases. These are >>> the type of lines: >>> >>> SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts >>> SigWind: 850hPa?, , , , 205 @ 11kts >>> Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts >>> >>> I am using the following cleanstring = re.compile( >>> '(hPa|hPa\xb1|m|C|kts)' >>> ). And then the cleanstring.sub("",line). I have tried using >>> numerous \ to >>> escape the \xb1. >>> >>> I also tried replacing all non numeric characters that are part of a >>> number-character string but I could not make that work. The idea was >>> replace >>> all non-number characters in a "word" that is made up of numbers >>> followed by >>> numbers. >>> >>> I then split the line at the commas so in the current thinking I need >>> the >>> commas for the split. How do I deal with the hPa?? When I print it >>> out it >>> looks like it is a hexadecimal escape character (\xb1) but I am note >>> sure >>> how to deal with this. >>> >>> Any ideas? >>> >>> Thanks >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > From singingxduck at gmail.com Mon Mar 28 01:08:41 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon Mar 28 01:08:44 2005 Subject: [Tutor] unhashable objects (unrelated to previous topic) Message-ID: <3449428f050327150863073b1a@mail.gmail.com> Hello all, I am attempting to implement a LinkedList in Python, and in doing so, have created a Node class which represents the elements of the LinkedList. However, since these Nodes have custom-defined __lt__(), __gt__(), __le__(), __ge__(), __eq__(), and __ne__() methods, they are, for some reason, unhashable. When I comment out these methods, Python makes no complaint. But when they are present, 'TypeError: unhashable instance' is raised when attempting to use a Node as a key in a dictionary. The full error appears: Traceback (most recent call last): File "<pyshell#4>", line 1, in -toplevel- a.append(0) File "C:\Documents and Settings\Owner\Desktop\LinkedList.py", line 217, in append self.lltopl[self.head] = self.pylist[0] TypeError: unhashable instance ; the relevant code being: class LinkedList: def __init__(self,node=None): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" self.length = 0 self.pylist = [] self.lltopl = {} if node is not None and type(node) == list: self.head = None self.tail = None for i in range(len(node)): self.append(node[i]) elif node is not None and isinstance(node, LinkedList): self.head = None self.tail = None self.appendlist(node) else: if node is not None and not isinstance(node, Node): self.length += 1 self.pylist.append(Node(node).cargo) self.head = Node(node) elif node: self.length += 1 self.pylist.append(node.cargo) self.head = node else: self.head = node self.tail = None if len(self.pylist) != 0: self.lltopl[self.head] = self.pylist[0] if self.head: nod = self.head while nod.next: self.append(nod.next) nod = nod.next self.head.prev = None def append(self, cargo): """Only for the appending of single Nodes. To append multiple Nodes linked with .next and .prev, just use appendlist(linkedlist) method""" if not isinstance(cargo, Node): node = Node(cargo) else: node = cargo node.next = None node.prev = None if not self.head: self.head = node self.pylist.append(self.head.cargo) self.lltopl[self.head] = self.pylist[0] elif self.tail: self.tail.next = node node.prev = self.tail self.tail = node self.pylist.append(self.tail.cargo) self.lltopl[self.tail] = self.pylist[-1] else: self.head.next = node node.prev = self.head self.tail = node self.pylist.append(self.tail.cargo) self.lltopl[self.tail] = self.pylist[-1] self.length += 1 self.head.prev = None return True class Node: ## def __eq__(self, y): ## """x.__eq__(y) <==> x==y""" ## try: ## return self.cargo == y.cargo ## except: ## return self.cargo == y ## def __ge__(self, y): ## """x.__ge__(y) <==> x>=y""" ## try: ## return self.cargo >= y.cargo ## except: ## return self.cargo >= y ## def __gt__(self, y): ## """x.__gt__(y) <==> x>y""" ## try: ## return self.cargo > y.cargo ## except: ## return self.cargo > y def __init__(self, cargo=None, prev=None, next=None): self.cargo = cargo self.prev = prev self.next = next ## def __le__(self, y): ## """x.__le__(y) <==> x<=y""" ## try: ## return self.cargo <= y.cargo ## except: ## return self.cargo <= y ## def __lt__(self, y): ## """x.__lt__(y) <==> x<y""" ## try: ## return self.cargo < y.cargo ## except: ## return self.cargo < y ## def __ne__(self, y): ## """x.__ne__(y) <==> x!=y""" ## try: ## return self.cargo != y.cargo ## except: ## return self.cargo != y def __str__(self): return str(self.cargo) def cequals(self, node): if not isinstance(node, Node): node = Node(node) if self.cargo == node.cargo: return True return False def equals(self, node): if self.cequals(node) and self.nequals(node) and self.pequals(node): return True return False def pequals(self, node): if not isinstance(node, Node): if self.prev == node: return True elif self.prev == node.prev: return True return False def nequals(self, node): if not isinstance(node, Node): if self.next == node: return True elif self.next == node.next: return True return False Since the code here is unfinished and not in full form in any case, its not yet ready for suggestions, however, once I'm done with the implementation (a matter of finishing the docstrings and making unittests), I will welcome suggestions and comments. However, if anyone has any idea why custom comparing methods make an object unhashable, I'd be grateful. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Mon Mar 28 01:12:54 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon Mar 28 01:12:57 2005 Subject: [Tutor] hash()ing a list In-Reply-To: <Pine.LNX.4.44.0503271137040.20418-100000@hkn.eecs.berkeley.edu> References: <3449428f05032709216c60f4dd@mail.gmail.com> <Pine.LNX.4.44.0503271137040.20418-100000@hkn.eecs.berkeley.edu> Message-ID: <3449428f05032715127f2d4c52@mail.gmail.com> So, any class that has 'rich comparison methods' defined is unhashable? What gives? (See '[Tutor] unhashable objects') On Sun, 27 Mar 2005 12:38:09 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Sun, 27 Mar 2005, Orri Ganel wrote: > > > While I do not have a pressing need to hash a list, I am curious as to > > why, if lists are unhashable, there is a __hash__() method in the list > > class, which also does not work on lists, but results in a 'TypeError: > > list objects are unhashable'. What's the point of including a > > __hash__() method in the list class if lists are unhashable? > > [warning: my post is long. Sorry!] > > Hi Orri, > > This is an interesting question! Let's check something: > > ###### > >>> [].__hash__() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: list objects are unhashable > ###### > > Yes, lists have a __hash__() function that isn't really meant to be > called. > > Let's imagine that our list object didn't have a __hash__() function. If > we try our expermient again, we can imagine that we might get something > like this: > > ###### (thought experiment) --- not real Python! > >>> [].__hash__() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > AttributeError: 'list' object has no attribute '__hash__' > ###### > > The error message here, in our thought experiment, is slightly less > informative: rather than knowing that lists aren't meant to be hashed, we > can imagine that we'd get a more generic AttributeError about lists not > having a __hash__() method. > > So one possible explanation is that lists have a __hash__() to make sure > we get good error messages when we misuse them. *grin* > > I have to admit that I'm making all this up as a story: I'm not sure if > "better error message" is the real reason that lists have a customized > __hash__(), although, from looking at the list implementation, this seems > reasonable. > > [some time passes with Danny fiddling with CPython] > > From my explorations below, my best story is that all Python objects must > have a __hash__(), so list.__hash__ exists so that it errors out > deliberately and early. I kept running notes of what I was trying, so if > you're interested, read below. > > [The material below is for folks who are familiar with C, and goes into > this in more rambling depth. Skip this if it starts looking weird. > *grin*] > > In the C implementation of hash(), the implementation in Object.c appears > to do the following: > > 1. Check to see if the object implements its own __hash__. > 2. If it doesn't, check to see if it's allowed to just use the > pointer address as a hash number --- basically check if the object > type doesn't define an __eq__. > 3. Finally, throw up its hands and just say "TypeError: unhashable type". > > (See PyObject_Hash() in Objects/object.c for the details) > > From Objects/typeobject.c, it appears that all the base types in Python > get a default implementation of __hash__ under a certain set of > conditions: > > /******/ > if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) > { > if (type->tp_compare == NULL && > type->tp_richcompare == NULL && > type->tp_hash == NULL) > { > type->tp_compare = base->tp_compare; > type->tp_richcompare = base->tp_richcompare; > type->tp_hash = base->tp_hash; > } > } > /******/ > > but because the Python list type does define its own rich comparison > operators, no default hash function should be set. > > If I go ahead and munge up listobject.c so that it no longer has a > tp_hash: > > /******/ > mumak:~/Desktop/downloads/Python-2.4/Objects dyoo$ !diff > diff -u listobject.c listobject.c2 > --- listobject.c Sun Mar 27 12:12:11 2005 > +++ listobject.c2 Sun Mar 27 12:11:52 2005 > @@ -2660,7 +2660,8 @@ > 0, /* tp_as_number */ > &list_as_sequence, /* tp_as_sequence */ > &list_as_mapping, /* tp_as_mapping */ > - list_nohash, /* tp_hash */ > + 0, /* tp_hash */ > + /* list_nohash, */ /* tp_hash */ > 0, /* tp_call */ > 0, /* tp_str */ > PyObject_GenericGetAttr, /* tp_getattro */ > /******/ > > and recompile the interpreter, I'd expect that we'd end up with an object > and who would respond to a hash() call with a "TypeError: unhashable type" > error. Let's check that: > > ###### Warning: locally munged Python interpreter > ###### > mumak:~/local/Python-2.4 dyoo$ bin/python > Python 2.4 (#1, Mar 27 2005, 12:18:24) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> [].__hash__ > <method-wrapper object at 0x38ac30> > >>> [].__hash__() > 3720536 > >>> hash([]) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: unhashable type > ###### > > Weird. *grin* Ok, some of that was expected, and some of that was very > unexpected. There must be some code path in the interpreter that still > defines a default __hash__() somewhere, even if an implementation isn't > given. But at least we do get an 'unhashable type' error if we use the > builtin hash() function. > > So my best guess for Orri's question is: better error message. *grin* > > Anyway, I hope this helps! > > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From jeffshannon at gmail.com Mon Mar 28 01:33:16 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Mon Mar 28 01:33:19 2005 Subject: [Tutor] unhashable objects (unrelated to previous topic) In-Reply-To: <3449428f050327150863073b1a@mail.gmail.com> References: <3449428f050327150863073b1a@mail.gmail.com> Message-ID: <5d0204a105032715337e19cb17@mail.gmail.com> On Sun, 27 Mar 2005 18:08:41 -0500, Orri Ganel <singingxduck@gmail.com> wrote: > Hello all, > > I am attempting to implement a LinkedList in Python, and in doing so, > have created a Node class which represents the elements of the > LinkedList. However, since these Nodes have custom-defined __lt__(), > __gt__(), __le__(), __ge__(), __eq__(), and __ne__() methods, they > are, for some reason, unhashable. When I comment out these methods, > Python makes no complaint. But when they are present, 'TypeError: > unhashable instance' is raised when attempting to use a Node as a key > in a dictionary. When you don't define __eq__(), Python will use an object's ID as its hash value. However, the standard usage of hashes implies that objects which compare as equal should hash identically. This means that objects which define __eq__() and which are intended to be hashed need to define a __hash__() method. Be very careful if you're doing this with mutable objects, though -- you need to either hash by object identity or by object equality, and for mutable objects either choice will leave you breaking an implied promise. (Either a single object will not hash the same at different points in its life, or objects which are equal will not hash identically.) Jeff Shannon From singingxduck at gmail.com Mon Mar 28 01:54:36 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon Mar 28 01:54:40 2005 Subject: [Tutor] unhashable objects (unrelated to previous topic) In-Reply-To: <5d0204a105032715337e19cb17@mail.gmail.com> References: <3449428f050327150863073b1a@mail.gmail.com> <5d0204a105032715337e19cb17@mail.gmail.com> Message-ID: <3449428f05032715545dbbfc51@mail.gmail.com> Thanks to Jeff and John Fouhy . . . However, my question now is: can I treat Nodes sometimes the same and sometimes not? I want to treat Nodes whose cargo is the same the same everywhere *except* in a dictionary, because I want the user to be able to use LinkedList in a broader way than sets allow . . . In order to do this, I need my __hash__() method to treat Nodes differently than the rich comparison methods do. Is this a Bad Idea(tm) ? -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From python.programming at gmail.com Mon Mar 28 03:37:02 2005 From: python.programming at gmail.com (Kevin) Date: Mon Mar 28 03:37:05 2005 Subject: [Tutor] How and where to use pass and continue Message-ID: <d082fff805032717372f2b4995@mail.gmail.com> I am having lot of trouble learning where and when to use pass and continue. The two books that I use don't explian these very good. Is there a website the explains these is great detail? I have also looked at the python tutorial as well. Thanks Kevin From cyresse at gmail.com Mon Mar 28 04:22:29 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Mar 28 04:22:32 2005 Subject: Fwd: [Tutor] How and where to use pass and continue In-Reply-To: <f2ff2d050327182245b343eb@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> <f2ff2d050327182245b343eb@mail.gmail.com> Message-ID: <f2ff2d05032718225ca08c8@mail.gmail.com> Oops, forward to list as well. ---------- Forwarded message ---------- From: Liam Clarke <cyresse@gmail.com> Date: Mon, 28 Mar 2005 14:22:00 +1200 Subject: Re: [Tutor] How and where to use pass and continue To: Kevin <python.programming@gmail.com> Hi Kevin, I generally use pass as a placeholder - if you have a function that you want to define so you can use it without creating syntax errors, but you haven't written it yet, it's just a case of - def neededFunc(x): pass continue is good. say you have a loop - for i in range(10): if i % 2 == 0: continue print i * 3 So, what the loop does, is it gets i, checks if i divided by 2 has zero remainder and if it does, it continues. Which, basically means, it doesn't do anything else in the loop (i.e. print i * 3), it just goes back, get the next value of i, and go through the loop again. You'll find you don't need continue that often. It's good for checking an value in a list you're looping through meets your criteria before passing it to a big function. That's about it. HTH, Liam Clarke On Sun, 27 Mar 2005 20:37:02 -0500, Kevin <python.programming@gmail.com> wrote: > I am having lot of trouble learning where and when to use pass and > continue. The two books that I use don't explian these very good. Is > there a website the explains these is great detail? > I have also looked at the python tutorial as well. > > Thanks > > Kevin > _______________________________________________ > 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. -- '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. From shaleh at speakeasy.net Mon Mar 28 04:28:57 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Mon Mar 28 04:31:10 2005 Subject: [Tutor] How and where to use pass and continue In-Reply-To: <d082fff805032717372f2b4995@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> Message-ID: <42476BE9.8040102@speakeasy.net> Kevin wrote: > I am having lot of trouble learning where and when to use pass and > continue. The two books that I use don't explian these very good. Is > there a website the explains these is great detail? > I have also looked at the python tutorial as well. > language idioms are one of the hardest things to learn and only really come after having written code and then coming back to it later. My thoughts on the subject. continue is a common idiom in I/O routines. for line in fp.xreadlines(): line = line.strip() if not line: continue # process line data here pass is an odd one. I tend to use it while prototyping to set up the bones of control statements to be. def func(one, two): if sometest(one): pass # need to actually do something here # work with one and two pass can also be used in multi-catch functions / control statements if input == 'something': handle_something(input) elif input == 'other': pass else: # do stuff here We want to ignore 'other' for some reason, so just use pass. Also handy if a value could be one of N choices but we only handle a few cases. This way someone else reading the code does not think "hey wait, they do not check for 'foo'!". From bill.mill at gmail.com Mon Mar 28 04:43:45 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon Mar 28 04:43:48 2005 Subject: [Tutor] How and where to use pass and continue In-Reply-To: <d082fff805032717372f2b4995@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> Message-ID: <797fe3d4050327184362d1ef31@mail.gmail.com> On Sun, 27 Mar 2005 20:37:02 -0500, Kevin <python.programming@gmail.com> wrote: > I am having lot of trouble learning where and when to use pass and > continue. The two books that I use don't explian these very good. Is > there a website the explains these is great detail? > I have also looked at the python tutorial as well. Kevin, I'll try to help you out - pass and continue are pretty simple concepts. Consider the following code snippet which I will try to use to explain both: command = None while command != '3': command = raw_input("Press 1 to pass, 2 to continue, or 3 to exit ") if command == '1': print "passing" pass elif command == '2': print "continuing" continue else: print "othering" print "end of loop reached" print "exiting" PASS The 'pass' statement simply means 'do nothing'. In the example above, when the python interpreter encounters the pass statement, it simply continues with its execution as it normally would. It is usually used as the only statement in the body of an if statement to denote explicitly that nothing is to be done. I will often use it as a placeholder so that a program compiles correctly, like: if 'a': do_something() elif 'b': #TODO: implement do_something_else() pass elif 'c': quit_foo() Without the pass statement, there are no statements in the second block, and python will raise a SyntaxError. In the first example above, Python sees the pass, exits the series of 'If...elif..." conditions, advances to the final statement of the while loop, prints "end of loop reached", and resumes execution at the top of the loop. CONTINUE The continue statement means what it says - continue with the loop, but resume execution at the top of the loop. In the case of a while loop, the exit condition will be evaluated again, and execution resumes from the top. In the case of a for loop, the item being iterated over will move to its next element. Thus, for i in (1,2): print i continue print "we never get here" Will print 1, hit the continue, update i to the value 2, print 2, hit the continue, and exit because there are no more iterations for i. In the first example I gave, after python reaches the continue, 'command' is again evaluated to see if its value is 3, then the loop proceeds from the top down. If you run the example, you should be able to figure out what's going on. There are a couple more wrinkles - for example, continue only works on the innermost loop in its execution context - but generally, they work as you expect. The longer you work with python, the more you'll find this to be the case, but I'm biased. Hope this helps, and feel free to ask questions about what you don't understand. Peace Bill Mill bill.mill at gmail.com > > Thanks > > Kevin > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python.programming at gmail.com Mon Mar 28 05:13:45 2005 From: python.programming at gmail.com (Kevin) Date: Mon Mar 28 05:13:48 2005 Subject: [Tutor] How and where to use pass and continue In-Reply-To: <797fe3d4050327184362d1ef31@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> <797fe3d4050327184362d1ef31@mail.gmail.com> Message-ID: <d082fff805032719132ad7ad21@mail.gmail.com> That was a great help I understand now what they do and how to use them. Thanks alot for all your help. On Sun, 27 Mar 2005 21:43:45 -0500, Bill Mill <bill.mill@gmail.com> wrote: > On Sun, 27 Mar 2005 20:37:02 -0500, Kevin <python.programming@gmail.com> wrote: > > I am having lot of trouble learning where and when to use pass and > > continue. The two books that I use don't explian these very good. Is > > there a website the explains these is great detail? > > I have also looked at the python tutorial as well. > > Kevin, > > I'll try to help you out - pass and continue are pretty simple > concepts. Consider the following code snippet which I will try to use > to explain both: > > command = None > while command != '3': > command = raw_input("Press 1 to pass, 2 to continue, or 3 to exit ") > if command == '1': > print "passing" > pass > elif command == '2': > print "continuing" > continue > else: > print "othering" > print "end of loop reached" > print "exiting" > > PASS > > The 'pass' statement simply means 'do nothing'. In the example above, > when the python interpreter encounters the pass statement, it simply > continues with its execution as it normally would. It is usually used > as the only statement in the body of an if statement to denote > explicitly that nothing is to be done. I will often use it as a > placeholder so that a program compiles correctly, like: > > if 'a': > do_something() > elif 'b': > #TODO: implement do_something_else() > pass > elif 'c': > quit_foo() > > Without the pass statement, there are no statements in the second > block, and python will raise a SyntaxError. > > In the first example above, Python sees the pass, exits the series of > 'If...elif..." conditions, advances to the final statement of the > while loop, prints "end of loop reached", and resumes execution at the > top of the loop. > > CONTINUE > > The continue statement means what it says - continue with the loop, > but resume execution at the top of the loop. In the case of a while > loop, the exit condition will be evaluated again, and execution > resumes from the top. In the case of a for loop, the item being > iterated over will move to its next element. Thus, > > for i in (1,2): > print i > continue > print "we never get here" > > Will print 1, hit the continue, update i to the value 2, print 2, hit > the continue, and exit because there are no more iterations for i. > > In the first example I gave, after python reaches the continue, > 'command' is again evaluated to see if its value is 3, then the loop > proceeds from the top down. If you run the example, you should be able > to figure out what's going on. > > There are a couple more wrinkles - for example, continue only works on > the innermost loop in its execution context - but generally, they work > as you expect. The longer you work with python, the more you'll find > this to be the case, but I'm biased. > > Hope this helps, and feel free to ask questions about what you don't understand. > > Peace > Bill Mill > bill.mill at gmail.com > > > > > Thanks > > > > Kevin > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From python.programming at gmail.com Mon Mar 28 05:23:59 2005 From: python.programming at gmail.com (Kevin) Date: Mon Mar 28 05:24:04 2005 Subject: [Tutor] How and where to use pass and continue In-Reply-To: <d082fff805032719132ad7ad21@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> <797fe3d4050327184362d1ef31@mail.gmail.com> <d082fff805032719132ad7ad21@mail.gmail.com> Message-ID: <d082fff80503271923511a7be3@mail.gmail.com> Ok I have another question now I noticed that at the tope of a while loop there will be somthing like this: test = None while test != "enter": test = raw_input("Type a word: ") if test == "enter": break what is the purpose of test = None ? Thanks Kevin On Sun, 27 Mar 2005 22:13:45 -0500, Kevin <python.programming@gmail.com> wrote: > That was a great help I understand now what they do and how to use > them. Thanks alot for all your help. > > > On Sun, 27 Mar 2005 21:43:45 -0500, Bill Mill <bill.mill@gmail.com> wrote: > > On Sun, 27 Mar 2005 20:37:02 -0500, Kevin <python.programming@gmail.com> wrote: > > > I am having lot of trouble learning where and when to use pass and > > > continue. The two books that I use don't explian these very good. Is > > > there a website the explains these is great detail? > > > I have also looked at the python tutorial as well. > > > > Kevin, > > > > I'll try to help you out - pass and continue are pretty simple > > concepts. Consider the following code snippet which I will try to use > > to explain both: > > > > command = None > > while command != '3': > > command = raw_input("Press 1 to pass, 2 to continue, or 3 to exit ") > > if command == '1': > > print "passing" > > pass > > elif command == '2': > > print "continuing" > > continue > > else: > > print "othering" > > print "end of loop reached" > > print "exiting" > > > > PASS > > > > The 'pass' statement simply means 'do nothing'. In the example above, > > when the python interpreter encounters the pass statement, it simply > > continues with its execution as it normally would. It is usually used > > as the only statement in the body of an if statement to denote > > explicitly that nothing is to be done. I will often use it as a > > placeholder so that a program compiles correctly, like: > > > > if 'a': > > do_something() > > elif 'b': > > #TODO: implement do_something_else() > > pass > > elif 'c': > > quit_foo() > > > > Without the pass statement, there are no statements in the second > > block, and python will raise a SyntaxError. > > > > In the first example above, Python sees the pass, exits the series of > > 'If...elif..." conditions, advances to the final statement of the > > while loop, prints "end of loop reached", and resumes execution at the > > top of the loop. > > > > CONTINUE > > > > The continue statement means what it says - continue with the loop, > > but resume execution at the top of the loop. In the case of a while > > loop, the exit condition will be evaluated again, and execution > > resumes from the top. In the case of a for loop, the item being > > iterated over will move to its next element. Thus, > > > > for i in (1,2): > > print i > > continue > > print "we never get here" > > > > Will print 1, hit the continue, update i to the value 2, print 2, hit > > the continue, and exit because there are no more iterations for i. > > > > In the first example I gave, after python reaches the continue, > > 'command' is again evaluated to see if its value is 3, then the loop > > proceeds from the top down. If you run the example, you should be able > > to figure out what's going on. > > > > There are a couple more wrinkles - for example, continue only works on > > the innermost loop in its execution context - but generally, they work > > as you expect. The longer you work with python, the more you'll find > > this to be the case, but I'm biased. > > > > Hope this helps, and feel free to ask questions about what you don't understand. > > > > Peace > > Bill Mill > > bill.mill at gmail.com > > > > > > > > Thanks > > > > > > Kevin > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > From shaleh at speakeasy.net Mon Mar 28 05:48:58 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Mon Mar 28 05:51:09 2005 Subject: [Tutor] How and where to use pass and continue In-Reply-To: <d082fff80503271923511a7be3@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> <797fe3d4050327184362d1ef31@mail.gmail.com> <d082fff805032719132ad7ad21@mail.gmail.com> <d082fff80503271923511a7be3@mail.gmail.com> Message-ID: <42477EAA.8000001@speakeasy.net> Kevin wrote: > Ok I have another question now I noticed that at the tope of a while > loop there will be somthing like this: > > test = None > while test != "enter": > test = raw_input("Type a word: ") > if test == "enter": > break > > what is the purpose of test = None ? > 'test' must be given a value before Python will use it. Without the first assignment, the program will fail to execute the first time it reaches the unknown variable. Think of it as riming the pump. From kent37 at tds.net Mon Mar 28 05:52:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 28 05:53:01 2005 Subject: [Tutor] unhashable objects (unrelated to previous topic) In-Reply-To: <3449428f05032715545dbbfc51@mail.gmail.com> References: <3449428f050327150863073b1a@mail.gmail.com> <5d0204a105032715337e19cb17@mail.gmail.com> <3449428f05032715545dbbfc51@mail.gmail.com> Message-ID: <42477F97.9040106@tds.net> Orri Ganel wrote: > Thanks to Jeff and John Fouhy . . . However, my question now is: can I > treat Nodes sometimes the same and sometimes not? I want to treat > Nodes whose cargo is the same the same everywhere *except* in a > dictionary, because I want the user to be able to use LinkedList in a > broader way than sets allow . . . In order to do this, I need my > __hash__() method to treat Nodes differently than the rich comparison > methods do. Is this a Bad Idea(tm) ? The problem is, if you have two Nodes a and b where a == b, you will expect that for any dictionary d[a] == d[b]. If Node.__eq__() has different semantics than Node.__hash__() this expectation will not be correct. Kent From kent37 at tds.net Mon Mar 28 05:57:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 28 05:57:21 2005 Subject: [Tutor] How and where to use pass and continue In-Reply-To: <d082fff80503271923511a7be3@mail.gmail.com> References: <d082fff805032717372f2b4995@mail.gmail.com> <797fe3d4050327184362d1ef31@mail.gmail.com> <d082fff805032719132ad7ad21@mail.gmail.com> <d082fff80503271923511a7be3@mail.gmail.com> Message-ID: <4247809C.3090403@tds.net> Kevin wrote: > Ok I have another question now I noticed that at the tope of a while > loop there will be somthing like this: > > test = None > while test != "enter": > test = raw_input("Type a word: ") > if test == "enter": > break > > what is the purpose of test = None ? Otherwise you will get a NameError the first time the while is executed because test is not defined. Personally I prefer this form of the loop which is shorter and doesn't duplicate the test: while True: test = raw_input("Type a word: ") if test == "enter": break Kent > > Thanks > Kevin > > > On Sun, 27 Mar 2005 22:13:45 -0500, Kevin <python.programming@gmail.com> wrote: > >>That was a great help I understand now what they do and how to use >>them. Thanks alot for all your help. >> >> >>On Sun, 27 Mar 2005 21:43:45 -0500, Bill Mill <bill.mill@gmail.com> wrote: >> >>>On Sun, 27 Mar 2005 20:37:02 -0500, Kevin <python.programming@gmail.com> wrote: >>> >>>>I am having lot of trouble learning where and when to use pass and >>>>continue. The two books that I use don't explian these very good. Is >>>>there a website the explains these is great detail? >>>>I have also looked at the python tutorial as well. >>> >>>Kevin, >>> >>>I'll try to help you out - pass and continue are pretty simple >>>concepts. Consider the following code snippet which I will try to use >>>to explain both: >>> >>>command = None >>>while command != '3': >>> command = raw_input("Press 1 to pass, 2 to continue, or 3 to exit ") >>> if command == '1': >>> print "passing" >>> pass >>> elif command == '2': >>> print "continuing" >>> continue >>> else: >>> print "othering" >>> print "end of loop reached" >>>print "exiting" >>> >>>PASS >>> >>>The 'pass' statement simply means 'do nothing'. In the example above, >>>when the python interpreter encounters the pass statement, it simply >>>continues with its execution as it normally would. It is usually used >>>as the only statement in the body of an if statement to denote >>>explicitly that nothing is to be done. I will often use it as a >>>placeholder so that a program compiles correctly, like: >>> >>>if 'a': >>> do_something() >>>elif 'b': >>> #TODO: implement do_something_else() >>> pass >>>elif 'c': >>> quit_foo() >>> >>>Without the pass statement, there are no statements in the second >>>block, and python will raise a SyntaxError. >>> >>>In the first example above, Python sees the pass, exits the series of >>>'If...elif..." conditions, advances to the final statement of the >>>while loop, prints "end of loop reached", and resumes execution at the >>>top of the loop. >>> >>>CONTINUE >>> >>>The continue statement means what it says - continue with the loop, >>>but resume execution at the top of the loop. In the case of a while >>>loop, the exit condition will be evaluated again, and execution >>>resumes from the top. In the case of a for loop, the item being >>>iterated over will move to its next element. Thus, >>> >>>for i in (1,2): >>> print i >>> continue >>> print "we never get here" >>> >>>Will print 1, hit the continue, update i to the value 2, print 2, hit >>>the continue, and exit because there are no more iterations for i. >>> >>>In the first example I gave, after python reaches the continue, >>>'command' is again evaluated to see if its value is 3, then the loop >>>proceeds from the top down. If you run the example, you should be able >>>to figure out what's going on. >>> >>>There are a couple more wrinkles - for example, continue only works on >>>the innermost loop in its execution context - but generally, they work >>>as you expect. The longer you work with python, the more you'll find >>>this to be the case, but I'm biased. >>> >>>Hope this helps, and feel free to ask questions about what you don't understand. >>> >>>Peace >>>Bill Mill >>>bill.mill at gmail.com >>> >>> >>>>Thanks >>>> >>>>Kevin >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From garnaez at gmail.com Mon Mar 28 09:11:13 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Mon Mar 28 09:11:16 2005 Subject: [Tutor] If elif not working in comparison Message-ID: <148eea7105032723117df16132@mail.gmail.com> Hi all, I am trying to get a value dependant on initial vlaue inputed Depending on the value, I want the functiont to return a percentage For some reason, It seems to skip the first if state and just print out the 1st elif not sure what is going. also, is there a cleaner way to write this? -=------------------------- #! /usr/bin/env python ''' Calulate the percent increase in dose given an INR value. ''' def INRadjust(x): if x < 1: return .15 elif x < 1.5: return .12 elif x < 1.75: return .1 elif x < 1.9: return .05 elif x < 3.1: return 0 elif x < 4.1: return -.1 elif x < 5.1: return -.2 elif x < 6.1: return -.25 elif x < 7.1: return -.3 else: print "Notify Doctor" From libsvm at tom.com Mon Mar 28 11:15:52 2005 From: libsvm at tom.com (libsvm) Date: Mon Mar 28 11:24:28 2005 Subject: [Tutor] Question about urllib module? Message-ID: <1112001353.31182.16.camel@qlli> Dear all, I was learning how to use the urllib, BUT there is nothing printed out in the following example. Could anyone hellp me or tell why? import urllib params = urllib.urlencode({'DN':'Adrenal glands disorders'}) address="http://xin.cz3.nus.edu.sg/group/cjttd/List.asp?SetQuery=Y" f = urllib.urlopen(address,params) print f.read() Regards, Denny From kent37 at tds.net Mon Mar 28 13:32:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 28 13:32:33 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <148eea7105032723117df16132@mail.gmail.com> References: <148eea7105032723117df16132@mail.gmail.com> Message-ID: <4247EB4B.3090403@tds.net> gerardo arnaez wrote: > Hi all, > I am trying to get a value dependant on initial vlaue inputed > Depending on the value, I want the functiont to return a percentage > For some reason, It seems to skip the first if state and just print > out the 1st elif > not sure what is going. Are you sure you are passing a number to the function? If you are passing a value you received from raw_input it is a string. > also, is there a cleaner way to write this? I would use a list of value pairs. It separates the data from the code so it is easier to see what is going on. Here is a version that does this. It also ensures that the input value is a float: def INRadjust(x): cutoffs = [ (1, .15), (1.5, .12), (1.75, .1), (1.9, .05), (3.1, 0), (4.1, -.1), (5.1, -.2), (6.1, -.25), (7.1, -.3), ] x = float(x) # make sure x is a number for cutoff, value in cutoffs: if x < cutoff: return value print "Notify doctor" Kent > -=------------------------- > > > #! /usr/bin/env python > ''' > Calulate the percent increase in dose given an INR value. > ''' > > def INRadjust(x): > if x < 1: > return .15 > elif x < 1.5: > return .12 > elif x < 1.75: > return .1 > elif x < 1.9: > return .05 > elif x < 3.1: > return 0 > elif x < 4.1: > return -.1 > elif x < 5.1: > return -.2 > elif x < 6.1: > return -.25 > elif x < 7.1: > return -.3 > else: > print "Notify Doctor" > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From john.ertl at fnmoc.navy.mil Mon Mar 28 16:16:16 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Mon Mar 28 16:13:40 2005 Subject: [Tutor] re question Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C5C7@lanexc107p.fnmoc.navy.mil> All, Thanks. I love this list...great freindly advice. I had taken a slightly longer approach to Kent's "re.findall(r'[\d\.]+', s)" but the simplicity is just too good to pass up. Jacob I too got the warning about encoding and saved with the line added. It still would not strip out the charecter...I may try a bit harder to make it work just becouse it bugs me that you made it work. Thanks again John Ertl -----Original Message----- From: Kent Johnson Cc: tutor@python.org Sent: 3/27/05 2:31 PM Subject: Re: [Tutor] re question Jacob S. wrote: > Kent -- when pulling out just the numbers, why go to the trouble of > splitting by "," first? Good question. It made sense at the time :-) Here is another way using re.findall(): >>> import re >>> s='Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts' >>> re.findall(r'[\d\.]+', s) ['850', '1503', '16.8', '15.7', '205', '11'] Kent > > import re > pat = re.compile(r"[^\d.]*") > > t = """SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts > SigWind: 850hPa?, , , , 205 @ 11kts > Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts""" > > result = pat.split(t) > print result > > yields > > ['', '857', '21.0', '20.1', '210', '9', '850', '205', '11', '850', > '1503', '16.8', '15.7', '205', '11', ''] > > IDLE pops up with a dialog that says Non-ASCII found, yet no encoding > declared. Add a line like > # -*- coding: cp1252 -*- > to your file > Choose OK to save this file as cp1252 > Edit your general options to silence this warning > > It has buttons: Ok, Edit my file > Edit my file adds the commented line above to the top of the script. > > Could this possibly be causing his problem? > > HTH, > Jacob > >> I don't know why this isn't working for you but this worked for me at >> a DOS console: >> >>> s='850hPa?' >> >>> s >> '850hPa\xf1' >> >>> import re >> >>> re.sub('\xf1', '*', s) >> '850hPa*' >> >>> import sys >> >>> sys.stdout.encoding >> 'cp437' >> >> and also in IDLE with a different encoding: >> >>> s='850hPa?' >> >>> s >> '850hPa\xb1' >> >>> import re >> >>> re.sub('\xb1', '*', s) >> '850hPa*' >> >>> import sys >> >>> sys.stdout.encoding >> 'cp1252' >> >> So one guess is that the data is in a different encoding than what you >> expect? When you print the string and get '\xb1', is that in the same >> program that is doing the regex? >> >> Another approach would be to just pull out the numbers and ignore >> everything else: >> >>> s='Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts' >> >>> l=s.split(',') >> >>> l >> ['Std Lvl: 850hPa', ' 1503m', ' 16.8C', ' 15.7C', ' 205 @ 11kts'] >> >>> [ re.search(r'[\d\.]+', i).group() for i in l] >> ['850', '1503', '16.8', '15.7', '205'] >> >> Kent >> >> Ertl, John wrote: >> >>> All >>> >>> I have a string that has a bunch of numbers with the units attached >>> to them. >>> I want to strip off the units. I am using a regular expression and >>> sub to >>> do this. This works great for almost all of the cases. These are >>> the type of lines: >>> >>> SigWind: 857hPa, , 21.0C, 20.1C, 210 @ 9kts >>> SigWind: 850hPa?, , , , 205 @ 11kts >>> Std Lvl: 850hPa, 1503m, 16.8C, 15.7C, 205 @ 11kts >>> >>> I am using the following cleanstring = re.compile( >>> '(hPa|hPa\xb1|m|C|kts)' >>> ). And then the cleanstring.sub("",line). I have tried using >>> numerous \ to >>> escape the \xb1. >>> >>> I also tried replacing all non numeric characters that are part of a >>> number-character string but I could not make that work. The idea was >>> replace >>> all non-number characters in a "word" that is made up of numbers >>> followed by >>> numbers. >>> >>> I then split the line at the commas so in the current thinking I need >>> the >>> commas for the split. How do I deal with the hPa?? When I print it >>> out it >>> looks like it is a hexadecimal escape character (\xb1) but I am note >>> sure >>> how to deal with this. >>> >>> Any ideas? >>> >>> Thanks >>> _______________________________________________ >>> 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 maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From python.programming at gmail.com Mon Mar 28 20:35:20 2005 From: python.programming at gmail.com (Kevin) Date: Mon Mar 28 20:35:27 2005 Subject: [Tutor] An attribute error problem Message-ID: <d082fff805032810351f6f7be5@mail.gmail.com> Hi, I fond this game on the internet I was able to fix most of the errors that it was giving and it will now start up ok. However when you try to enter a name to login to the game it will crash and give this: in sServer.py line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' How would I go about fixing this. I have uploaded to entire game to http://lotheria.com/mudmaker.zp if anyone would care to take a look at it. Thanks Kevin From python.programming at gmail.com Mon Mar 28 20:46:29 2005 From: python.programming at gmail.com (Kevin) Date: Mon Mar 28 20:46:35 2005 Subject: [Tutor] Re: An attribute error problem In-Reply-To: <d082fff805032810351f6f7be5@mail.gmail.com> References: <d082fff805032810351f6f7be5@mail.gmail.com> Message-ID: <d082fff80503281046165a22c3@mail.gmail.com> Sorry http://www.lotheria.com/mudmaker.zip On Mon, 28 Mar 2005 13:35:20 -0500, Kevin <python.programming@gmail.com> wrote: > Hi, > > I fond this game on the internet I was able to fix most of the errors > that it was giving and it will > now start up ok. However when you try to enter a name to login to the > game it will crash and > give this: > > in sServer.py > line 42, in removeConnection > self._descriptors.remove(conn._fd) > AttributeError: 'tuple' object has no attribute '_fd' > > How would I go about fixing this. > > I have uploaded to entire game to http://lotheria.com/mudmaker.zp if > anyone would care to > take a look at it. > > Thanks > > Kevin > From kent37 at tds.net Mon Mar 28 20:50:07 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 28 20:50:10 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <d082fff805032810351f6f7be5@mail.gmail.com> References: <d082fff805032810351f6f7be5@mail.gmail.com> Message-ID: <424851DF.1050206@tds.net> Kevin wrote: > Hi, > > I fond this game on the internet I was able to fix most of the errors > that it was giving and it will > now start up ok. However when you try to enter a name to login to the > game it will crash and > give this: > > in sServer.py > line 42, in removeConnection > self._descriptors.remove(conn._fd) > AttributeError: 'tuple' object has no attribute '_fd' > > How would I go about fixing this. This error is because the caller is passing the wrong kind of argument to removeConnection. It seems to expect a connection object but it is getting a tuple instead. My guess is the error is the line self.closeConnection((self, f)) in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be self.closeConnection(self._connections[f]) ?? > I have uploaded to entire game to http://lotheria.com/mudmaker.zp if > anyone would care to > take a look at it. That should be http://lotheria.com/mudmaker.zip Kent From python.programming at gmail.com Mon Mar 28 20:56:29 2005 From: python.programming at gmail.com (Kevin) Date: Mon Mar 28 20:56:32 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <424851DF.1050206@tds.net> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> Message-ID: <d082fff80503281056136e8a6d@mail.gmail.com> Nope it will still give the same Attribute error. On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson <kent37@tds.net> wrote: > Kevin wrote: > > Hi, > > > > I fond this game on the internet I was able to fix most of the errors > > that it was giving and it will > > now start up ok. However when you try to enter a name to login to the > > game it will crash and > > give this: > > > > in sServer.py > > line 42, in removeConnection > > self._descriptors.remove(conn._fd) > > AttributeError: 'tuple' object has no attribute '_fd' > > > > How would I go about fixing this. > > This error is because the caller is passing the wrong kind of argument to removeConnection. It seems > to expect a connection object but it is getting a tuple instead. > > My guess is the error is the line > self.closeConnection((self, f)) > in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be > self.closeConnection(self._connections[f]) ?? > > > I have uploaded to entire game to http://lotheria.com/mudmaker.zp if > > anyone would care to > > take a look at it. > > That should be http://lotheria.com/mudmaker.zip > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From orbitz at drorbitz.ath.cx Mon Mar 28 16:27:11 2005 From: orbitz at drorbitz.ath.cx (orbitz) Date: Mon Mar 28 20:57:36 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <4247EB4B.3090403@tds.net> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> Message-ID: <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> Floats are inherintly inprecise. So if thigns arn't working like you expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same number than you think. On Mar 28, 2005, at 6:32 AM, Kent Johnson wrote: > gerardo arnaez wrote: >> Hi all, >> I am trying to get a value dependant on initial vlaue inputed >> Depending on the value, I want the functiont to return a percentage >> For some reason, It seems to skip the first if state and just print >> out the 1st elif >> not sure what is going. > > Are you sure you are passing a number to the function? If you are > passing a value you received from raw_input it is a string. > >> also, is there a cleaner way to write this? > > I would use a list of value pairs. It separates the data from the code > so it is easier to see what is going on. Here is a version that does > this. It also ensures that the input value is a float: > > def INRadjust(x): > cutoffs = [ > (1, .15), > (1.5, .12), > (1.75, .1), > (1.9, .05), > (3.1, 0), > (4.1, -.1), > (5.1, -.2), > (6.1, -.25), > (7.1, -.3), > ] > > x = float(x) # make sure x is a number > for cutoff, value in cutoffs: > if x < cutoff: > return value > > print "Notify doctor" > > Kent >> -=------------------------- >> #! /usr/bin/env python >> ''' >> Calulate the percent increase in dose given an INR value. >> ''' >> def INRadjust(x): >> if x < 1: >> return .15 >> elif x < 1.5: >> return .12 >> elif x < 1.75: >> return .1 >> elif x < 1.9: >> return .05 >> elif x < 3.1: >> return 0 >> elif x < 4.1: >> return -.1 >> elif x < 5.1: >> return -.2 >> elif x < 6.1: >> return -.25 >> elif x < 7.1: >> return -.3 >> else: >> print "Notify Doctor" >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Mon Mar 28 21:06:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Mar 28 21:06:52 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <d082fff80503281056136e8a6d@mail.gmail.com> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> <d082fff80503281056136e8a6d@mail.gmail.com> Message-ID: <424855C9.3080205@tds.net> Kevin wrote: > Nope it will still give the same Attribute error. Please post the entire error including the stack trace and the whole error message. Copy and paste the whole thing, don't transcribe it. Kent > > > On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson <kent37@tds.net> wrote: > >>Kevin wrote: >> >>>Hi, >>> >>>I fond this game on the internet I was able to fix most of the errors >>>that it was giving and it will >>>now start up ok. However when you try to enter a name to login to the >>>game it will crash and >>>give this: >>> >>>in sServer.py >>>line 42, in removeConnection >>> self._descriptors.remove(conn._fd) >>>AttributeError: 'tuple' object has no attribute '_fd' >>> >>>How would I go about fixing this. >> >>This error is because the caller is passing the wrong kind of argument to removeConnection. It seems >>to expect a connection object but it is getting a tuple instead. >> >>My guess is the error is the line >> self.closeConnection((self, f)) >>in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be >> self.closeConnection(self._connections[f]) ?? >> >> >>>I have uploaded to entire game to http://lotheria.com/mudmaker.zp if >>>anyone would care to >>>take a look at it. >> >>That should be http://lotheria.com/mudmaker.zip >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > From dyoo at hkn.eecs.berkeley.edu Mon Mar 28 21:33:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Mar 28 21:33:08 2005 Subject: [Tutor] hash()ing a list In-Reply-To: <3449428f05032715127f2d4c52@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> On Sun, 27 Mar 2005, Orri Ganel wrote: > So, any class that has 'rich comparison methods' defined is unhashable? > What gives? (See '[Tutor] unhashable objects') Hi Orri, If we change what it means for two objects to be equal, hashing won't work in a nice way until we also make hashing take equality into account. Here's an example, using a fairly useless Pair class: ###### >>> class Pair(object): ... def __init__(self, x, y): ... self.x, self.y = x, y ... def __repr__(self): ... return 'Pair(%s, %s)' % (self.x, self.y) ... def __eq__(self, other): ... return (self.x, self.y) == (other.x, other.y) ... >>> p1 = Pair(3, 4) >>> p1 Pair(3, 4) >>> p2 = Pair(3, 4) >>> p2 Pair(3, 4) >>> p1 == p2 True ###### (I know, this class is really useless since we already have tuples, but bear with me. *grin*) Say that we might want to use pairs as keys in a dictionary. Naively, we just do it: ###### >>> d = {} >>> d[Pair(17, 29)] = 'saturn' ###### And things look ok so far: ### >>> d {Pair(17, 29): 'saturn'} ### But if we go back and try to retrieve 'saturn' through our key, we're in for a surprise: ###### >>> d[Pair(17, 29)] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: Pair(17, 29) ###### The reason is because different Pair instances, by default, hash to different values: ###### >>> hash(Pair(17, 29)) 1076767244 >>> hash(Pair(17, 29)) 1076767116 ###### The default hash code of an object is its memory address: that's why the numbers are different here. So to make this work, to allow Pairs to be used reliably as keys, we also have to write an appropriate __hash__() function that overrides the default: ###### def __hash__(self): return hash((self.x, self.y)) ###### And the other direction is true: if we define a __hash__() function, we have to write a comparison function for equality, or else the hash scheme also breaks: ###### >>> class Pair2: ... def __init__(self, x, y): self.x, self.y = x, y ... def __repr__(self): return "Pair2(%s, %s)" % (self.x, self.y) ... def __hash__(self): return hash((self.x, self.y)) ... >>> d = {} >>> d[Pair2(4, 9)] = "lunchtime" >>> d {Pair2(4, 9): 'lunchtime'} >>> d[Pair2(4, 9)] Traceback (most recent call last): File "<stdin>", line 1, in ? KeyError: Pair2(4, 9) ###### The reason hashing breaks here depends strongly on what hashing really is doing. We can talk about this more if you'd like. In general, if we have two objects, and if they are equal to each other, they should also "hash" to the same values. Otherwise, they're fairly useless as dictionary keys. (But of course, if we never intend to use an object as a key, then we probably don't need to care about __hash__(). *grin*) I know I'm rushing this, so please feel free to ask more questions about this. From singingxduck at gmail.com Mon Mar 28 23:06:37 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Mon Mar 28 23:06:40 2005 Subject: [Tutor] hash()ing a list In-Reply-To: <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> References: <3449428f05032715127f2d4c52@mail.gmail.com> <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> Message-ID: <3449428f05032813061eca1f6c@mail.gmail.com> Well, what I ended up doing is making it so that Nodes are equal if they have the same 'cargo', but hash based on memory address. If this wasn't the case, I either wouldn't be able to have multiple Nodes with the same 'cargo' in a LinkedList, or I wouldn't be able to sort them properly, among other things. Even as is, however, its not a big deal, because in order to access a value with a Node whose 'cargo' is the same as the key, I only have to do a bit of maneuvering, while if I want to make sure I have the right Node in self.__get__(self, index=0), it takes no manuevering at all: Python 2.4.1c2 (#64, Mar 17 2005, 11:11:23) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.1 >>> a = LinkedList(range(10)) >>> a.appendlist(range(9,-1,-1)) True >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> a[-2] <__main__.Node instance at 0x00C5E580> >>> print _ 1 >>> a.lltopl[_] 1 >>> [a.lltopl.keys()[i] for i in range(len(a.lltopl)) if a.lltopl.keys()[i] == Node(1)] [<__main__.Node instance at 0x00C5E580>, <__main__.Node instance at 0x00C5A558>] >>> for i in _: print i 1 1 The reason this makes a difference is because, if Nodes are hashed based on memory location and are *not* equal based on cargo, it becomes impossible to sort with a cmp parameter because I'd already be sorting based on cargo: def sort(self, key=None, reverse=False): """LL.sort() -- stable sort *IN PLACE*""" unsort = self.lltopl.keys()[:] unsort.sort(lambda x, y: cmp(x.cargo, y.cargo), key, reverse) self.head = unsort[0] self.head.prev = None self.tail = unsort[-1] self.tail.next = None nod = self.head i = 1 while i < len(unsort): nod.next = unsort[i] nod = nod.next i += 1 nod = self.tail i = len(unsort)-2 while i >= 0: nod.prev = unsort[i] nod = nod.prev i -= 1 self.pylist.sort(key=key, reverse=reverse) return self.pylist Otherwise, the *sorting* becomes memory address-based. I guess what it comes down to is that for me, it's more intuitive to sort based on cargo and still allow multiple "equal" Nodes in a dictionary than to sort based on cargo and disallow multiple "equal" Nodes, and more so than to sort based on memory address and allow multiple "equal" Nodes in a dictionary. This method gives me the most intuitivity with no loss, from what I can see. In any case, I will soon be posting the entire code (via rafb.net/paste) for suggestions/comments. Thanks, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Tue Mar 29 00:36:39 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Mar 29 00:36:43 2005 Subject: [Tutor] A Pythonic LinkedList Implementation Message-ID: <3449428f0503281436562f388@mail.gmail.com> Hello all, I've been working on making a complete pythonic LinkedList implementation, as per the specifications of Java's LinkedList and Python's list. The full code may be found at http://rafb.net/paste/results/JKhsQn59.html. Once the link expires, please feel free to email me for the code. Any suggestions and comments are welcome. As far as I can tell, the only possible improvement to be made is adding comments. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From jeffshannon at gmail.com Tue Mar 29 01:15:37 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Tue Mar 29 01:26:19 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> Message-ID: <5d0204a1050328151539a99f5e@mail.gmail.com> On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <orbitz@drorbitz.ath.cx> wrote: > Floats are inherintly inprecise. So if thigns arn't working like you > expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same > number than you think. However, the imprecision of floats is in the 10-12 precision digit range. That is, it's precise up to about 0.0000000001 (or slightly fewer decimal places if the integer part is large). Given the precision with which those constants are specified, I doubt that float imprecision will be an issue here, unless there's a *lot* of repeated operations, e.g. a loop with many (i.e. hundreds to thousands of) iterations. Jeff Shannon From python.programming at gmail.com Tue Mar 29 01:26:31 2005 From: python.programming at gmail.com (Kevin) Date: Tue Mar 29 01:26:35 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <424855C9.3080205@tds.net> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> <d082fff80503281056136e8a6d@mail.gmail.com> <424855C9.3080205@tds.net> Message-ID: <d082fff8050328152678f2a369@mail.gmail.com> Here is the entire error message: Traceback (most recent call last): File "C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\mmaker.py", line 55, in ? server.checkConnections(0.1) File "C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py", line 73, in checkConnections self.closeConnection((self, f)) File "C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py", line 49, in closeConnection self.removeConnection((self, conn)) File "C:\Documents and Settings\Kevin\Desktop\New Folder\mudmaker\sServer.py", line 42, in removeConnection self._descriptors.remove(conn._fd) AttributeError: 'tuple' object has no attribute '_fd' On Mon, 28 Mar 2005 14:06:49 -0500, Kent Johnson <kent37@tds.net> wrote: > Kevin wrote: > > Nope it will still give the same Attribute error. > > Please post the entire error including the stack trace and the whole error message. Copy and paste > the whole thing, don't transcribe it. > > Kent > > > > > > > On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson <kent37@tds.net> wrote: > > > >>Kevin wrote: > >> > >>>Hi, > >>> > >>>I fond this game on the internet I was able to fix most of the errors > >>>that it was giving and it will > >>>now start up ok. However when you try to enter a name to login to the > >>>game it will crash and > >>>give this: > >>> > >>>in sServer.py > >>>line 42, in removeConnection > >>> self._descriptors.remove(conn._fd) > >>>AttributeError: 'tuple' object has no attribute '_fd' > >>> > >>>How would I go about fixing this. > >> > >>This error is because the caller is passing the wrong kind of argument to removeConnection. It seems > >>to expect a connection object but it is getting a tuple instead. > >> > >>My guess is the error is the line > >> self.closeConnection((self, f)) > >>in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be > >> self.closeConnection(self._connections[f]) ?? > >> > >> > >>>I have uploaded to entire game to http://lotheria.com/mudmaker.zp if > >>>anyone would care to > >>>take a look at it. > >> > >>That should be http://lotheria.com/mudmaker.zip > >> > >>Kent > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From flaxeater at yahoo.com Tue Mar 29 01:50:15 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Mar 29 01:50:19 2005 Subject: [Tutor] A Pythonic LinkedList Implementation Message-ID: <20050328235016.44893.qmail@web54302.mail.yahoo.com> I'm at a loss as to why this is helpful. How and why would one use this instead of a regular list? I know what linked lists are and why they would be useful in C++ or C or any other but not python. Orri Ganel wrote: >Hello all, > > > >I've been working on making a complete pythonic LinkedList > >implementation, as per the specifications of Java's LinkedList and > >Python's list. The full code may be found at > >http://rafb.net/paste/results/JKhsQn59.html. Once the link expires, > >please feel free to email me for the code. Any suggestions and > >comments are welcome. As far as I can tell, the only possible > >improvement to be made is adding comments. > > > >Thanks in advance, > >Orri > > > > > __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From michael.hall at critterpixstudios.com Tue Mar 29 02:06:15 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Tue Mar 29 02:06:10 2005 Subject: [Tutor] Launching a file browser Message-ID: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> I looked over the global module index and the closest thing I could find relating to my os (osx) was EasyDialogs, which has a few functions pertaining to this, "AskFileForOpen()" being one. Calling any function within EasyDialogs however yields an Apple Event error: AE.AEInteractWithUser(50000000) MacOS.Error: (-1713, 'no user interaction is allowed') I get the impression some of these "Mac" modules are more relevant to os 9 than 10(which is Unix), so maybe EasyDialogs is not the right choice here. Any suggestions are appreciated. -MH -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 596 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050328/10362d23/attachment.bin From jfouhy at paradise.net.nz Tue Mar 29 02:24:32 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 29 02:24:35 2005 Subject: [Tutor] Launching a file browser In-Reply-To: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> Message-ID: <1112055872.4248a0408ea5c@www.paradise.net.nz> Quoting Mike Hall <michael.hall@critterpixstudios.com>: > I get the impression some of these "Mac" modules are more relevant to > os 9 than 10(which is Unix), so maybe EasyDialogs is not the right > choice here. Any suggestions are appreciated. So, you are writing a GUI app and you want some kind of open file dialog? Won't this depend on what toolkit you are using for your GUI? If you are using Tkinter (which should work on OS X, I think), try: >>> import tkFileDialog >>> f = tkFileDialog.askopenfilename() Check dir(tkFileDialog) for other functions. But other GUI toolkits will have their own functions. -- John. From garnaez at gmail.com Tue Mar 29 02:36:15 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Tue Mar 29 02:36:48 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> Message-ID: <148eea7105032816364fb39d44@mail.gmail.com> On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <orbitz@drorbitz.ath.cx> wrote: > Floats are inherintly inprecise. So if thigns arn't working like you > expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same > number than you think. Are you telling me that I cant expect 2 digit preceision? From garnaez at gmail.com Tue Mar 29 02:36:15 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Tue Mar 29 02:45:54 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> Message-ID: <148eea7105032816364fb39d44@mail.gmail.com> On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <orbitz@drorbitz.ath.cx> wrote: > Floats are inherintly inprecise. So if thigns arn't working like you > expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same > number than you think. Are you telling me that I cant expect 2 digit preceision? From shaleh at speakeasy.net Tue Mar 29 02:46:15 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 29 02:48:28 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <148eea7105032816364fb39d44@mail.gmail.com> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> <148eea7105032816364fb39d44@mail.gmail.com> Message-ID: <4248A557.7020702@speakeasy.net> gerardo arnaez wrote: > On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <orbitz@drorbitz.ath.cx> wrote: > >>Floats are inherintly inprecise. So if thigns arn't working like you >>expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same >>number than you think. > > > Are you telling me that I cant expect 2 digit preceision? Not without using round. Have *NO* faith in floating points. This is especially true when you are creating the decimals via division and the like. From singingxduck at gmail.com Tue Mar 29 02:48:44 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Mar 29 02:48:49 2005 Subject: [Tutor] A Pythonic LinkedList Implementation In-Reply-To: <20050328235016.44893.qmail@web54302.mail.yahoo.com> References: <20050328235016.44893.qmail@web54302.mail.yahoo.com> Message-ID: <3449428f050328164867e72543@mail.gmail.com> I'm not at all sure this is, indeed, helpful *grin*. I was just looking for a project to code, and decided to implement a LinkedList. The how of using it is very simple: in the same way you would use a regular list. Except for a few extra/different methods, the use of LinkedList is very similar to that of regular lists. As to the why, like I said, I don't know that this will actually serve a purpose, it's a project I wrote just to write something. If it actually ends up being useful, too, that'd be great, but it wasn't my main objective. HTH, Orri On Mon, 28 Mar 2005 15:50:15 -0800 (PST), Chad Crabtree <flaxeater@yahoo.com> wrote: > I'm at a loss as to why this is helpful. How and why would one use > this > instead of a regular list? I know what linked lists are and why they > > would be useful in C++ or C or any other but not python. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From kent37 at tds.net Tue Mar 29 03:21:59 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 29 03:22:04 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <4248A557.7020702@speakeasy.net> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> <148eea7105032816364fb39d44@mail.gmail.com> <4248A557.7020702@speakeasy.net> Message-ID: <4248ADB7.2040805@tds.net> Sean Perry wrote: > gerardo arnaez wrote: > >> On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <orbitz@drorbitz.ath.cx> >> wrote: >> >>> Floats are inherintly inprecise. So if thigns arn't working like you >>> expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same >>> number than you think. >> >> >> >> Are you telling me that I cant expect 2 digit preceision? > > > Not without using round. Have *NO* faith in floating points. This is > especially true when you are creating the decimals via division and the > like. What?!?! OK, floats don't necessarily have the exact values you expect (they may have errors after many decimal places), and comparing floats for equality is risky business (you should compare for close, not equal). But the errors are well past the two-digit place. See the FAQ for more info on one kind of error: http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate Note that the original poster was looking at ranges, not looking for exact matches! Can you be more specific about what kinds of problems you have had? Kent From kent37 at tds.net Tue Mar 29 03:25:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 29 03:25:45 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <d082fff8050328152678f2a369@mail.gmail.com> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> <d082fff80503281056136e8a6d@mail.gmail.com> <424855C9.3080205@tds.net> <d082fff8050328152678f2a369@mail.gmail.com> Message-ID: <4248AE92.70504@tds.net> Kevin wrote: > Here is the entire error message: > > Traceback (most recent call last): > File "C:\Documents and Settings\Kevin\Desktop\New > Folder\mudmaker\mmaker.py", line 55, in ? > server.checkConnections(0.1) > File "C:\Documents and Settings\Kevin\Desktop\New > Folder\mudmaker\sServer.py", line 73, in checkConnections > self.closeConnection((self, f)) The line above is exactly the line I suggested you change (see below). It doesn't look like you did. Did you understand my suggestion? Are you able to change the file? Kent > File "C:\Documents and Settings\Kevin\Desktop\New > Folder\mudmaker\sServer.py", line 49, in closeConnection > self.removeConnection((self, conn)) > File "C:\Documents and Settings\Kevin\Desktop\New > Folder\mudmaker\sServer.py", line 42, in removeConnection > self._descriptors.remove(conn._fd) > AttributeError: 'tuple' object has no attribute '_fd' > > > On Mon, 28 Mar 2005 14:06:49 -0500, Kent Johnson <kent37@tds.net> wrote: > >>Kevin wrote: >> >>>Nope it will still give the same Attribute error. >> >>Please post the entire error including the stack trace and the whole error message. Copy and paste >>the whole thing, don't transcribe it. >> >>Kent >> >> >>> >>>On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson <kent37@tds.net> wrote: >>> >>> >>>>Kevin wrote: >>>> >>>> >>>>>Hi, >>>>> >>>>>I fond this game on the internet I was able to fix most of the errors >>>>>that it was giving and it will >>>>>now start up ok. However when you try to enter a name to login to the >>>>>game it will crash and >>>>>give this: >>>>> >>>>>in sServer.py >>>>>line 42, in removeConnection >>>>> self._descriptors.remove(conn._fd) >>>>>AttributeError: 'tuple' object has no attribute '_fd' >>>>> >>>>>How would I go about fixing this. >>>> >>>>This error is because the caller is passing the wrong kind of argument to removeConnection. It seems >>>>to expect a connection object but it is getting a tuple instead. >>>> >>>>My guess is the error is the line >>>> self.closeConnection((self, f)) >>>>in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be >>>> self.closeConnection(self._connections[f]) ?? >>>> >>>> >>>> >>>>>I have uploaded to entire game to http://lotheria.com/mudmaker.zp if >>>>>anyone would care to >>>>>take a look at it. >>>> >>>>That should be http://lotheria.com/mudmaker.zip >>>> >>>>Kent >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > From pierre.barbier at cirad.fr Tue Mar 29 03:58:30 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue Mar 29 03:57:20 2005 Subject: [Tutor] A Pythonic LinkedList Implementation In-Reply-To: <3449428f050328164867e72543@mail.gmail.com> References: <20050328235016.44893.qmail@web54302.mail.yahoo.com> <3449428f050328164867e72543@mail.gmail.com> Message-ID: <4248B646.8020505@cirad.fr> Well, my opinion about your code : At first, it seems far too complex for what it is ! First, there is a whole lot of useless tests ! For example : if node is not None and type(node) == list The "node is not None" is useless, because the type of None is ... NoneType so type(node) == list is enough to ensure what you want. And you have a lot of tests like that. Then, you code is still buggy ! Just try : l = LinkedList([1,2,3]) l < 4 l == 4 with code like : def __eq__(self, y): if [...] try: [...] except: return self == y that's jsut natural ... remember that "self == y" will just call ... self.__eq__ ! Thus you get an infinite loop !!! Another thing is your indentation. Please, always use the same indentation level everywhere ! Don't just align code that are not at the same level ... that reduces the readability of your code. I think the worst part was some code like : if foo: line of code line of code line of code line of code line of code line of code line of code line of code else: line of code another line of code ... in your __init__ method. Please, never do that again ! I almost missed the "else" ! At last, if you use linked list why embed a python list in it ??????? I can think of applications for a linked list, but if you embed a real list, what is the use of your links ???? I can't think of a single application in any language that would make use of your "linked list" ... you lost the O(1) insertion time for example. I don't know about java LinkedList but I doubt it's like that ! Well, the fact your code is useless is not very important, but please, first, try to express what data structure you want and its properties. Then, write your tests, and don't forget important ones !!! (Like l > 4) Remember Python has no type checking, so you have to test with strange types too ! And follow the coding rules for python : http://www.python.org/doc/essays/styleguide.html Please, try again, and be carefull with your coding style when you post your code ;) Pierre Orri Ganel a ?crit : > I'm not at all sure this is, indeed, helpful *grin*. I was just > looking for a project to code, and decided to implement a LinkedList. > The how of using it is very simple: in the same way you would use a > regular list. Except for a few extra/different methods, the use of > LinkedList is very similar to that of regular lists. As to the why, > like I said, I don't know that this will actually serve a purpose, > it's a project I wrote just to write something. If it actually ends > up being useful, too, that'd be great, but it wasn't my main > objective. > > HTH, > Orri > > On Mon, 28 Mar 2005 15:50:15 -0800 (PST), Chad Crabtree > <flaxeater@yahoo.com> wrote: > >>I'm at a loss as to why this is helpful. How and why would one use >>this >>instead of a regular list? I know what linked lists are and why they >> >>would be useful in C++ or C or any other but not python. > > > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From michael.hall at critterpixstudios.com Tue Mar 29 04:53:39 2005 From: michael.hall at critterpixstudios.com (Mike Hall) Date: Tue Mar 29 04:53:34 2005 Subject: [Tutor] Launching a file browser In-Reply-To: <1112055872.4248a0408ea5c@www.paradise.net.nz> References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> <1112055872.4248a0408ea5c@www.paradise.net.nz> Message-ID: <4b685d8f6b18e7823cf46d0ba8d8908b@critterpixstudios.com> On Mar 28, 2005, at 4:24 PM, jfouhy@paradise.net.nz wrote: > So, you are writing a GUI app and you want some kind of open file > dialog? Won't > this depend on what toolkit you are using for your GUI? > > If you are using Tkinter (which should work on OS X, I think), try: > >>>> import tkFileDialog >>>> f = tkFileDialog.askopenfilename() > > Check dir(tkFileDialog) for other functions. > > But other GUI toolkits will have their own functions. I my case the gui will be comprised of html and javascript, talking to python through system calls. I basically want to know if there's an equivalent of the "webbrowser()" module (which launches my browser) for file dialogs. This is what EasyDialogs should do, but does not. -MH From keridee at jayco.net Tue Mar 29 05:13:10 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Mar 29 05:12:45 2005 Subject: [Tutor] Float precision untrustworthy~~~ Message-ID: <000901c5340d$52bd6410$da5428cf@JSLAPTOP> I've already deleted the recent thread-- But sometimes I agree with he who said that you can't trust floats at all. The scientific theory suggests that if an output is not what it should be, then the hypothesis is untrue. In this case, the hypothesis is the fact that float division should always produce the same output as our decimal division used in common schools today. Since that is not always true, then floats are not trustworthy~~~ frankly, the mere fact that floats are difficult to check with equality has bitten me more than anything I've met yet in python. For example -- Unfortunatley, I can't give you the full setup due to I have forgotten it. But it dealt with a taking a float to a float power -- Ah, Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 64.0**(1/3.0) == 4 False >>> 64**(1.0/3) == 4 False >>> from __future__ import division >>> 64**(1/3) == 4 False >>> 64**-3 == 4 False >>> a = 1/3 >>> a 0.33333333333333331 >>> 64**a == 4 False >>> b = float(64) >>> b 64.0 >>> b**a 3.9999999999999996 >>> round(b**a,9) == 4 True >>> round(7/2) == 4 True >>> round(7/2) == 3.5 False >>> Well, somehow, working it out part by part, splitting each float into a variable, I managed to get it to come out true without rounding. (Again, I'm sorry that I don't have that which works...) The last three checks also show that you need to define the places argument to get a good answer. Why not just implement decimal or some equivalent and get rid of hidden, hard to debug headaches? I understand uses of floats where the precision isn't exact anyway -- i.e. sqrt(2) Oh, by the way, just because today I fight against floats, tomorrow I might fight for them. I just like pointing things out. ;-) Jacob From python.programming at gmail.com Tue Mar 29 06:11:17 2005 From: python.programming at gmail.com (Kevin) Date: Tue Mar 29 06:11:20 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <4248AE92.70504@tds.net> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> <d082fff80503281056136e8a6d@mail.gmail.com> <424855C9.3080205@tds.net> <d082fff8050328152678f2a369@mail.gmail.com> <4248AE92.70504@tds.net> Message-ID: <d082fff80503282011607e9d89@mail.gmail.com> Well I just noticed somthing about the entire sServer.py file. All the code under each def is not indented, after I fixed all the indentation I got a host of other errors when I try to log in. I posted the files on my site if you want to take a look at it. There are to many problems with it right now. I only wanted to look at how it ran under a linux box and windows to see how a mud server would run. Thanks for the help Kevin On Mon, 28 Mar 2005 20:25:38 -0500, Kent Johnson <kent37@tds.net> wrote: > Kevin wrote: > > Here is the entire error message: > > > > Traceback (most recent call last): > > File "C:\Documents and Settings\Kevin\Desktop\New > > Folder\mudmaker\mmaker.py", line 55, in ? > > server.checkConnections(0.1) > > File "C:\Documents and Settings\Kevin\Desktop\New > > Folder\mudmaker\sServer.py", line 73, in checkConnections > > self.closeConnection((self, f)) > > The line above is exactly the line I suggested you change (see below). It doesn't look like you did. > Did you understand my suggestion? Are you able to change the file? > > Kent > > > File "C:\Documents and Settings\Kevin\Desktop\New > > Folder\mudmaker\sServer.py", line 49, in closeConnection > > self.removeConnection((self, conn)) > > File "C:\Documents and Settings\Kevin\Desktop\New > > Folder\mudmaker\sServer.py", line 42, in removeConnection > > self._descriptors.remove(conn._fd) > > AttributeError: 'tuple' object has no attribute '_fd' > > > > > > On Mon, 28 Mar 2005 14:06:49 -0500, Kent Johnson <kent37@tds.net> wrote: > > > >>Kevin wrote: > >> > >>>Nope it will still give the same Attribute error. > >> > >>Please post the entire error including the stack trace and the whole error message. Copy and paste > >>the whole thing, don't transcribe it. > >> > >>Kent > >> > >> > >>> > >>>On Mon, 28 Mar 2005 13:50:07 -0500, Kent Johnson <kent37@tds.net> wrote: > >>> > >>> > >>>>Kevin wrote: > >>>> > >>>> > >>>>>Hi, > >>>>> > >>>>>I fond this game on the internet I was able to fix most of the errors > >>>>>that it was giving and it will > >>>>>now start up ok. However when you try to enter a name to login to the > >>>>>game it will crash and > >>>>>give this: > >>>>> > >>>>>in sServer.py > >>>>>line 42, in removeConnection > >>>>> self._descriptors.remove(conn._fd) > >>>>>AttributeError: 'tuple' object has no attribute '_fd' > >>>>> > >>>>>How would I go about fixing this. > >>>> > >>>>This error is because the caller is passing the wrong kind of argument to removeConnection. It seems > >>>>to expect a connection object but it is getting a tuple instead. > >>>> > >>>>My guess is the error is the line > >>>> self.closeConnection((self, f)) > >>>>in checkConnections(). The argument is (self, f) which is a tuple. Maybe it should be > >>>> self.closeConnection(self._connections[f]) ?? > >>>> > >>>> > >>>> > >>>>>I have uploaded to entire game to http://lotheria.com/mudmaker.zp if > >>>>>anyone would care to > >>>>>take a look at it. > >>>> > >>>>That should be http://lotheria.com/mudmaker.zip > >>>> > >>>>Kent > >>>> > >>>>_______________________________________________ > >>>>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 maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dianahawks at optusnet.com.au Tue Mar 29 08:08:23 2005 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Tue Mar 29 08:10:02 2005 Subject: [Tutor] commands with multiple things to do? Message-ID: <001801c53425$b9087260$c208a4cb@dianahawks> Dear list! Is it possible for me to make a command do multiple things instead of 1? For instance, I have a button that allows me to "submit" some user input (that is, show it in a window), but I also want it to count the number of times that submit button has been pressed. I have tried this code: self.submit_bttn = Button(self, text = "Tries: 0", command = self.reveal, self.update_count) but I get this error: *** non-keyword arg after keyword arg I have tried putting the code as 2 commands on separate lines, but it then will do just the 2nd command and not the first - it will either reveal what the user has typed, but not update, or will show the update but not reveal the user input! Any ideas appreciated! Thanks from newbie Diana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050329/ed6a1ec3/attachment.html From jfouhy at paradise.net.nz Tue Mar 29 08:16:42 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 29 08:16:46 2005 Subject: [Tutor] commands with multiple things to do? In-Reply-To: <001801c53425$b9087260$c208a4cb@dianahawks> References: <001801c53425$b9087260$c208a4cb@dianahawks> Message-ID: <1112077002.4248f2ca24d45@www.paradise.net.nz> Quoting Diana Hawksworth <dianahawks@optusnet.com.au>: > Is it possible for me to make a command do multiple things instead of > 1? Not directly ... But you can always write a function that does both things. > self.submit_bttn = Button(self, text = "Tries: 0", command = > self.reveal, self.update_count) eg: def callback(): self.reveal() self.update_count() self.submit_bttn = Button(self, text='Tries: 0', command=callback) In python, function definitions can be placed anywhere (including inside other functions). HTH. -- John. From bvande at po-box.mcgill.ca Tue Mar 29 08:38:29 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 29 08:38:58 2005 Subject: hash issues [WAS] Re: [Tutor] hash()ing a list In-Reply-To: <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> Message-ID: <4248F7E5.2000100@po-box.mcgill.ca> Danny Yoo said unto the world upon 2005-03-28 14:33: <Snip much useful discussion> > I know I'm rushing this, so please feel free to ask more questions about > this. Hi Danny, Orri, and all, I'm really glad Orri raised the hashing issues he did, and appreciate your informative posts, Danny. :-) There are some related things I've been wondering about, and, since hashing is under discussion, I hope no one minds if I throw my issues into the mix. First issue: *Almost* all ints are fixed points for the hashing function in the sense that hash(some_int) == some_int. Almost all as: >>> hash(-1) -2 Any idea why -1 is the sole exception? (Perhaps alternatively: why -1 is not a good value to use as a hash value?) I know it is the sole exception from having run both the following and its decrementing counterpart to check all the integers: counter = 0 while True: if hash(counter) != counter: print counter, type(counter) break counter += 1 (That took a while!) Second issue: I must misunderstand how dictionary lookups work: >>> a_long = 424242424242424 >>> long_hash = hash(a_long) >>> hash(long_hash) == long_hash True >>> some_dict = {a_long: 4242, long_hash: 42} >>> some_dict[a_long] 4242 >>> some_dict[long_hash] 42 >>> print 'Brian is confused' Brian is confused >>> I had thought lookup was by hash value, and thus expected the access to some_dict to cause troubles. Yet it worked. Is it that lookup is by hash value, and then equality if need be so as to settle ambiguity, or have I completely misunderstood the mechanism of dictionary lookup? Thanks and best to all, Brian vdB From jfouhy at paradise.net.nz Tue Mar 29 10:14:36 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Tue Mar 29 10:14:40 2005 Subject: hash issues [WAS] Re: [Tutor] hash()ing a list In-Reply-To: <4248F7E5.2000100@po-box.mcgill.ca> References: <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> <4248F7E5.2000100@po-box.mcgill.ca> Message-ID: <1112084076.42490e6c653b5@www.paradise.net.nz> Quoting Brian van den Broek <bvande@po-box.mcgill.ca>: > I had thought lookup was by hash value, and thus expected the access > to some_dict to cause troubles. Yet it worked. Is it that lookup is by > hash value, and then equality if need be so as to settle ambiguity, or > have I completely misunderstood the mechanism of dictionary lookup? Hash functions are rarely perfect (in terms of mapping every input to a different output) [1], so they have to deal with collisions. AFAIK, the hash table lookup algorithm basically works like this: def lookup(self, key): hits = self.internalDataStructure[key] for key_, value in hits: if key_ == key: return value raise KeyError, 'Key not found'. (except that it will be written in C and there may be advanced trickery involved to improve efficiency in other ways) HTH! [1] The pigeonhole principle [2] tells us that it is rarely possible to make perfect hash functions. For example, there are more possible strings than there are integers [3,4], so, in principle, you could find arbitrarily many strings all with the same hash value. In that case, a dictionary with them as keys would be O(n), not O(1). But a good hash function will make that very unlikely. [2] http://en.wikipedia.org/wiki/Pigeonhole_principle [3] Because every integer n has a corresponding string "n", but there are strings which do not (directly) correspond to an integer (eg, "foo"). [4] Unless we allow integers to go to infinity... But computers generally do not have infinite memory :-) From dyoo at hkn.eecs.berkeley.edu Tue Mar 29 10:18:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 29 10:19:00 2005 Subject: [Tutor] commands with multiple things to do? In-Reply-To: <001801c53425$b9087260$c208a4cb@dianahawks> Message-ID: <Pine.LNX.4.44.0503290003480.5537-100000@hkn.eecs.berkeley.edu> On Tue, 29 Mar 2005, Diana Hawksworth wrote: > Is it possible for me to make a command do multiple things instead of 1? > For instance, I have a button that allows me to "submit" some user input > (that is, show it in a window), but I also want it to count the number > of times that submit button has been pressed. > > I have tried this code: > > self.submit_bttn = Button(self, text = "Tries: 0", command = > self.reveal, self.update_count) Hi Diana, Yes. The easiest thing to do here is write an "internal function" definition. We already know how to define functions: ###### def square(x): return x * x def sqrt(x): return x**0.5 def hypotenuse(a, b): return sqrt(square(a) + square(b)) ###### Here, we're writing square and sqrt just as helpers to hypotenuse, to make hypotenuse read well as English. Anyway, a neat thing is that we can do this function definition pretty much anywhere, even within other functions: ###### def hypotenuse(a, b): def square(x): return x * x def sqrt(x): return x**0.5 return sqrt(square(a) + square(b)) ###### And now it's very clear that square() and sqrt() are intended for internal use by the hypotenuse function. They are "local" internal defintions. In the problem brought up above, we can write an internal definition: ###### # ... some earlier code, right before the call to the Button # construction def my_command(): self.reveal() self.update_count() ###### Once we have this function, we can then use it as the callback we pass to submit_bttn: ###### def my_command(): self.reveal() self.update_count() self.submit_bttn = Button(self, text = "Tries: 0", command = my_command) ###### This is a nice feature of Python. But if you're familiar with more static languages like C, this might look a little weird. *grin* If you can tell us what other programming languages you've had experience with, perhaps we can give you analogies in those languages. Please feel free to ask more questions on this. Best of wishes! From dyoo at hkn.eecs.berkeley.edu Tue Mar 29 10:37:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Mar 29 10:37:58 2005 Subject: hash issues [WAS] Re: [Tutor] hash()ing a list In-Reply-To: <4248F7E5.2000100@po-box.mcgill.ca> Message-ID: <Pine.LNX.4.44.0503290019120.5537-100000@hkn.eecs.berkeley.edu> > *Almost* all ints are fixed points for the hashing function in the > sense that hash(some_int) == some_int. Almost all as: > > >>> hash(-1) > -2 > > Any idea why -1 is the sole exception? [warning: beginners, skip this. Completely inconsequential CPython detail ahead.] Hi Brian, Yeah, I remember this from studying the Python C implementation. -1 is used internally in the CPython implementation to represent that the hash function failed in some bad way. It is a pure CPython implementation detail, and is completely not important. *grin* There's a really brief mention of this in 'Objects/object.c' in the comment: /******/ /* Set of hash utility functions to help maintaining the invariant that if a==b then hash(a)==hash(b) All the utility functions (_Py_Hash*()) return "-1" to signify an error. */ /******/ In terms of "essential" versus "accidental" properties, this is an "accidental" one that we shouldn't worry too much about. > I had thought lookup was by hash value, and thus expected the access to > some_dict to cause troubles. Yet it worked. Is it that lookup is by hash > value, and then equality if need be so as to settle ambiguity, Yes, exactly! That's why equality and hashing codes are tied together in this kind of "if a==b then hash(a)==hash(b)" contract: there's bound to be "collisions" in any hashing scheme. So we have to do something about collisions. Equality is meant to settle things when two keys have the same hash code. I just did a quick Google search to see if someone else has written about hash table theory, and trusty Wikipedia came up with a very nice article: http://en.wikipedia.org/wiki/Hash_table If you have more questions, please feel free to ask. Best of wishes to you! From shaleh at speakeasy.net Tue Mar 29 10:48:38 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 29 10:50:53 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <4248ADB7.2040805@tds.net> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> <148eea7105032816364fb39d44@mail.gmail.com> <4248A557.7020702@speakeasy.net> <4248ADB7.2040805@tds.net> Message-ID: <42491666.2000904@speakeasy.net> Kent Johnson wrote: >> Not without using round. Have *NO* faith in floating points. This is >> especially true when you are creating the decimals via division and >> the like. > > > What?!?! > > OK, floats don't necessarily have the exact values you expect (they may > have errors after many decimal places), and comparing floats for > equality is risky business (you should compare for close, not equal). > But the errors are well past the two-digit place. See the FAQ for more > info on one kind of error: > http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate > > > Note that the original poster was looking at ranges, not looking for > exact matches! > > Can you be more specific about what kinds of problems you have had? > sure, what is 2/3? 0.66? 0.67? From smichr at hotmail.com Tue Mar 29 11:11:52 2005 From: smichr at hotmail.com (C Smith) Date: Tue Mar 29 11:13:57 2005 Subject: [Tutor] Float precision untrustworthy~~~ In-Reply-To: <20050329041124.70F411E4013@bag.python.org> Message-ID: <BAY101-DAV13503214ABBA7EB77ADE04C1450@phx.gbl> On Monday, Mar 28, 2005, at 22:11 America/Chicago, tutor-request@python.org wrote: [cut] > the mere fact that floats are difficult to check with equality has > bitten me more than anything I've met yet in python. > [cut] I understand what you are talking about, but I tend toward just making it one of the things to remember when working with floats. (I've been bitten a lot when I forget to use '==' instead of '=', too!) As you say, the problems arise when you try to make comparisons. To get around the difficulties with comparisons, I wrote a helper function: ### Python 2.3 (#2, Jul 30 2003, 11:45:28) [GCC 3.1 20020420 (prerelease)] Type "copyright", "credits" or "license" for more information. MacPython IDE 1.0.1 >>> from math import floor, log10 >>> def Round(x, n=0, sigfigs=False): '''An enhanced rounder which rounds to the nth significant digit (the nth digit from the first non-zero digit, not the nth decimal place) if the parameter sigfigs is not zero. This uses "round-up" decisions when the digit following the one of interest is a 5, i.e. 1.35 and 1.45 Round to 1.4 and 1.5 when sigfigs = 2. ''' if x==0: return 0 if not sigfigs: return round(x,n) else: return round(x,n-1-int(floor(log10(abs(x))))) ### And here's a helper that uses it to check for equality of two numbers (floats, or otherwise) to whatever number of digits you desire --starting from the first non-zero digit, The default is for high precision. ### >>> def same(x,y,prec=9): """Return True if x and y are the same after being rounded to the same degree of precision.""" return Round(x,prec,1)==Round(y,prec,1) .. >>> print same(1.3,1.31,3) #at the 3rd digit these are different False >>> print same(1.3,1.31,2) #at the second digit they are (rounded to) the same digit number True >>> same(64.0**(1/3.0) ,4) #here's your example True ### You can be bitten by any comparison, not only tests for equality, too. ### >>> while 1: .. i+=.1 .. if i>2.1:break .. >>> print i 2.1 ### It doesn't look like the last value of i was really greater than 2.1--it's actually 2.1000000000000005 so the result is correct (though not what we expected). We don't have the problem with a step size of 0.7 in this case, though, because the value before 2.8 was 2.0999999999999996--just a little smaller than 2.1. Here, we specify the precision and get the desired result. ### >>> i=0 >>> while 1: .. i+=.1 .. if round(i,9)>round(2.1,9):break .. >>> print i 2.2 ### [cut] > The last three checks also show that you need to define the places > argument > to get a good answer. Why not just implement decimal or some > equivalent and > get rid of hidden, hard to debug headaches? I understand uses of > floats > where the precision isn't exact anyway -- i.e. sqrt(2) Wish granted in version 2.4 ;-) I don't have it on the mac, but there is a write-up at http://www.python.org/doc/2.4/whatsnew/node9.html The starting blurb says: "Python has always supported floating-point (FP) numbers, based on the underlying C double type, as a data type. However, while most programming languages provide a floating-point type, many people (even programmers) are unaware that floating-point numbers don't represent certain decimal fractions accurately. The new Decimal type can represent these fractions accurately, up to a user-specified precision limit. " /c From bvande at po-box.mcgill.ca Tue Mar 29 10:59:16 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 29 11:22:19 2005 Subject: hash issues [WAS] Re: [Tutor] hash()ing a list In-Reply-To: <1112084076.42490e6c653b5@www.paradise.net.nz> References: <Pine.LNX.4.44.0503281106580.19702-100000@hkn.eecs.berkeley.edu> <4248F7E5.2000100@po-box.mcgill.ca> <1112084076.42490e6c653b5@www.paradise.net.nz> Message-ID: <424918E4.4020606@po-box.mcgill.ca> jfouhy@paradise.net.nz said unto the world upon 2005-03-29 03:14: > Quoting Brian van den Broek <bvande@po-box.mcgill.ca>: > > >>I had thought lookup was by hash value, and thus expected the access >>to some_dict to cause troubles. Yet it worked. Is it that lookup is by >>hash value, and then equality if need be so as to settle ambiguity, or >>have I completely misunderstood the mechanism of dictionary lookup? > > > Hash functions are rarely perfect (in terms of mapping every input to a > different output) [1], so they have to deal with collisions. > > AFAIK, the hash table lookup algorithm basically works like this: > > def lookup(self, key): > hits = self.internalDataStructure[key] > for key_, value in hits: > if key_ == key: > return value > raise KeyError, 'Key not found'. > > (except that it will be written in C and there may be advanced trickery involved > to improve efficiency in other ways) > > HTH! Thanks. The code snip puts into code what I meant by asking if "lookup is by hash value, and then equality if need be so as to settle ambiguity", but the code is clearer than the prose ;-) > [1] The pigeonhole principle [2] tells us that it is rarely possible to make > perfect hash functions. For example, there are more possible strings than there > are integers [3,4], so, in principle, you could find arbitrarily many strings > all with the same hash value. In that case, a dictionary with them as keys > would be O(n), not O(1). But a good hash function will make that very unlikely. > [2] http://en.wikipedia.org/wiki/Pigeonhole_principle > [3] Because every integer n has a corresponding string "n", but there are > strings which do not (directly) correspond to an integer (eg, "foo"). > [4] Unless we allow integers to go to infinity... But computers generally do not > have infinite memory :-) I just about spat a beverage all over my keyboard when I read: > there are more possible strings than there are integers until I read the footnote and realized that you meant ints not integers (or, integer in the python sense, rather than in the mathematical sense). I got tempted to start droning on about why I wanted to spit, but there is a limit to how off topic one can go ;-) (For the curious or the insomniacs, due to some cool results in set-theory, if we had infinitely many integers in our computers, we could get a perfect hash function, not just for the strings or the integers, but for all recursively specifiable Python objects, in the same single hash function.) Thanks for the reply, Brian vdB From bvande at po-box.mcgill.ca Tue Mar 29 11:22:19 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 29 11:22:41 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <42491666.2000904@speakeasy.net> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> <148eea7105032816364fb39d44@mail.gmail.com> <4248A557.7020702@speakeasy.net> <4248ADB7.2040805@tds.net> <42491666.2000904@speakeasy.net> Message-ID: <42491E4B.8090303@po-box.mcgill.ca> Sean Perry said unto the world upon 2005-03-29 03:48: > Kent Johnson wrote: > >>> Not without using round. Have *NO* faith in floating points. This is >>> especially true when you are creating the decimals via division and >>> the like. >> >> >> >> What?!?! >> >> OK, floats don't necessarily have the exact values you expect (they >> may have errors after many decimal places), and comparing floats for >> equality is risky business (you should compare for close, not equal). >> But the errors are well past the two-digit place. See the FAQ for more >> info on one kind of error: >> http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate >> >> >> Note that the original poster was looking at ranges, not looking for >> exact matches! >> >> Can you be more specific about what kinds of problems you have had? >> > > sure, what is 2/3? 0.66? 0.67? >>> 2/3 0 >>> 2.0/3 0.66666666666666663 >>> From bvande at po-box.mcgill.ca Tue Mar 29 11:19:47 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Mar 29 11:22:44 2005 Subject: hash issues [WAS] Re: [Tutor] hash()ing a list In-Reply-To: <Pine.LNX.4.44.0503290019120.5537-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0503290019120.5537-100000@hkn.eecs.berkeley.edu> Message-ID: <42491DB3.8080609@po-box.mcgill.ca> Danny Yoo said unto the world upon 2005-03-29 03:37: >>*Almost* all ints are fixed points for the hashing function in the >>sense that hash(some_int) == some_int. Almost all as: >> >> >>> hash(-1) >>-2 >> >>Any idea why -1 is the sole exception? > > > [warning: beginners, skip this. Completely inconsequential CPython detail > ahead.] > > Hi Brian, > > Yeah, I remember this from studying the Python C implementation. -1 is > used internally in the CPython implementation to represent that the hash > function failed in some bad way. It is a pure CPython implementation > detail, and is completely not important. *grin* Thanks Danny, I did get that it wasn't important as clearly with finitely many ints available to be hash values, uniqueness of hash is out the window independently. But the oddity here did pique my curiosity. The explanation is obvious, once someone else thought of it for me :-) Thanks. <SNIP quote from C sources which sooner or later I am going to have to learn how to read :-) > > >>I had thought lookup was by hash value, and thus expected the access to >>some_dict to cause troubles. Yet it worked. Is it that lookup is by hash >>value, and then equality if need be so as to settle ambiguity, > > > Yes, exactly! That's why equality and hashing codes are tied together in > this kind of "if a==b then hash(a)==hash(b)" contract: there's bound to be > "collisions" in any hashing scheme. So we have to do something about > collisions. Equality is meant to settle things when two keys have the > same hash code. That's nicely put :-) > I just did a quick Google search to see if someone else has written about > hash table theory, and trusty Wikipedia came up with a very nice article: > > http://en.wikipedia.org/wiki/Hash_table Thanks for the link. Best to all, Brian vdB From smichr at hotmail.com Tue Mar 29 12:06:59 2005 From: smichr at hotmail.com (C Smith) Date: Tue Mar 29 12:08:01 2005 Subject: [Tutor] Re: If elif not working in comparison Message-ID: <BAY101-DAV7A867D4587F0DA2A3C996C1450@phx.gbl> > gerardo arnaez wrote: > >> On Mon, 28 Mar 2005 09:27:11 -0500, orbitz <orbitz at drorbitz.ath.cx> >> wrote: >> >>> Floats are inherintly inprecise. So if thigns arn't working like you >>> expect don't be surprised if 0.15, 0.12, and 0.1 are closer to the same >>> number than you think. >> >> >> >> Are you telling me that I cant expect 2 digit preceision? > > > Not without using round. Have *NO* faith in floating points. This is > especially true when you are creating the decimals via division and the > like. What makes one nervous when looking at your tests with floating point numbers is that calcuations that might lead up to one of the numbers in your test might actually be a tiny bit higher or a tiny bit lower than you expect. *However*, I think the thing to keep in mind is that if you are only a billionth or less away from the boundary, it really doesn't matter which way you go in terms of dosage--you are at the border. Here is an example of two calculations that you think should get you to 2.1. One is actually just shy of it and the other just a bit past: ### >>> 3*.7 2.0999999999999996 >>> 7*.3 2.1000000000000001 ### So if you have the following test to determine if it is time to increase someone's dose of medication and the results are based on some measurement being greater than 2.1, then... ### >>> def test(x): if x>2.1: print 'increase dose' else: print 'decrease dose' >>> ### if you test the above computed values, you will get different results: ### >>> dose1, dose2 = 3*.7, 7*.3 >>> test(dose1) decrease dose >>> test(dose2) decrease dose ### OR NOT! Why do they both come out to be the same even though one number is bigger than 2.1 and the other not? Because 2.1 is not actually '2.1': ### >>> 2.1 2.1000000000000001 ### The 7*.3 is actually "equal" to 2.1: they both are 2.1000000000000001. On the one hand, we want the boundaries so we can say, "if you are past this boundary you take the next sized dose"...but if you are so close to the boundary that you can just as well say that you are right on it, does it really matter which way you go? Other than bothering the deterministic nature, are there other reasons to be concerned? As far as economics, the '2,1' case will have people staying at a lower dose longer (as would 2.2, 2.6 and 2.7 which all are a tiny bit bigger than their mathematical values, just like 2.1). Just the opposite will happen at the 2.3, 2.4, 2.8, and 2.9 since these values are represented as numbers smaller than their mathematical counterparts: ### >>> 2.9 2.8999999999999999 ### If you have Python 2.4 you might want to check out the decimal type that is now part of the language. There is a description at http://www.python.org/doc/2.4/whatsnew/node9.html which starts with: "Python has always supported floating-point (FP) numbers, based on the underlying C double type, as a data type. However, while most programming languages provide a floating-point type, many people (even programmers) are unaware that floating-point numbers don't represent certain decimal fractions accurately. The new Decimal type can represent these fractions accurately, up to a user-specified precision limit. " And it gives the following example: Once you have Decimal instances, you can perform the usual mathematical operations on them. One limitation: exponentiation requires an integer exponent: >>> import decimal >>> a = decimal.Decimal('35.72') >>> b = decimal.Decimal('1.73') >>> a+b Decimal("37.45") >>> a-b Decimal("33.99") >>> a*b Decimal("61.7956") >>> a/b Decimal("20.64739884393063583815028902") Another suggestion is to use the Round replacement that I wrote about in response to the "Float precision untrustworthy~~~" thread. With it, you don't have to worry about how large or small your numbers are when you Round them (unlike with round()). You just decide on how many "parts per x" you are interested in with your numbers. e.g. if your calculations are only precise to about 1 part per hundred then you would round them to the 2nd (or maybe 3rd) digit and compare them. With the separation of code and data as already suggested this would look something like this: ### def Round(x, n=0, sigfigs=False): if x==0: return 0 if not sigfigs: return round(x,n) else: #round to nth digit counting from first non-zero digit # e.g. if n=3 and x = 0.002356 the result is 0.00236 return round(x,n-1-int(floor(log10(abs(x))))) ... for cutoff, value in cutoffs: if Round(x,3) < Round(cutoff,3): return value .. ### IMHO, I don't think that decimal is the way to go with such calculations since calculations performed with limited precision numbers shouldn't be treated as though they had infinite precision. From basic error analysis of the calculated values above, one shouldn't probably keep more than 3 digits in a/b result of Decimal("20.64739884393063583815028902"). On the other hand, perhaps one can keep all the digits until the end and then make the precision decision--this gives the best of both worlds. /c From smichr at hotmail.com Tue Mar 29 12:17:31 2005 From: smichr at hotmail.com (C Smith) Date: Tue Mar 29 12:20:21 2005 Subject: [Tutor] Math Question In-Reply-To: <20050322213451.E68D51E4011@bag.python.org> Message-ID: <BAY101-DAV104E114DD04806AEF2EC99C1450@phx.gbl> On Tuesday, Mar 22, 2005, at 15:34 America/Chicago, tutor-request@python.org wrote: > When I adjust coumadin doses I normal have to use whole or half pills > of the medicien the patient already has. > Fer Instance, if a pt takes 5mg of coumadin a day, that's 35mg of > coumadin week > and suppose I do a test that says thye are not taking enough coumadin > and to increase the dose by 10%, ie add another 3.5mg but have it > split evenly over the week or at least every other day. > normall, I would say ok > Take 5mg coumadine everty but on mon and thurs day take 7.5mg > (Note the patient only has 5mg tabs, which they can split to make dose > adjust my 2.5) > > My question is, > How would I solve this using math instead of geustimating it. > What kind of math am I talking about here? > I don't know that much about this medication (and I know you just said that the patient only has 5 mg pills) but on this page, http://www.heartpoint.com/coumadin.html I see that doses come in amounts like 1, 2, 2.5, 5, 7.5, and 10. With the ability to split pills, you can add 0.5, 1.25 and 3.75 to the list of possibilities. And then I wonder if the "math topic" expands from integer math, as has been suggested, to combinatorics which can tell you what combinations of pills and half pills that are at your disposal for making dosages. There are other factors, however, like keeping the prescription simple for patients. For example, let's say that the patient is not going to want to buy more than 2 pill sizes. This will give 4 different dosage amounts that one could play with. Let's say that the patient should never have to take more than 2 pills (or pill pieces) each day. The possible dosages that can be prescribed for a given day would be all the pair-wise combinations of the dosages. These could be obtained with 2 FOR loops: ### >>> dosages = [1, 2, 3] #just an example; different from above notes >>> possible = [] >>> for i,x in enumerate(dosages): .. for y in dosages[i:]: .. possible.append((x+y,[x,y])) .. >>> for pi in possible: .. print pi .. (2, [1, 1]) (3, [1, 2]) (4, [1, 3]) (4, [2, 2]) (5, [2, 3]) (6, [3, 3]) >>> ### Just a thought, /c From kent37 at tds.net Tue Mar 29 13:11:46 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 29 13:11:51 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <d082fff80503282011607e9d89@mail.gmail.com> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> <d082fff80503281056136e8a6d@mail.gmail.com> <424855C9.3080205@tds.net> <d082fff8050328152678f2a369@mail.gmail.com> <4248AE92.70504@tds.net> <d082fff80503282011607e9d89@mail.gmail.com> Message-ID: <424937F2.8010309@tds.net> Kevin wrote: > Well I just noticed somthing about the entire sServer.py file. All the > code under each def is not indented sServer.py mixes tabs and spaces for indentation. If you view it in an editor that indents 8 spaces for a tab it is fine. You might be interested in the reindent.py and untabify.py scripts in the Python/Tools/Scripts directory. Kent From kent37 at tds.net Tue Mar 29 13:16:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 29 13:16:34 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <42491E4B.8090303@po-box.mcgill.ca> References: <148eea7105032723117df16132@mail.gmail.com> <4247EB4B.3090403@tds.net> <91441f74eb6f35f1b4dd52870e5774be@drorbitz.ath.cx> <148eea7105032816364fb39d44@mail.gmail.com> <4248A557.7020702@speakeasy.net> <4248ADB7.2040805@tds.net> <42491666.2000904@speakeasy.net> <42491E4B.8090303@po-box.mcgill.ca> Message-ID: <4249390D.7060501@tds.net> Brian van den Broek wrote: > Sean Perry said unto the world upon 2005-03-29 03:48: > >> Kent Johnson wrote: >> >>>> Not without using round. Have *NO* faith in floating points. This is >>>> especially true when you are creating the decimals via division and >>>> the like. >>> >>> Can you be more specific about what kinds of problems you have had? >>> >> >> sure, what is 2/3? 0.66? 0.67? > > > >>> 2/3 > 0 > >>> 2.0/3 > 0.66666666666666663 or even: Python 2.4.1c2 (#64, Mar 17 2005, 11:11:23) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2/3 0 >>> from __future__ import division >>> 2/3 0.66666666666666663 >>> 2//3 0 There are definitely some gotchas you should be aware of when using floats. They are well-understood and fairly simple to work around. You have to understand the limitations. But to avoid floats entirely seems a bit extreme to me. Kent From billk at fastmail.fm Tue Mar 29 14:00:58 2005 From: billk at fastmail.fm (Bill Kranec) Date: Tue Mar 29 14:01:11 2005 Subject: [Tutor] HTML form post to Python script, without server Message-ID: <Pine.WNT.4.62.0503290642350.2944@Desktop> Hello, This might be slightly OT, but I hope I can get a few pointers. Is it possible to have an HTML form pass values to a Python script on a local computer, and execute that script? (I'm running Win XP, if that matters.) I would like to set up such a form to do some data entry. I understand that a GUI is probably a better way to do what I want, but thought this way might be quicker. Is this as simple as having the form action point to my script, and using the input names as my variables? Or am I not thinking about this right? Thanks for any help, Bill From kent37 at tds.net Tue Mar 29 14:17:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 29 14:17:33 2005 Subject: [Tutor] HTML form post to Python script, without server In-Reply-To: <Pine.WNT.4.62.0503290642350.2944@Desktop> References: <Pine.WNT.4.62.0503290642350.2944@Desktop> Message-ID: <42494758.4090707@tds.net> Bill Kranec wrote: > Hello, > > This might be slightly OT, but I hope I can get a few pointers. Is it > possible to have an HTML form pass values to a Python script on a local > computer, and execute that script? (I'm running Win XP, if that matters.) You have to have a server process running. It can be on your local computer, you don't need a separate server machine. Running a web server with CGI support on your PC is as simple as - open a DOS shell - cd to a directory containing a cgi-bin directory - python -c "import CGIHTTPServer; CGIHTTPServer.test()" Now of course you have to write a CGI script to handle the data. See the docs for the cgi module and the guides listed here for help: http://www.python.org/topics/web/ Important note! There is a bug (gasp!) in the os module in Python 2.4 that breaks CGIHTTPServer; if you want to do this with Python 2.4 you should download the 2.4.1c2 release. > I would like to set up such a form to do some data entry. I understand > that a GUI is probably a better way to do what I want, but thought this > way might be quicker. If you are comfortable with HTML and CGI then this could be faster. Though I don't think you have to know much about Tkinter to put up a simple data entry screen. > Is this as simple as having the form action point to my script, and > using the input names as my variables? Or am I not thinking about this > right? No, not quite that simple. You need the server to find the script and run it. Kent From snoylr at cheqnet.net Tue Mar 29 14:57:42 2005 From: snoylr at cheqnet.net (Richard Lyons) Date: Tue Mar 29 14:57:22 2005 Subject: [Tutor] A Newbie Printing Question Message-ID: <424950C6.1020909@cheqnet.net> I have little experience with programming. I have Python installed on a Windows XP system. What code do I need to use to send output from a Python script to a local printer attached to my workstation? to a network printer? Any help would be appreciated. From python.programming at gmail.com Tue Mar 29 17:01:24 2005 From: python.programming at gmail.com (Kevin) Date: Tue Mar 29 17:01:28 2005 Subject: [Tutor] An attribute error problem In-Reply-To: <424937F2.8010309@tds.net> References: <d082fff805032810351f6f7be5@mail.gmail.com> <424851DF.1050206@tds.net> <d082fff80503281056136e8a6d@mail.gmail.com> <424855C9.3080205@tds.net> <d082fff8050328152678f2a369@mail.gmail.com> <4248AE92.70504@tds.net> <d082fff80503282011607e9d89@mail.gmail.com> <424937F2.8010309@tds.net> Message-ID: <d082fff80503290701484fce5e@mail.gmail.com> Well I think I am going to learn how to create small little server the will just send and recive a message from a client. I just want to know is it easier to use twistedmatrix or just plain socket to create servers? Thanks Kevin On Tue, 29 Mar 2005 06:11:46 -0500, Kent Johnson <kent37@tds.net> wrote: > Kevin wrote: > > Well I just noticed somthing about the entire sServer.py file. All the > > code under each def is not indented > > sServer.py mixes tabs and spaces for indentation. If you view it in an editor that indents 8 spaces > for a tab it is fine. > > You might be interested in the reindent.py and untabify.py scripts in the Python/Tools/Scripts > directory. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jsmith at medplus.com Tue Mar 29 17:32:50 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Mar 29 17:32:55 2005 Subject: [Tutor] If elif not working in comparison Message-ID: <C4C644CF4ADA9448904C3E8BACC4B97C031C3CEE@medexch1.medplus.com> Brian van den Broek wrote: > Sean Perry said unto the world upon 2005-03-29 03:48: > >> Kent Johnson wrote: >> >>>> Not without using round. Have *NO* faith in floating points. This >>>> is >>>> especially true when you are creating the decimals via division and >>>> the like. >>> >>> Can you be more specific about what kinds of problems you have had? >>> >> >> sure, what is 2/3? 0.66? 0.67? > > > >>> 2/3 > 0 > >>> 2.0/3 > 0.66666666666666663 I don't know what you are getting at here. The first result is deterministic because it's integer divison and has nothing to do with any imprecision in floating points. Moreover, the original poster was asking about using two-decimal places for testing which is completely deterministic in this case as well >>> 2.0/3 < .66 False >>> 2.0/3 < .67 True >>> Which is just what you'd expect. It's absolutey absurd to tell someone to have *NO* faith in floating numbers. It's like anything else in programming: you have to understand what you are doing. Jeff From shaleh at speakeasy.net Tue Mar 29 19:05:52 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Tue Mar 29 19:08:07 2005 Subject: [Tutor] If elif not working in comparison In-Reply-To: <C4C644CF4ADA9448904C3E8BACC4B97C031C3CEE@medexch1.medplus.com> References: <C4C644CF4ADA9448904C3E8BACC4B97C031C3CEE@medexch1.medplus.com> Message-ID: <42498AF0.9060101@speakeasy.net> Smith, Jeff wrote: > > Which is just what you'd expect. > > It's absolutey absurd to tell someone to have *NO* faith in floating > numbers. It's like anything else in programming: you have to understand > what you are doing. > Unless a float that has been through a round function I do not trus it. That is what I mean by no faith. From alan.gauld at freenet.co.uk Tue Mar 29 19:27:06 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 29 19:26:36 2005 Subject: [Tutor] commands with multiple things to do? References: <001801c53425$b9087260$c208a4cb@dianahawks> Message-ID: <006101c53484$88614290$61cb8751@xp> > Is it possible for me to make a command do multiple things instead of 1? Yes, its called writing a function or method. > self.submit_bttn = Button(self, text = "Tries: 0", command = self.reveal, self.update_count) > I have tried putting the code as 2 commands on separate lines, Try putting the call to self_update inside self.reveal. Or if reveal gets called elsewhere as well then define a new method called say, self.revealAndUpdate that calls both. Alan G. From alan.gauld at freenet.co.uk Tue Mar 29 19:37:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Mar 29 19:36:59 2005 Subject: [Tutor] A Newbie Printing Question References: <424950C6.1020909@cheqnet.net> Message-ID: <008001c53485$eeb521f0$61cb8751@xp> > I have little experience with programming. I have Python installed on a > Windows XP system. What code do I need to use to send output from a > Python script to a local printer attached to my workstation? to a > network printer? Printing in windows is inordinately difficult although there are some modules around to help. In essence you have to draw the window as if you were drawing in a canvas object on the screen but using a printer device context. This is much too much like hard work and I generally do one of two things: 1) For plain text use the old DOS trick of sending output direct to the PRN: file/device - I can't remember if this still works in XP but I can't think why not... 2) For anything else generate HTML and then use the command line switches in the browser to generate the outpur using the default printer. Another option but its much more work is to create a PDF file for which task a 3rd party module exists somewhere. A lot depends on how complex your output needs to be. Text, Graphics or both. And how critical is the precision of your layout? HTH, Alan G. From python.programming at gmail.com Tue Mar 29 20:04:08 2005 From: python.programming at gmail.com (Kevin) Date: Tue Mar 29 20:04:20 2005 Subject: [Tutor] A very simple socket server question Message-ID: <d082fff805032910047e258414@mail.gmail.com> I figured out how to create a very simple socket server. Though this socket server does exactly nothing special. I can however get it to send only one line of data back to the telnet client. import socket ###################### HOST = "" PORT = 4000 ###################### s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((HOST,PORT)) s.listen(5) def log(): a = addr b = str(a) logfile = open("logfile.log", "a+") logfile.write("Attempting connection from "+b+"\n") logfile.close() while 1: conn, addr = s.accept() data = conn.recv(1024) if not data: break else: conn.send(data) How can I make it so that when a client sends the word hello the server will write back hello, how are you?. Thanks Kevin From jfouhy at paradise.net.nz Tue Mar 29 21:22:11 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Tue Mar 29 21:22:16 2005 Subject: [Tutor] A Newbie Printing Question In-Reply-To: <424950C6.1020909@cheqnet.net> References: <424950C6.1020909@cheqnet.net> Message-ID: <4249AAE3.30706@paradise.net.nz> Richard Lyons wrote: > I have little experience with programming. I have Python installed on a > Windows XP system. What code do I need to use to send output from a > Python script to a local printer attached to my workstation? to a > network printer? The win32print module (in Matt Hammond's windows modules) may help. eg: pid = win32print.OpenPrinter(win32print.GetDefaultPrinter()) win32print.StartDocPrinter(pid, 1, ('My print job', None, 'raw')) win32print.WritePrinter(pid, s) win32print.EndDocPrinter(pid) win32print.ClosePrinter(pid) When I did this, I was printing to a postscript printer, and I wasn't printing anything that required complex layout. So I generated the postscript code myself, and then just sent it straight to the printer... -- John. From igor.r at vodafone.net Tue Mar 29 21:54:27 2005 From: igor.r at vodafone.net (Igor Riabtchuk) Date: Tue Mar 29 21:54:47 2005 Subject: [Tutor] Text and Tkinter Message-ID: <000601c53499$1d557e70$c000a8c0@ARCISDESKTOP> Hi, As I am sure you know, the text widget in Tkinter by default prints keyboard output left-to-right. Is there a way to make it print right-to-left? Igor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050329/74a60f22/attachment.htm From kent37 at tds.net Tue Mar 29 22:55:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Mar 29 22:55:14 2005 Subject: [Tutor] A very simple socket server question In-Reply-To: <d082fff805032910047e258414@mail.gmail.com> References: <d082fff805032910047e258414@mail.gmail.com> Message-ID: <4249C0AE.2060408@tds.net> Kevin wrote: > I figured out how to create a very simple socket server. Though this > socket server does exactly nothing special. I can however get it to > send only one line of data back to the telnet client. You need two nested loops - an outer loop to accept the connection and an inner loop to proces the data. The way you have it now, it processes one line, then blocks waiting for a new connection. Take a look at example 19-1 in Python in a Nutshell. You can download it here: http://examples.oreilly.com/pythonian/ You might also be interested in example 19-5 which does the same thing using the SocketServer module and example 19-9 which uses Twisted. Kent > > import socket > ###################### > HOST = "" > PORT = 4000 > ###################### > > s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) > s.bind((HOST,PORT)) > s.listen(5) > def log(): > a = addr > b = str(a) > logfile = open("logfile.log", "a+") > logfile.write("Attempting connection from "+b+"\n") > logfile.close() > > while 1: > conn, addr = s.accept() > data = conn.recv(1024) > if not data: > break > else: > conn.send(data) > > How can I make it so that when a client sends the word hello the > server will write back > hello, how are you?. > > Thanks > Kevin > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Mar 30 01:01:54 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 01:01:57 2005 Subject: Fwd: [Tutor] Text and Tkinter In-Reply-To: <f2ff2d050329150131031544@mail.gmail.com> References: <000601c53499$1d557e70$c000a8c0@ARCISDESKTOP> <f2ff2d050329150131031544@mail.gmail.com> Message-ID: <f2ff2d05032915017eb1201d@mail.gmail.com> Oops, to list also. ---------- Forwarded message ---------- From: Liam Clarke <cyresse@gmail.com> Date: Wed, 30 Mar 2005 11:01:36 +1200 Subject: Re: [Tutor] Text and Tkinter To: Igor Riabtchuk <igor.r@vodafone.net> Yes.... I suppose. I don't use Tkinter overly much, so this may not be correct, but I understand that when you insert text you use someTextWidget.insert("the text", <pos>) where <pos> can be a numeric index, or a special position like END. So.... I would do this - text = "hello bob" for char in text: someTextWidget.insert(char, START) Give it a go, anyway. Regards, Liam Clarke On Tue, 29 Mar 2005 20:54:27 +0100, Igor Riabtchuk <igor.r@vodafone.net> wrote: > > Hi, > > As I am sure you know, the text widget in Tkinter by default prints keyboard > output left-to-right. Is there a way to make it print right-to-left? > > Igor > _______________________________________________ > 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. -- '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. From WilliTf at dshs.wa.gov Wed Mar 30 01:16:41 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Wed Mar 30 01:16:59 2005 Subject: [Tutor] updating Oracle tables via python Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0FD197E1@dshs-exch2.dshs.wa.lcl> Greetings, I am attempting to update an Oracle table using python. When I execute the code, the python script appears to hang, in that nothing else happens. As always, any assistance you can provide will be appreciated. Code: connection = cx_Oracle.connect("db/password@dbname") cursor = connection.cursor() strUpdate = " UPDATE table SET firstname = 'JOSEPH' WHERE lastname = 'SMITH' " cursor.execute(strUpdate) cursor.close() connection.close() Tom Williams DSHS - Research and Data Analysis Division 14th and Jefferson, MS: 45204 Olympia, WA 98504-5204 360.902.0764 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050329/d8e1add7/attachment.htm From cyresse at gmail.com Wed Mar 30 01:22:42 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 01:22:46 2005 Subject: [Tutor] updating Oracle tables via python In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0FD197E1@dshs-exch2.dshs.wa.lcl> References: <592E8923DB6EA348BE8E33FCAADEFFFC0FD197E1@dshs-exch2.dshs.wa.lcl> Message-ID: <f2ff2d050329152221871236@mail.gmail.com> Is that all the code? It's not going to be giving you any feedback. Chuck a few print commands in it. i.e. connection = cx_Oracle.connect("db/password@dbname") cursor = connection.cursor() print "Cursor created" strUpdate = " UPDATE table SET firstname = 'JOSEPH' WHERE lastname = 'SMITH' " cursor.execute(strUpdate) cursor.close() connection.close() print "completed" When you query the database manually, are your changes there? Regards, Liam Clarke On Tue, 29 Mar 2005 15:16:41 -0800, Williams, Thomas <WilliTf@dshs.wa.gov> wrote: > > > > Greetings, > > I am attempting to update an Oracle table using python. When I execute the > code, the python script appears to hang, in that nothing else happens. > > > > As always, any assistance you can provide will be appreciated. > > > > Code: > > > > connection = cx_Oracle.connect("db/password@dbname") > > cursor = connection.cursor() > > strUpdate = " UPDATE table SET firstname = 'JOSEPH' WHERE lastname = > 'SMITH' " > > cursor.execute(strUpdate) > > cursor.close() > > connection.close() > > > > > > Tom Williams > DSHS - Research and Data Analysis Division > 14th and Jefferson, MS: 45204 > Olympia, WA 98504-5204 > 360.902.0764 > > > _______________________________________________ > 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. From cyresse at gmail.com Wed Mar 30 02:13:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 02:13:20 2005 Subject: [Tutor] updating Oracle tables via python In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0FD197E2@dshs-exch2.dshs.wa.lcl> References: <592E8923DB6EA348BE8E33FCAADEFFFC0FD197E2@dshs-exch2.dshs.wa.lcl> Message-ID: <f2ff2d050329161334bbed4@mail.gmail.com> >From what little SQL I know, try using your quotation marks differently, see if it helps. strUpdate = 'UPDATE table SET firstname = "JOSEPH" WHERE lastname = "SMITH" ' Good luck, Liam Clarke On Tue, 29 Mar 2005 15:35:24 -0800, Williams, Thomas <WilliTf@dshs.wa.gov> wrote: > I have placed several print commands in the code before I submitted this > question, both before and after the cursor.execute(strUpdate) command. The > script will print all of the print commands up to the > cursor.execute(strUpdate) command, but not those after it. Therefore, I > think that the cursor.execute(strUpdate) is the source of the problem. > Also, when I manually query the database, the records within the table have > not been changed. > > Thanks, > > Tom > > -----Original Message----- > From: Liam Clarke [mailto:cyresse@gmail.com] > Sent: Tuesday, March 29, 2005 3:23 PM > To: Williams, Thomas > Cc: tutor@python.org > Subject: Re: [Tutor] updating Oracle tables via python > > Is that all the code? It's not going to be giving you any feedback. > Chuck a few print commands in it. > > i.e. > connection = cx_Oracle.connect("db/password@dbname") > > cursor = connection.cursor() > > print "Cursor created" > > strUpdate = " UPDATE table SET firstname = 'JOSEPH' WHERE lastname = > 'SMITH' " > > cursor.execute(strUpdate) > > cursor.close() > > connection.close() > > print "completed" > > When you query the database manually, are your changes there? > > Regards, > > Liam Clarke > > On Tue, 29 Mar 2005 15:16:41 -0800, Williams, Thomas > <WilliTf@dshs.wa.gov> wrote: > > > > > > > > Greetings, > > > > I am attempting to update an Oracle table using python. When I execute > the > > code, the python script appears to hang, in that nothing else happens. > > > > > > > > As always, any assistance you can provide will be appreciated. > > > > > > > > Code: > > > > > > > > connection = cx_Oracle.connect("db/password@dbname") > > > > cursor = connection.cursor() > > > > strUpdate = " UPDATE table SET firstname = 'JOSEPH' WHERE lastname = > > 'SMITH' " > > > > cursor.execute(strUpdate) > > > > cursor.close() > > > > connection.close() > > > > > > > > > > > > Tom Williams > > DSHS - Research and Data Analysis Division > > 14th and Jefferson, MS: 45204 > > Olympia, WA 98504-5204 > > 360.902.0764 > > > > > > _______________________________________________ > > 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. > > -- '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. From leec03273 at mac.com Wed Mar 30 06:52:31 2005 From: leec03273 at mac.com (Lee Cullens) Date: Wed Mar 30 06:52:38 2005 Subject: [Tutor] RE: Using IDLE on Mac OS X? Message-ID: <ee620756bad3391e4e80cc60b6366988@mac.com> This is not a great way to start on this list, but I am having trouble with an annoyance that I have not been able to solve and have not found an answer to elsewhere. (Dual 2.5 Mac G5; 10.3.8; Python 2.3; retired software engineer getting started with Python) I don't like using Python via the Bash terminal and PythonIDE works well but as you know is somewhat lacking, and I'm not ready yet to shell out for something like WingIDE. So I started using IDLE but have found an annoyance with it on (OS X) 10.3.8 - reportedly not a problem on 10.2. In the Help menu, the About and IDLE Help work fine, but the Python Docs selection is DOA as is defining an alternate help source with the correct Python site URL. Yes I know I can always click on a link in Safari to bring such up, but would like to use the help viewer from within IDLE. Just getting started, I make a lot of trips to the Python Docs :~) Does anyone on this list have any experience with the problem or know of any appropriate links? Thanks, Lee C From nbbalane at gmail.com Wed Mar 30 06:56:16 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed Mar 30 06:56:25 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <f2ff2d050314200533b13392@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <f2ff2d0503141552f34c4bc@mail.gmail.com> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> <f2ff2d050314200533b13392@mail.gmail.com> Message-ID: <2cad209005032920563e976997@mail.gmail.com> how should i modify this data reader: (assumes that there is only one entry per line followed by '\n') data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') data = data_file.readlines() self.irradianceStrings = map(str, data) self.irradianceIntegers = map(int, data) self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) so that i can read the text file created by this: self.filename = "%s\%s.txt" %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) self.table_file = open(self.filename,"a") self.table_file.write('%f\t'%self.temp11) self.table_file.write('%f\t'%self.temp22) self.table_file.write('%f\t'%self.pyra11) self.table_file.write('%f\t'%self.pyra22) self.table_file.write('%f\t'%self.voltage11) self.table_file.write('%f\t'%self.current11) self.table_file.write('\n') self.table_file.close() On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > Whoops, golden rule - "Never post untested code" > Sorry. > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > jrlen balane wrote: > > > ok, i've done what sir Kent just said, my fault... > > > > > > but an error still occurs: > > > Traceback (most recent call last): > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > print process(data) > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > tempLine = int(line) > > > ValueError: invalid literal for int(): abc > > > > > > isn't this the job of : > > > > > > except TypeError: > > > print "Non numeric character in line", line > > > continue #Breaks, and starts with next line > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > >>> int('foo') > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > ValueError: invalid literal for int(): foo > > > > Kent > > > > _______________________________________________ > > 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 > From nbbalane at gmail.com Wed Mar 30 08:16:11 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed Mar 30 08:16:17 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad209005032920563e976997@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> <f2ff2d050314200533b13392@mail.gmail.com> <2cad209005032920563e976997@mail.gmail.com> Message-ID: <2cad20900503292216706f9325@mail.gmail.com> I need the string representation of the data read so that i can put it on a wxGrid while i am goin to need the integer representation of the data so that i can plot it. anybody, please help!!! On Tue, 29 Mar 2005 20:56:16 -0800, jrlen balane <nbbalane@gmail.com> wrote: > how should i modify this data reader: > (assumes that there is only one entry per line followed by '\n') > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > data = data_file.readlines() > > self.irradianceStrings = map(str, data) > self.irradianceIntegers = map(int, data) > self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) > > so that i can read the text file created by this: > > self.filename = "%s\%s.txt" > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) > > self.table_file = open(self.filename,"a") > self.table_file.write('%f\t'%self.temp11) > self.table_file.write('%f\t'%self.temp22) > self.table_file.write('%f\t'%self.pyra11) > self.table_file.write('%f\t'%self.pyra22) > self.table_file.write('%f\t'%self.voltage11) > self.table_file.write('%f\t'%self.current11) > self.table_file.write('\n') > self.table_file.close() > > > On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > Whoops, golden rule - "Never post untested code" > > Sorry. > > > > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > > jrlen balane wrote: > > > > ok, i've done what sir Kent just said, my fault... > > > > > > > > but an error still occurs: > > > > Traceback (most recent call last): > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > > print process(data) > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > > tempLine = int(line) > > > > ValueError: invalid literal for int(): abc > > > > > > > > isn't this the job of : > > > > > > > > except TypeError: > > > > print "Non numeric character in line", line > > > > continue #Breaks, and starts with next line > > > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > > >>> int('foo') > > > Traceback (most recent call last): > > > File "<stdin>", line 1, in ? > > > ValueError: invalid literal for int(): foo > > > > > > Kent > > > > > > _______________________________________________ > > > 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 > > > From nbbalane at gmail.com Wed Mar 30 09:47:14 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed Mar 30 09:47:16 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad20900503292216706f9325@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> <f2ff2d050314200533b13392@mail.gmail.com> <2cad209005032920563e976997@mail.gmail.com> <2cad20900503292216706f9325@mail.gmail.com> Message-ID: <2cad20900503292347c55e317@mail.gmail.com> am getting desperate on this, please help me, I just can't figure out how to read those tabs please help me! On Tue, 29 Mar 2005 22:16:11 -0800, jrlen balane <nbbalane@gmail.com> wrote: > I need the string representation of the data read so that i can put it > on a wxGrid > while i am goin to need the integer representation of the data so that > i can plot it. > > anybody, please help!!! > > > On Tue, 29 Mar 2005 20:56:16 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > how should i modify this data reader: > > (assumes that there is only one entry per line followed by '\n') > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > data = data_file.readlines() > > > > self.irradianceStrings = map(str, data) > > self.irradianceIntegers = map(int, data) > > self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) > > > > so that i can read the text file created by this: > > > > self.filename = "%s\%s.txt" > > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) > > > > self.table_file = open(self.filename,"a") > > self.table_file.write('%f\t'%self.temp11) > > self.table_file.write('%f\t'%self.temp22) > > self.table_file.write('%f\t'%self.pyra11) > > self.table_file.write('%f\t'%self.pyra22) > > self.table_file.write('%f\t'%self.voltage11) > > self.table_file.write('%f\t'%self.current11) > > self.table_file.write('\n') > > self.table_file.close() > > > > > > On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > > Whoops, golden rule - "Never post untested code" > > > Sorry. > > > > > > > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > > > jrlen balane wrote: > > > > > ok, i've done what sir Kent just said, my fault... > > > > > > > > > > but an error still occurs: > > > > > Traceback (most recent call last): > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > > > print process(data) > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > > > tempLine = int(line) > > > > > ValueError: invalid literal for int(): abc > > > > > > > > > > isn't this the job of : > > > > > > > > > > except TypeError: > > > > > print "Non numeric character in line", line > > > > > continue #Breaks, and starts with next line > > > > > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > > > >>> int('foo') > > > > Traceback (most recent call last): > > > > File "<stdin>", line 1, in ? > > > > ValueError: invalid literal for int(): foo > > > > > > > > Kent > > > > > > > > _______________________________________________ > > > > 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 > > > > > > From cyresse at gmail.com Wed Mar 30 10:07:42 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 10:07:46 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad209005032920563e976997@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <f2ff2d05031415534e7ba0b0@mail.gmail.com> <2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> <f2ff2d050314200533b13392@mail.gmail.com> <2cad209005032920563e976997@mail.gmail.com> Message-ID: <f2ff2d05033000077bb41a31@mail.gmail.com> So... you need those tabs? If you don't need them, go like this - > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') for x in data: y = str(x) ( temp11, temp22, pyra11, pyra22, voltage11, current1) = y.split('\t') And that should be all your values, separated in string format. On Tue, 29 Mar 2005 20:56:16 -0800, jrlen balane <nbbalane@gmail.com> wrote: > how should i modify this data reader: > (assumes that there is only one entry per line followed by '\n') > > data = data_file.readlines() > > self.irradianceStrings = map(str, data) > self.irradianceIntegers = map(int, data) > self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) > > so that i can read the text file created by this: > > self.filename = "%s\%s.txt" > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) > > self.table_file = open(self.filename,"a") > self.table_file.write('%f\t'%self.temp11) > self.table_file.write('%f\t'%self.temp22) > self.table_file.write('%f\t'%self.pyra11) > self.table_file.write('%f\t'%self.pyra22) > self.table_file.write('%f\t'%self.voltage11) > self.table_file.write('%f\t'%self.current11) > self.table_file.write('\n') > self.table_file.close() > > > On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > Whoops, golden rule - "Never post untested code" > > Sorry. > > > > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > > jrlen balane wrote: > > > > ok, i've done what sir Kent just said, my fault... > > > > > > > > but an error still occurs: > > > > Traceback (most recent call last): > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > > print process(data) > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > > tempLine = int(line) > > > > ValueError: invalid literal for int(): abc > > > > > > > > isn't this the job of : > > > > > > > > except TypeError: > > > > print "Non numeric character in line", line > > > > continue #Breaks, and starts with next line > > > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > > >>> int('foo') > > > Traceback (most recent call last): > > > File "<stdin>", line 1, in ? > > > ValueError: invalid literal for int(): foo > > > > > > Kent > > > > > > _______________________________________________ > > > 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 > > > -- '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. From cyresse at gmail.com Wed Mar 30 11:21:39 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 11:21:41 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad2090050330010848c83f4d@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> <f2ff2d050314200533b13392@mail.gmail.com> <2cad209005032920563e976997@mail.gmail.com> <f2ff2d05033000077bb41a31@mail.gmail.com> <2cad209005033000292f18ec86@mail.gmail.com> <2cad2090050330010848c83f4d@mail.gmail.com> Message-ID: <f2ff2d05033001218433135@mail.gmail.com> >print temp1[x], temp2[x] This won't work. >>> fob = [] >>> gab = ["fooBar","Baz","aBBa"] >>> for line in gab: ... print line, ... x = line.replace('B', 'X') ... print x ... fob.append(x) ... print fob[line] ... fooBar fooXar Traceback (most recent call last): File "<interactive input>", line 6, in ? TypeError: list indices must be integers >ValueError: unpack list of wrong size What should I do? Catch the exception - try: (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') except ValueError: print "Line:", y print len(y.split('\t')), "items found" And see what's going wrong. You get a ValueError like that one like so - >>> x = ["1,2,3", "4,5,6", "7,8"] >>> for af in x: ... (a,b,c) = af.split(',') ... print a,b,c ... 1 2 3 4 5 6 Traceback (most recent call last): File "<interactive input>", line 2, in ? ValueError: unpack list of wrong size See, it's trying to get 3 items from each split, but the last one only gives 2 items. So, print the offending line, I'm guessing it's a blank "\n" or "\t" line. Regards, Liam Clarke On Wed, 30 Mar 2005 17:08:07 +0800, jrlen balane <nbbalane@gmail.com> wrote: > after running this in IDLE: > > import sys > import serial > import sys, os > import serial > import string > import time > from struct import * > > temp1 = [] > temp2 = [] > pyra1 = [] > pyra2 = [] > voltage = [] > current = [] > > data_file = open('C:/Documents and Settings/nyer/My > Documents/Info/info2/200503300858.txt', 'r') > data = data_file.readlines() > for x in data: > y = str(x) > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > temp11Integer = map(int, temp11) > temp22Integer = map(int, temp22) > pyra11Integer = map(int, pyra11) > pyra22Integer = map(int, pyra22) > voltage11Integer = map(int, voltage11) > current11Integer = map(int, current11) > > print temp11Integer, temp22Integer, pyra11Integer, pyra22Integer, > voltage11Integer, current11Integer > > temp1.append(temp11Integer) > temp2.append(temp22Integer) > pyra1.append(pyra11Integer) > pyra2.append(pyra22Integer) > voltage.append(voltage11Integer) > current.append(current11Integer) > > print temp1[x], temp2[x] > > an error: > Traceback (most recent call last): > File "C:/Python23/practices/read.py", line 21, in -toplevel- > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > ValueError: unpack list of wrong size > > What should i do?? > > > On Wed, 30 Mar 2005 00:29:05 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > so basically, i'll just do this to append the data to the list: > > > > temp1[]=0 > > temp2[]=0 > > pyra1[] =0 > > pyra2[] =0 > > voltage[] =0 > > current[] =0 > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > > > for x in data: > > y = str(x) > > ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > temp11Integer = map(int, temp11) > > temp22Integer = map(int, temp22) > > pyra11Integer = map(int, pyra11) > > pyra22Integer = map(int, pyra22) > > voltage11Integer = map(int, voltage11) > > current11Integer = map(int, current11) > > > > temp1.append(temp11Integer) > > temp2.append(temp22Integer) > > pyra1.append(pyra11Integer) > > pyra2.append(pyra22Integer) > > voltage.append(voltage11Integer) > > current.append(current11Integer) > > > > > > On Wed, 30 Mar 2005 20:07:42 +1200, Liam Clarke <cyresse@gmail.com> wrote: > > > So... you need those tabs? If you don't need them, go like this - > > > > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > > for x in data: > > > y = str(x) > > > ( temp11, temp22, pyra11, pyra22, voltage11, current1) = y.split('\t') > > > > > > And that should be all your values, separated in string format. > > > > > > > > > On Tue, 29 Mar 2005 20:56:16 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > > > how should i modify this data reader: > > > > (assumes that there is only one entry per line followed by '\n') > > > > > > > > > > > data = data_file.readlines() > > > > > > > > self.irradianceStrings = map(str, data) > > > > self.irradianceIntegers = map(int, data) > > > > self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) > > > > > > > > so that i can read the text file created by this: > > > > > > > > self.filename = "%s\%s.txt" > > > > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) > > > > > > > > self.table_file = open(self.filename,"a") > > > > self.table_file.write('%f\t'%self.temp11) > > > > self.table_file.write('%f\t'%self.temp22) > > > > self.table_file.write('%f\t'%self.pyra11) > > > > self.table_file.write('%f\t'%self.pyra22) > > > > self.table_file.write('%f\t'%self.voltage11) > > > > self.table_file.write('%f\t'%self.current11) > > > > self.table_file.write('\n') > > > > self.table_file.close() > > > > > > > > > > > > On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > > > > Whoops, golden rule - "Never post untested code" > > > > > Sorry. > > > > > > > > > > > > > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > > > > > jrlen balane wrote: > > > > > > > ok, i've done what sir Kent just said, my fault... > > > > > > > > > > > > > > but an error still occurs: > > > > > > > Traceback (most recent call last): > > > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > > > > > print process(data) > > > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > > > > > tempLine = int(line) > > > > > > > ValueError: invalid literal for int(): abc > > > > > > > > > > > > > > isn't this the job of : > > > > > > > > > > > > > > except TypeError: > > > > > > > print "Non numeric character in line", line > > > > > > > continue #Breaks, and starts with next line > > > > > > > > > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > > > > > >>> int('foo') > > > > > > Traceback (most recent call last): > > > > > > File "<stdin>", line 1, in ? > > > > > > ValueError: invalid literal for int(): foo > > > > > > > > > > > > Kent > > > > > > > > > > > > _______________________________________________ > > > > > > 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 > > > > > > > > > > > > > > > -- > > > '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. > > > > > > -- '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. From cyresse at gmail.com Wed Mar 30 12:13:58 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 12:14:01 2005 Subject: [Tutor] how to read from a txt file In-Reply-To: <2cad2090050330012923ca35b7@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net> <f2ff2d050314200533b13392@mail.gmail.com> <2cad209005032920563e976997@mail.gmail.com> <f2ff2d05033000077bb41a31@mail.gmail.com> <2cad209005033000292f18ec86@mail.gmail.com> <2cad2090050330010848c83f4d@mail.gmail.com> <f2ff2d05033001218433135@mail.gmail.com> <2cad2090050330012923ca35b7@mail.gmail.com> Message-ID: <f2ff2d0503300213305b3d79@mail.gmail.com> Nope, it's not that. You can just change your map(int, foo) calls to use float. (But that said, you don't need map, as you're operating on one item at a time.) Hmm.... try changing the following. for x in data: y = str(x).rstrip('\t\n') #This will remove any stray tabs or newlines on the end. ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') (Also, you could probably rewrite like this) temp1, temp2, pyra1, pyra2, voltage, current = [],[],[],[],[],[] data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') for x in data: y = str(x).rstrip('\t\n') ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') temp1.append(float(temp11)) temp2.append(float(temp22)) pyra1.append(float(pyra11)) pyra2.append(float(pyra22)) voltage.append(float(voltage11)) current.append(float(current11)) On Wed, 30 Mar 2005 17:29:38 +0800, jrlen balane <nbbalane@gmail.com> wrote: > sir Liam, > > I think i know now what the problem is, i'm trying to read a float and > not integer. in this case how should i do this > > ======================================================== > Line: 1.313725 3.274510 4.352941 0.039216 0.019608 0.019608 > > 7 items found > > > On Wed, 30 Mar 2005 21:21:39 +1200, Liam Clarke <cyresse@gmail.com> wrote: > > >print temp1[x], temp2[x] > > > > This won't work. > > > > >>> fob = [] > > >>> gab = ["fooBar","Baz","aBBa"] > > >>> for line in gab: > > ... print line, > > ... x = line.replace('B', 'X') > > ... print x > > ... fob.append(x) > > ... print fob[line] > > ... > > fooBar fooXar > > Traceback (most recent call last): > > File "<interactive input>", line 6, in ? > > TypeError: list indices must be integers > > > > >ValueError: unpack list of wrong size > > What should I do? > > > > Catch the exception - > > > > try: > > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > except ValueError: > > print "Line:", y > > print len(y.split('\t')), "items found" > > > > And see what's going wrong. You get a ValueError like that one like so - > > >>> x = ["1,2,3", > > "4,5,6", > > "7,8"] > > >>> for af in x: > > ... (a,b,c) = af.split(',') > > ... print a,b,c > > ... > > 1 2 3 > > 4 5 6 > > Traceback (most recent call last): > > File "<interactive input>", line 2, in ? > > ValueError: unpack list of wrong size > > > > See, it's trying to get 3 items from each split, but the last one only > > gives 2 items. > > > > So, print the offending line, I'm guessing it's a blank "\n" or "\t" line. > > > > Regards, > > > > Liam Clarke > > > > > > On Wed, 30 Mar 2005 17:08:07 +0800, jrlen balane <nbbalane@gmail.com> wrote: > > > after running this in IDLE: > > > > > > import sys > > > import serial > > > import sys, os > > > import serial > > > import string > > > import time > > > from struct import * > > > > > > temp1 = [] > > > temp2 = [] > > > pyra1 = [] > > > pyra2 = [] > > > voltage = [] > > > current = [] > > > > > > data_file = open('C:/Documents and Settings/nyer/My > > > Documents/Info/info2/200503300858.txt', 'r') > > > data = data_file.readlines() > > > for x in data: > > > y = str(x) > > > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > temp11Integer = map(int, temp11) > > > temp22Integer = map(int, temp22) > > > pyra11Integer = map(int, pyra11) > > > pyra22Integer = map(int, pyra22) > > > voltage11Integer = map(int, voltage11) > > > current11Integer = map(int, current11) > > > > > > print temp11Integer, temp22Integer, pyra11Integer, pyra22Integer, > > > voltage11Integer, current11Integer > > > > > > temp1.append(temp11Integer) > > > temp2.append(temp22Integer) > > > pyra1.append(pyra11Integer) > > > pyra2.append(pyra22Integer) > > > voltage.append(voltage11Integer) > > > current.append(current11Integer) > > > > > > print temp1[x], temp2[x] > > > > > > an error: > > > Traceback (most recent call last): > > > File "C:/Python23/practices/read.py", line 21, in -toplevel- > > > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > ValueError: unpack list of wrong size > > > > > > What should i do?? > > > > > > > > > On Wed, 30 Mar 2005 00:29:05 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > > > so basically, i'll just do this to append the data to the list: > > > > > > > > temp1[]=0 > > > > temp2[]=0 > > > > pyra1[] =0 > > > > pyra2[] =0 > > > > voltage[] =0 > > > > current[] =0 > > > > > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > > > > > > > for x in data: > > > > y = str(x) > > > > ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > > temp11Integer = map(int, temp11) > > > > temp22Integer = map(int, temp22) > > > > pyra11Integer = map(int, pyra11) > > > > pyra22Integer = map(int, pyra22) > > > > voltage11Integer = map(int, voltage11) > > > > current11Integer = map(int, current11) > > > > > > > > temp1.append(temp11Integer) > > > > temp2.append(temp22Integer) > > > > pyra1.append(pyra11Integer) > > > > pyra2.append(pyra22Integer) > > > > voltage.append(voltage11Integer) > > > > current.append(current11Integer) > > > > > > > > > > > > On Wed, 30 Mar 2005 20:07:42 +1200, Liam Clarke <cyresse@gmail.com> wrote: > > > > > So... you need those tabs? If you don't need them, go like this - > > > > > > > > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > > > > for x in data: > > > > > y = str(x) > > > > > ( temp11, temp22, pyra11, pyra22, voltage11, current1) = y.split('\t') > > > > > > > > > > And that should be all your values, separated in string format. > > > > > > > > > > > > > > > On Tue, 29 Mar 2005 20:56:16 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > > > > > how should i modify this data reader: > > > > > > (assumes that there is only one entry per line followed by '\n') > > > > > > > > > > > > > > > > > data = data_file.readlines() > > > > > > > > > > > > self.irradianceStrings = map(str, data) > > > > > > self.irradianceIntegers = map(int, data) > > > > > > self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) > > > > > > > > > > > > so that i can read the text file created by this: > > > > > > > > > > > > self.filename = "%s\%s.txt" > > > > > > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) > > > > > > > > > > > > self.table_file = open(self.filename,"a") > > > > > > self.table_file.write('%f\t'%self.temp11) > > > > > > self.table_file.write('%f\t'%self.temp22) > > > > > > self.table_file.write('%f\t'%self.pyra11) > > > > > > self.table_file.write('%f\t'%self.pyra22) > > > > > > self.table_file.write('%f\t'%self.voltage11) > > > > > > self.table_file.write('%f\t'%self.current11) > > > > > > self.table_file.write('\n') > > > > > > self.table_file.close() > > > > > > > > > > > > > > > > > > On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > > > > > > Whoops, golden rule - "Never post untested code" > > > > > > > Sorry. > > > > > > > > > > > > > > > > > > > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > > > > > > > jrlen balane wrote: > > > > > > > > > ok, i've done what sir Kent just said, my fault... > > > > > > > > > > > > > > > > > > but an error still occurs: > > > > > > > > > Traceback (most recent call last): > > > > > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > > > > > > > print process(data) > > > > > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > > > > > > > tempLine = int(line) > > > > > > > > > ValueError: invalid literal for int(): abc > > > > > > > > > > > > > > > > > > isn't this the job of : > > > > > > > > > > > > > > > > > > except TypeError: > > > > > > > > > print "Non numeric character in line", line > > > > > > > > > continue #Breaks, and starts with next line > > > > > > > > > > > > > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > > > > > > > >>> int('foo') > > > > > > > > Traceback (most recent call last): > > > > > > > > File "<stdin>", line 1, in ? > > > > > > > > ValueError: invalid literal for int(): foo > > > > > > > > > > > > > > > > Kent > > > > > > > > > > > > > > > > _______________________________________________ > > > > > > > > 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 > > > > > > > > > > > > > > > > > > > > > > > -- > > > > > '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. > > > > > > > > > > > > > > > > -- > > '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 > > > -- '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. From cyresse at gmail.com Wed Mar 30 12:30:06 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Mar 30 12:30:10 2005 Subject: Fwd: [Tutor] how to read from a txt file In-Reply-To: <2cad20900503300226175741a5@mail.gmail.com> References: <4214615F.8020008@po-box.mcgill.ca> <f2ff2d050314200533b13392@mail.gmail.com> <2cad209005032920563e976997@mail.gmail.com> <f2ff2d05033000077bb41a31@mail.gmail.com> <2cad209005033000292f18ec86@mail.gmail.com> <2cad2090050330010848c83f4d@mail.gmail.com> <f2ff2d05033001218433135@mail.gmail.com> <2cad2090050330012923ca35b7@mail.gmail.com> <f2ff2d0503300213305b3d79@mail.gmail.com> <2cad20900503300226175741a5@mail.gmail.com> Message-ID: <f2ff2d05033002303b5c077f@mail.gmail.com> Sweet as. You should forward stuff to the list though, click reply all. : ) Liam ---------- Forwarded message ---------- From: jrlen balane <nbbalane@gmail.com> Date: Wed, 30 Mar 2005 18:26:44 +0800 Subject: Re: [Tutor] how to read from a txt file To: Liam Clarke <cyresse@gmail.com> many thanks to you sir, got it finally! On Wed, 30 Mar 2005 22:13:58 +1200, Liam Clarke <cyresse@gmail.com> wrote: > Nope, it's not that. You can just change your map(int, foo) calls to > use float. (But that said, you don't need map, as you're operating on > one item at a time.) > > Hmm.... > > try changing the following. > > for x in data: > y = str(x).rstrip('\t\n') #This will remove any stray tabs or > newlines on the end. > > ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > (Also, you could probably rewrite like this) > > temp1, temp2, pyra1, pyra2, voltage, current = [],[],[],[],[],[] > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > for x in data: > y = str(x).rstrip('\t\n') > ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > temp1.append(float(temp11)) > temp2.append(float(temp22)) > pyra1.append(float(pyra11)) > pyra2.append(float(pyra22)) > voltage.append(float(voltage11)) > current.append(float(current11)) > > On Wed, 30 Mar 2005 17:29:38 +0800, jrlen balane <nbbalane@gmail.com> wrote: > > sir Liam, > > > > I think i know now what the problem is, i'm trying to read a float and > > not integer. in this case how should i do this > > > > ======================================================== > > Line: 1.313725 3.274510 4.352941 0.039216 0.019608 0.019608 > > > > 7 items found > > > > > > On Wed, 30 Mar 2005 21:21:39 +1200, Liam Clarke <cyresse@gmail.com> wrote: > > > >print temp1[x], temp2[x] > > > > > > This won't work. > > > > > > >>> fob = [] > > > >>> gab = ["fooBar","Baz","aBBa"] > > > >>> for line in gab: > > > ... print line, > > > ... x = line.replace('B', 'X') > > > ... print x > > > ... fob.append(x) > > > ... print fob[line] > > > ... > > > fooBar fooXar > > > Traceback (most recent call last): > > > File "<interactive input>", line 6, in ? > > > TypeError: list indices must be integers > > > > > > >ValueError: unpack list of wrong size > > > What should I do? > > > > > > Catch the exception - > > > > > > try: > > > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > except ValueError: > > > print "Line:", y > > > print len(y.split('\t')), "items found" > > > > > > And see what's going wrong. You get a ValueError like that one like so - > > > >>> x = ["1,2,3", > > > "4,5,6", > > > "7,8"] > > > >>> for af in x: > > > ... (a,b,c) = af.split(',') > > > ... print a,b,c > > > ... > > > 1 2 3 > > > 4 5 6 > > > Traceback (most recent call last): > > > File "<interactive input>", line 2, in ? > > > ValueError: unpack list of wrong size > > > > > > See, it's trying to get 3 items from each split, but the last one only > > > gives 2 items. > > > > > > So, print the offending line, I'm guessing it's a blank "\n" or "\t" line. > > > > > > Regards, > > > > > > Liam Clarke > > > > > > > > > On Wed, 30 Mar 2005 17:08:07 +0800, jrlen balane <nbbalane@gmail.com> wrote: > > > > after running this in IDLE: > > > > > > > > import sys > > > > import serial > > > > import sys, os > > > > import serial > > > > import string > > > > import time > > > > from struct import * > > > > > > > > temp1 = [] > > > > temp2 = [] > > > > pyra1 = [] > > > > pyra2 = [] > > > > voltage = [] > > > > current = [] > > > > > > > > data_file = open('C:/Documents and Settings/nyer/My > > > > Documents/Info/info2/200503300858.txt', 'r') > > > > data = data_file.readlines() > > > > for x in data: > > > > y = str(x) > > > > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > > temp11Integer = map(int, temp11) > > > > temp22Integer = map(int, temp22) > > > > pyra11Integer = map(int, pyra11) > > > > pyra22Integer = map(int, pyra22) > > > > voltage11Integer = map(int, voltage11) > > > > current11Integer = map(int, current11) > > > > > > > > print temp11Integer, temp22Integer, pyra11Integer, pyra22Integer, > > > > voltage11Integer, current11Integer > > > > > > > > temp1.append(temp11Integer) > > > > temp2.append(temp22Integer) > > > > pyra1.append(pyra11Integer) > > > > pyra2.append(pyra22Integer) > > > > voltage.append(voltage11Integer) > > > > current.append(current11Integer) > > > > > > > > print temp1[x], temp2[x] > > > > > > > > an error: > > > > Traceback (most recent call last): > > > > File "C:/Python23/practices/read.py", line 21, in -toplevel- > > > > (temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > > ValueError: unpack list of wrong size > > > > > > > > What should i do?? > > > > > > > > > > > > On Wed, 30 Mar 2005 00:29:05 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > > > > so basically, i'll just do this to append the data to the list: > > > > > > > > > > temp1[]=0 > > > > > temp2[]=0 > > > > > pyra1[] =0 > > > > > pyra2[] =0 > > > > > voltage[] =0 > > > > > current[] =0 > > > > > > > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > > > > > > > > > for x in data: > > > > > y = str(x) > > > > > ( temp11, temp22, pyra11, pyra22, voltage11, current11) = y.split('\t') > > > > > temp11Integer = map(int, temp11) > > > > > temp22Integer = map(int, temp22) > > > > > pyra11Integer = map(int, pyra11) > > > > > pyra22Integer = map(int, pyra22) > > > > > voltage11Integer = map(int, voltage11) > > > > > current11Integer = map(int, current11) > > > > > > > > > > temp1.append(temp11Integer) > > > > > temp2.append(temp22Integer) > > > > > pyra1.append(pyra11Integer) > > > > > pyra2.append(pyra22Integer) > > > > > voltage.append(voltage11Integer) > > > > > current.append(current11Integer) > > > > > > > > > > > > > > > On Wed, 30 Mar 2005 20:07:42 +1200, Liam Clarke <cyresse@gmail.com> wrote: > > > > > > So... you need those tabs? If you don't need them, go like this - > > > > > > > > > > > > > data_file = open(os.path.normpath(self.TextFile.GetValue()), 'r') > > > > > > for x in data: > > > > > > y = str(x) > > > > > > ( temp11, temp22, pyra11, pyra22, voltage11, current1) = y.split('\t') > > > > > > > > > > > > And that should be all your values, separated in string format. > > > > > > > > > > > > > > > > > > On Tue, 29 Mar 2005 20:56:16 -0800, jrlen balane <nbbalane@gmail.com> wrote: > > > > > > > how should i modify this data reader: > > > > > > > (assumes that there is only one entry per line followed by '\n') > > > > > > > > > > > > > > > > > > > > data = data_file.readlines() > > > > > > > > > > > > > > self.irradianceStrings = map(str, data) > > > > > > > self.irradianceIntegers = map(int, data) > > > > > > > self.IrradianceExecute.SetValue(''.join(self.irradianceStrings)) > > > > > > > > > > > > > > so that i can read the text file created by this: > > > > > > > > > > > > > > self.filename = "%s\%s.txt" > > > > > > > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H%M")) > > > > > > > > > > > > > > self.table_file = open(self.filename,"a") > > > > > > > self.table_file.write('%f\t'%self.temp11) > > > > > > > self.table_file.write('%f\t'%self.temp22) > > > > > > > self.table_file.write('%f\t'%self.pyra11) > > > > > > > self.table_file.write('%f\t'%self.pyra22) > > > > > > > self.table_file.write('%f\t'%self.voltage11) > > > > > > > self.table_file.write('%f\t'%self.current11) > > > > > > > self.table_file.write('\n') > > > > > > > self.table_file.close() > > > > > > > > > > > > > > > > > > > > > On Tue, 15 Mar 2005 17:05:46 +1300, Liam Clarke <cyresse@gmail.com> wrote: > > > > > > > > Whoops, golden rule - "Never post untested code" > > > > > > > > Sorry. > > > > > > > > > > > > > > > > > > > > > > > > On Mon, 14 Mar 2005 21:05:44 -0500, Kent Johnson <kent37@tds.net> wrote: > > > > > > > > > jrlen balane wrote: > > > > > > > > > > ok, i've done what sir Kent just said, my fault... > > > > > > > > > > > > > > > > > > > > but an error still occurs: > > > > > > > > > > Traceback (most recent call last): > > > > > > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 18, in -toplevel- > > > > > > > > > > print process(data) > > > > > > > > > > File "C:\Python23\practices\opentxtprintlngnew.py", line 10, in process > > > > > > > > > > tempLine = int(line) > > > > > > > > > > ValueError: invalid literal for int(): abc > > > > > > > > > > > > > > > > > > > > isn't this the job of : > > > > > > > > > > > > > > > > > > > > except TypeError: > > > > > > > > > > print "Non numeric character in line", line > > > > > > > > > > continue #Breaks, and starts with next line > > > > > > > > > > > > > > > > > > Yes, only it should be ValueError instead of TypeError. You can check this interactively: > > > > > > > > > >>> int('foo') > > > > > > > > > Traceback (most recent call last): > > > > > > > > > File "<stdin>", line 1, in ? > > > > > > > > > ValueError: invalid literal for int(): foo > > > > > > > > > > > > > > > > > > Kent > > > > > > > > > > > > > > > > > > _______________________________________________ > > > > > > > > > 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 > > > > > > > > > > > > > > > > > > > > > > > > > > > -- > > > > > > '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. > > > > > > > > > > > > > > > > > > > > > -- > > > '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 > > > > > > > -- > '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. > -- '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. From bvande at po-box.mcgill.ca Wed Mar 30 15:51:56 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Mar 30 15:52:49 2005 Subject: [Tutor] RE: Using IDLE on Mac OS X? In-Reply-To: <ee620756bad3391e4e80cc60b6366988@mac.com> References: <ee620756bad3391e4e80cc60b6366988@mac.com> Message-ID: <424AAEFC.30105@po-box.mcgill.ca> Lee Cullens said unto the world upon 2005-03-29 23:52: > This is not a great way to start on this list, but I am having trouble > with an annoyance that I have not been able to solve and have not found > an answer to elsewhere. > > (Dual 2.5 Mac G5; 10.3.8; Python 2.3; retired software engineer getting > started with Python) > > I don't like using Python via the Bash terminal and PythonIDE works well > but as you know is somewhat lacking, and I'm not ready yet to shell out > for something like WingIDE. So I started using IDLE but have found an > annoyance with it on (OS X) 10.3.8 - reportedly not a problem on 10.2. > In the Help menu, the About and IDLE Help work fine, but the Python Docs > selection is DOA as is defining an alternate help source with the > correct Python site URL. > > Yes I know I can always click on a link in Safari to bring such up, but > would like to use the help viewer from within IDLE. Just getting > started, I make a lot of trips to the Python Docs :~) Does anyone on > this list have any experience with the problem or know of any > appropriate links? > > Thanks, > Lee C > Hi Lee, welcome to the list and to Python! I'm ignorant of what goes on in the Mac. I know on Windows installations there is a compiled help (.chm) file bundled with the Python installer and the option to download the help files as html from the python site. There is also a way to get (much of) the documentation within IDLE (or when running Python in a bash shell for that mater). Try help() at the prompt -- that gets you much of the documentation via pydoc. You can also call help(some_object_or_imported_module) This will also work for your own objects, if you give them docstrings. Very handy. At least on Windows, if you have the html docs installed and have set the pythondocs environment variable to point the the directory where they are installed[*], help(topics) pulls up a menu that gives you access to much of them, too. This feature seems little known, but I've found it handy. [*] On windows, putting SET PYTHONDOCS=[my html docs install dir] (with the obvious substitution) into my autoexec.bat worked. No idea for the Mac. HTH, Brian vdB From python.programming at gmail.com Wed Mar 30 18:38:46 2005 From: python.programming at gmail.com (Kevin) Date: Wed Mar 30 18:38:49 2005 Subject: [Tutor] Class and methods? Message-ID: <d082fff8050330083841cedec5@mail.gmail.com> In a class is every def called a method and the def __init__(self) is called the constructor method? This class stuff is a little confusing. I don't have a problem writting a def I am still not clear on how to use a constructor. Is there a site that explains the constructor in great detail? Thanks Kevin From shaleh at speakeasy.net Wed Mar 30 18:53:41 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 30 18:55:58 2005 Subject: [Tutor] Class and methods? In-Reply-To: <d082fff8050330083841cedec5@mail.gmail.com> References: <d082fff8050330083841cedec5@mail.gmail.com> Message-ID: <424AD995.7000900@speakeasy.net> Kevin wrote: > In a class is every def called a method and the def __init__(self) is > called the constructor method? This class stuff is a little confusing. > I don't have a problem writting a def I am still not clear on how to > use a constructor. Is there a site that explains the constructor in > great detail? > a method is simply a function attached to an object which acts on that object. Nothing fancy. You can think of __init__ as a constructor. I have seen Python people refer to it as an initializer as well. All __init__ is doing is preparing the object for use. Give initial values to any variables, setup any datastructures, and/or maybe call a few other functions / classes. thing = MyClass(a,b) the call to MyClass above gets mapped to MyClass.__init__(a,b). Logically the flow is: Python makes an instance of the object (MyClass) Python calls __init__ if it is defined when __init__ returns Python assigns the object to the waiting variable From jeffshannon at gmail.com Wed Mar 30 19:45:06 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Mar 30 19:45:10 2005 Subject: [Tutor] Launching a file browser In-Reply-To: <4b685d8f6b18e7823cf46d0ba8d8908b@critterpixstudios.com> References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> <1112055872.4248a0408ea5c@www.paradise.net.nz> <4b685d8f6b18e7823cf46d0ba8d8908b@critterpixstudios.com> Message-ID: <5d0204a105033009457f432254@mail.gmail.com> On Mon, 28 Mar 2005 18:53:39 -0800, Mike Hall <michael.hall@critterpixstudios.com> wrote: > I my case the gui will be comprised of html and javascript, talking to > python through system calls. I basically want to know if there's an > equivalent of the "webbrowser()" module (which launches my browser) for > file dialogs. This is what EasyDialogs should do, but does not. If you're using html and browser scripting for your GUI, then you'll probably need to use html and browser scripting for your file dialog too. A file dialog is just another GUI segment, so it should work the same as the rest of your GUI. Jeff Shannon From jeannot18 at hotmail.com Wed Mar 30 19:50:08 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Wed Mar 30 19:50:35 2005 Subject: [Tutor] Calendar module Message-ID: <BAY20-F14679A8B7ECBF9F4ECF0EAB3460@phx.gbl> Hi guys, I have typed this programme from the Josh Cogliati manual ------------------------------------------------------------- import calendar year = input("Type in the year number: ") calendar.prcal(year) I get this error message Traceback (most recent call last): File "C:/Python24/Example/cal.py", line 1, in -toplevel- import calendar File "C:\Python24\Example\calendar.py", line 4, in -toplevel- calendar.prcal(year) AttributeError: 'module' object has no attribute 'prcal' ---------------------------------------------------------------- And for some reason it does not work. I saved it as cal.py and it is running from the same folder that hold Python 2.4 (I run XP) any reason why it is not working (I managed to make it work at my workplace by the way. JC From singingxduck at gmail.com Wed Mar 30 20:00:50 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Wed Mar 30 20:00:53 2005 Subject: [Tutor] issues with .remove method Message-ID: <3449428f050330100064aacdfa@mail.gmail.com> Hello all, True to Pierre's suggestion, I have reimplemented LinkedList without embedding a list in it. I also took out the dictionary, on the basis that dictionaries can behave as badly as O(n), and often behave O(log(n)), depending on the hash function they're based on, and the point of a LinkedList is O(1) behavior for insertions. The new implementation is available at http://rafb.net/paste/results/JH4txr81.html, but it does not yet work completely, and as such, I haven't included any unit tests. In particular, the remove method seems to work arbitrarily (removing random indices instead of the specified ones), and I'm baffled as to why. I'd be grateful to anyone who can enlighten me. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From jeffshannon at gmail.com Wed Mar 30 20:05:07 2005 From: jeffshannon at gmail.com (Jeff Shannon) Date: Wed Mar 30 20:05:13 2005 Subject: [Tutor] Float precision untrustworthy~~~ In-Reply-To: <000901c5340d$52bd6410$da5428cf@JSLAPTOP> References: <000901c5340d$52bd6410$da5428cf@JSLAPTOP> Message-ID: <5d0204a1050330100579512ab8@mail.gmail.com> On Mon, 28 Mar 2005 22:13:10 -0500, Jacob S. <keridee@jayco.net> wrote: > I've already deleted the recent thread-- > > But sometimes I agree with he who said that you can't trust floats at all. > > The scientific theory suggests that if an output is not what it should be, > then the hypothesis is untrue. > In this case, the hypothesis is the fact that float division should always > produce the same output as our decimal division used in common schools > today. Since that is not always true, then floats are not trustworthy~~~ > frankly, the mere fact that floats are difficult to check with equality has > bitten me more than anything I've met yet in python. The scientific method is also quite well aware of the limits of precision. *EVERY* tool that you use to make measurements has precision limits. In most of those cases, the imprecision due to measuring tools will overwhelmingly swamp the tiny bit of imprecision involved with floating-point arithmetic. It's also worth pointing out that most of the float imprecision isn't anything inherent in the floats themselves -- it's due to converting between binary and decimal representation. Just as a phrase that's translated from English into Russian and then back to English again can have its meaning shifted, translating between different numerical bases can create error -- but it's usually *much* less error than the natural language translations cause. Really, all this talk about floating-point imprecision is *way* overblown. It's important to be aware of it, yes, because in some cases it can be relevant... but it's a *long* way from making floats unusable or unreliable. > >>> 64**(1/3) == 4 > False > >>> 64**-3 == 4 > False > >>> a = 1/3 > >>> a > 0.33333333333333331 Note that you'll have the same problems if you use a Decimal number type, because there's also an imprecision with Decimals. The problem is that you're expecting a digital variable with a limited discrete set of possible values to be equivalent to a rational number -- but no binary or decimal floating-point number can exactly represent 1/3. A Decimal approximation would have a 3 as the final digit rather than a 1, but there *would* be a final digit, and *that* is why this can't work. > Why not just implement decimal or some equivalent and > get rid of hidden, hard to debug headaches? Well, a Decimal type *has* been implemented... but it's just trading one set of headaches for another. What your code is apparently expecting is a Rational type, which has been discussed ad infinitum (and probably implemented several times, though not (yet) accepted into the standard library); Rationals have the problem, though, that any given operation may take an unpredictable amount of time to execute. Would you consider it an improvement if, instead of wondering why you're not getting an equality, you were wondering whether your machine had frozen? There's always a trade-off. It's important to be aware of the weaknesses of the tools that you use, but *every* tool has weaknesses, and it doesn't make sense to discard a tool just because you've learned what those weaknesses are. Jeff Shannon From kent37 at tds.net Wed Mar 30 20:36:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 30 20:36:06 2005 Subject: [Tutor] Calendar module In-Reply-To: <BAY20-F14679A8B7ECBF9F4ECF0EAB3460@phx.gbl> References: <BAY20-F14679A8B7ECBF9F4ECF0EAB3460@phx.gbl> Message-ID: <424AF193.605@tds.net> John Carmona wrote: > Hi guys, I have typed this programme from the Josh Cogliati manual > > ------------------------------------------------------------- > import calendar > > year = input("Type in the year number: ") > calendar.prcal(year) > > > I get this error message > > Traceback (most recent call last): > File "C:/Python24/Example/cal.py", line 1, in -toplevel- > import calendar > File "C:\Python24\Example\calendar.py", line 4, in -toplevel- > calendar.prcal(year) > AttributeError: 'module' object has no attribute 'prcal' > ---------------------------------------------------------------- > > And for some reason it does not work. I saved it as cal.py and it is > running from the same folder that hold Python 2.4 (I run XP) > > any reason why it is not working (I managed to make it work at my > workplace by the way. Because you have a file named calendar.py in the Example directory (look at the stack trace). This file is hiding the library calendar file. Kent > > JC > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Mar 30 20:38:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Mar 30 20:38:59 2005 Subject: [Tutor] Float precision untrustworthy~~~ In-Reply-To: <000901c5340d$52bd6410$da5428cf@JSLAPTOP> References: <000901c5340d$52bd6410$da5428cf@JSLAPTOP> Message-ID: <424AF240.30202@tds.net> Jacob S. wrote: > I've already deleted the recent thread-- > > But sometimes I agree with he who said that you can't trust floats at all. > > The scientific theory suggests that if an output is not what it should > be, then the hypothesis is untrue. > In this case, the hypothesis is the fact that float division should > always produce the same output as our decimal division used in common > schools today. Since that is not always true, then floats are not > trustworthy~~~ No, you should conclude that the hypothesis is untrue - that in fact float division does not produce the same output as decimal division - and look for a new hypothesis. Like, maybe that float division is a close approximation of exact decimal division that has some well-known limitations. Kent From jeannot18 at hotmail.com Wed Mar 30 22:32:05 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Wed Mar 30 22:32:08 2005 Subject: [Tutor] I am puzzled - help needed Message-ID: <BAY20-F162E3C9EADCC828881CF54B3460@phx.gbl> I am not sure that it is possible to ask that question please feel free to turn me down if it is going against the forum rules. I have going through Josh Cogliati tutorial, I am stuck on one of the exercise. I need to rewrite the high_low.py program (see below) to use the last two digits of time at that moment to be the "random number". This is using the import time module. I just can't work out how to do that, I have been looking at it for the past 2,5 hours but can't break it. Has anyone done it in order for me to study it. Many thanks in advance for any help JC This is the original programme: number = 78 guess = 0 while guess != number guess = input ("Guess a number: ") if guess > number: print "Too high" elif guess < number: print "Too low" print "just right" From alan.gauld at freenet.co.uk Wed Mar 30 22:38:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 30 22:39:13 2005 Subject: [Tutor] how to read from a txt file References: <4214615F.8020008@po-box.mcgill.ca><2cad2090050314163613e34ee@mail.gmail.com> <423632F6.8020304@tds.net><2cad209005031417065fe92874@mail.gmail.com> <423638D5.5050500@tds.net><2cad209005031417381018f2b4@mail.gmail.com> <423642F8.3090909@tds.net><f2ff2d050314200533b13392@mail.gmail.com><2cad209005032920563e976997@mail.gmail.com><2cad20900503292216706f9325@mail.gmail.com> <2cad20900503292347c55e317@mail.gmail.com> Message-ID: <011f01c53568$79ae63b0$61cb8751@xp> > please help me! I'll try but I m9issed the early bit of this thread so jumping in cold... > > > so that i can read the text file created by this: > > > > > > self.filename = "%s\%s.txt" If the OS is Windows you might want to use two \\ just to be safe or alternatively use a forward slash instead. > > > %(os.path.normpath(self.SaveFolder.GetValue()),time.strftime("%Y%m%d%H %M")) > > > > > > self.table_file = open(self.filename,"a") > > > self.table_file.write('%f\t'%self.temp11) > > > self.table_file.write('%f\t'%self.temp22) > > > self.table_file.write('%f\t'%self.pyra11) > > > self.table_file.write('%f\t'%self.pyra22) > > > self.table_file.write('%f\t'%self.voltage11) > > > self.table_file.write('%f\t'%self.current11) > > > self.table_file.write('\n') All of that is on a single line, so you could do it with a single format string if you prefer. self.table_file.write('%f\t%f\t%f\t%f\t%f\t%f\n' % self.temp11,self.temp22, self.pyra11,self.pyra22, self.voltage11,self.current11) Personally I find it easier to read. To read it back you want to read the line, strip it and then split it using a tab as separator. self.data = tuple(inputfile.readline().strip().split('\t')) ( self.temp11, self.temp22, self.pyra11, self.pyra22, self.voltage11, self.current11 ) = self.data HTH, Alan G. From alan.gauld at freenet.co.uk Wed Mar 30 22:46:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Mar 30 22:45:50 2005 Subject: [Tutor] Class and methods? References: <d082fff8050330083841cedec5@mail.gmail.com> Message-ID: <013701c53569$9103c9f0$61cb8751@xp> > In a class is every def called a method Strictly speaking only those that have a 'self' parameter(or equivalent) The others are "unbound functions" and pretty useless, usually being the result of programmer errors!... > and the def __init__(self) is called the constructor method? Usually. > I don't have a problem writting a def I am still not clear on how to > use a constructor. Use the constructor to initialise the attributes of your new instance. When you create an instance by calling a class: instance = Class(a,b,c) what happens is that Python creates a blank instance of Class then calls the __init__ method of the new instance passing in the arguments you gave to the class, in our case a,b,c. [ If your class inherits from a superclass then its usually a good idea to call the superclass init method inside your init just to make sure the superclass attributes are all set up properly too. ] > Is there a site that explains the constructor in > great detail? Well I try... But it depends on how great a detail you want. "Great detail" implies "not easy to understand", in which case the definitive site is the Python documentation! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jfouhy at paradise.net.nz Wed Mar 30 22:54:59 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: Wed Mar 30 22:55:00 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <BAY20-F162E3C9EADCC828881CF54B3460@phx.gbl> References: <BAY20-F162E3C9EADCC828881CF54B3460@phx.gbl> Message-ID: <424B1223.2000905@paradise.net.nz> John Carmona wrote: > I have going through Josh Cogliati tutorial, I am stuck on one of the > exercise. I need to rewrite the high_low.py program (see below) to use > the last two digits of time at that moment to be the "random number". > This is using the import time module. If you look at the docs for the time module, you will see that time.time will return the number of seconds since the epoch. >>> import time >>> help(time.time) Help on built-in function time: time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. >>> time.time() 1112215685.8956151 The last two digits here will be changing very frequently, so they make a reasonable choice as a simple sort of random number. But how do you get the last two? If we had the number as a string (ie: "1112215685.8956151"), we could use string slicing to extract the end: if s = "1112215685.8956151" then s[-2:] will be "51". So, to get your random number, you will need to: - Convert the current time into a string. - Get the last two characters. - Convert them into an integer. HTH! -- John. From shaleh at speakeasy.net Wed Mar 30 22:57:30 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Wed Mar 30 22:59:46 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <BAY20-F162E3C9EADCC828881CF54B3460@phx.gbl> References: <BAY20-F162E3C9EADCC828881CF54B3460@phx.gbl> Message-ID: <424B12BA.7000200@speakeasy.net> John Carmona wrote: > I am not sure that it is possible to ask that question please feel free > to turn me down if it is going against the forum rules. > > I have going through Josh Cogliati tutorial, I am stuck on one of the > exercise. I need to rewrite the high_low.py program (see below) to use > the last two digits of time at that moment to be the "random number". > This is using the import time module. > > I just can't work out how to do that, I have been looking at it for the > past 2,5 hours but can't break it. Has anyone done it in order for me to > study it. > > Many thanks in advance for any help It helps to know what you are having prolems with. Can you not get the time from the time module? Is getting the last two digits causing you fits? We do not mind helping people learn or even do their homework. We just don't like to give out the answers (-: From python.programming at gmail.com Wed Mar 30 23:00:03 2005 From: python.programming at gmail.com (Kevin) Date: Wed Mar 30 23:00:06 2005 Subject: [Tutor] A simple question about creating a program Message-ID: <d082fff8050330130079b4c91b@mail.gmail.com> I was wondering, can you make a program the uses alot of classes do the exact same thing with out useing classes? From ryan at acceleration.net Wed Mar 30 23:14:47 2005 From: ryan at acceleration.net (Ryan Davis) Date: Wed Mar 30 23:14:53 2005 Subject: [Tutor] A simple question about creating a program In-Reply-To: <d082fff8050330130079b4c91b@mail.gmail.com> Message-ID: <20050330211451.68F511E400E@bag.python.org> Sure. Thanks, Ryan -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Kevin Sent: Wednesday, March 30, 2005 4:00 PM To: tutor@python.org Subject: [Tutor] A simple question about creating a program I was wondering, can you make a program the uses alot of classes do the exact same thing with out useing classes? _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Thu Mar 31 00:04:54 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Mar 31 00:04:57 2005 Subject: [Tutor] A simple question about creating a program In-Reply-To: <d082fff8050330130079b4c91b@mail.gmail.com> References: <d082fff8050330130079b4c91b@mail.gmail.com> Message-ID: <f2ff2d0503301404f1d7b8a@mail.gmail.com> Yes you can, but if an app uses a lot of classes, chances are that it's the simplest way to do it. OOP is really just a convenient way to work with code. On Wed, 30 Mar 2005 16:00:03 -0500, Kevin <python.programming@gmail.com> wrote: > I was wondering, can you make a program the uses alot of classes do > the exact same thing with out useing classes? > _______________________________________________ > 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. From magoldfish at gmail.com Thu Mar 31 00:29:02 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Thu Mar 31 00:29:04 2005 Subject: [Tutor] a FIFO with fixed capacity? Message-ID: <5e183f3d050330142970d7d943@mail.gmail.com> I need to implement a FIFO with a fixed maximum capacity. Is there a name for such a beast? Also, I read two excellent cookbook recipes on FIFOs: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/210459 Would limiting the max capacity of the FIFO improve performance by allowing one to preallocate the FIFO buffer? All comments appreciated! Thanks, Marcus From python.programming at gmail.com Thu Mar 31 00:44:24 2005 From: python.programming at gmail.com (Kevin) Date: Thu Mar 31 00:44:27 2005 Subject: [Tutor] Class and methods? In-Reply-To: <013701c53569$9103c9f0$61cb8751@xp> References: <d082fff8050330083841cedec5@mail.gmail.com> <013701c53569$9103c9f0$61cb8751@xp> Message-ID: <d082fff805033014444abaa73e@mail.gmail.com> I am sorta starting to get it. So you could use __init__ to ask for a file name to see if there is one in a folder or not if there is then open that file and conitue where that file left off. If its not there create a new file with that name, then start the program? Or do I have that all wrong? Thanks Kevin On Wed, 30 Mar 2005 21:46:36 +0100, Alan Gauld <alan.gauld@freenet.co.uk> wrote: > > > In a class is every def called a method > > Strictly speaking only those that have a 'self' parameter(or > equivalent) > The others are "unbound functions" and pretty useless, usually being > the result of programmer errors!... > > > and the def __init__(self) is called the constructor method? > > Usually. > > > I don't have a problem writting a def I am still not clear on how to > > use a constructor. > > Use the constructor to initialise the attributes of your new instance. > When you create an instance by calling a class: > > instance = Class(a,b,c) > > what happens is that Python creates a blank instance of Class > then calls the __init__ method of the new instance passing in > the arguments you gave to the class, in our case a,b,c. > > [ If your class inherits from a superclass then its usually a > good idea to call the superclass init method inside your init > just to make sure the superclass attributes are all set up > properly too. ] > > > Is there a site that explains the constructor in > > great detail? > > Well I try... But it depends on how great a detail you want. "Great > detail" > implies "not easy to understand", in which case the definitive site is > the > Python documentation! > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > From maxnoel_fr at yahoo.fr Thu Mar 31 00:47:36 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Mar 31 00:47:41 2005 Subject: [Tutor] A simple question about creating a program In-Reply-To: <d082fff8050330130079b4c91b@mail.gmail.com> References: <d082fff8050330130079b4c91b@mail.gmail.com> Message-ID: <e268b8144f73d60e0100d5433a33a356@yahoo.fr> On Mar 30, 2005, at 23:00, Kevin wrote: > I was wondering, can you make a program the uses alot of classes do > the exact same thing with out useing classes? Yes. At some point, a program always has to be translated to machine code to be executed by the processor. Machine language is not object-oriented. It's not even procedural, or anything. Therefore, OO programming is just a more convenient way to write the code. Any program can be written in any (Turing-complete) programming language. -- Wild_Cat 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?" From dyoo at hkn.eecs.berkeley.edu Thu Mar 31 00:52:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 31 00:52:22 2005 Subject: [Tutor] A simple question about creating a program In-Reply-To: <d082fff8050330130079b4c91b@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503301425060.23553-100000@hkn.eecs.berkeley.edu> On Wed, 30 Mar 2005, Kevin wrote: > I was wondering, can you make a program the uses alot of classes do the > exact same thing with out useing classes? Hi Kevin, Yes. We can even do a lot of object oriented programming without classes, although it might be slightly painful. You asked an earlier question about constructors, so I'll try to flesh that out too. Let's use a small toy example. If we have a Person class: ###### class Person: def __init__(self, name): self.name = name self.friends = [] def addFriend(self, otherPerson): self.friends.append(otherPerson) def sayHelloToAll(self): for friend in self.friends: print "hi", friend.name, "it is I,", self.name ###### then we can just play with it: ###### >>> alan = Person("alan") >>> tim = Person("tim") >>> alan.addFriend(tim) >>> alan.sayHelloToAll() hi tim it is I, alan ###### But we can write fairly close code that just uses functions! ###### def makePerson(): return {'name': None, 'friends' : None} def initPerson(self, name): self['name'] = name self['friends'] = [] def addFriend(self, otherPerson): self['friends'].append(otherPerson) def sayHelloToAll(self): for friend in self['friends']: print "hi", friend['name'], "it is I,", self['name'] ###### Let's see how this might work: ###### >>> (kevin, danny, sean) = (makePerson(), makePerson(), makePerson()) >>> initPerson(kevin, "Kevin") >>> initPerson(danny, "Danny") >>> initPerson(sean, "Sean") >>> addFriend(kevin, danny) >>> addFriend(kevin, sean) >>> sayHelloToAll(kevin) hi Danny it is I, Kevin hi Sean it is I, Kevin ###### What's different here from the code with the explicit 'class' stuff is only mere appearance. Syntactially, it has the appearance of: verb(subject, object) If we were to use classes, things would look more like: subject.verb(object) which some people prefer to read. But it's a bit clunky to do this all by hand. As a concrete example, Python's class support automatically does stuff like makePerson() for us: we just have to write an appropriate initializer to shape the object the way we want. When we do something like this with Classes: ###### personUsingClasses = Person("Kevin") ###### we are actually doing two things: we first "construct" an object, and then we "initialize" it to fill the object in. In the function code above, we can see these two steps: ###### personUsingFunctions = makePerson() initPerson(personUsingFunctions, "Kevin") ###### It's a common idiom to do construct-and-init, since an uninitialized object is pretty useless, so Python's class support always does construction for us. This allows us to concentrate on the part that's really important to us --- the initializer. If we use Python's class support, stuff like this tends to be briefer and easier to read. So a little bit of Python's class support is syntax to make it nicer to write code that focuses on "objects". Does this make sense so far? From maxnoel_fr at yahoo.fr Thu Mar 31 01:01:13 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Mar 31 01:01:20 2005 Subject: [Tutor] Class and methods? In-Reply-To: <d082fff805033014444abaa73e@mail.gmail.com> References: <d082fff8050330083841cedec5@mail.gmail.com> <013701c53569$9103c9f0$61cb8751@xp> <d082fff805033014444abaa73e@mail.gmail.com> Message-ID: <69c0dfa940d3a8e8a6ec56f1b5438411@yahoo.fr> On Mar 31, 2005, at 00:44, Kevin wrote: > I am sorta starting to get it. So you could use __init__ to ask for a > file name to see if there is one in a folder or not if there is then > open that file and conitue where that file left off. If its not there > create a new file with that name, then start the program? Or do I have > that all wrong? > > Thanks > Kevin Not exactly. By the time you instantiate a class, the program has already started. Let's take an example: an Image class. It contains all the stuff needed to load, display, modify and save an image. These are the load(), display() and save() methods, for example. If you want to load an image from a file and display it somewhere on the screen, what you would do is the following: myImage = Image() # Creates a "blank" image myImage.load("test.jpg") # Load the image from test.jpg myImage.display(100, 100) # Displays the image at the position (100, 100) Now, loading an image from the disk is actually a very common operation with this class -- creating a blank image would probably be the exception rather than the rule. Therefore, it makes sense to define a __init__() method like this: def __init__(self, fileName=None): if fileName == None: # Create a blank image... else: self.load(fileName) __init__() is the method that's called with the arguments you supply when instantiating the class. Since it is defined, you can now instantiate the class with an argument: myImage1 = Image("test.jpg") # Creates an image from the file "test.jpg" myImage2 = Image() # Creates a blank image Get the idea? -- 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?" From jfouhy at paradise.net.nz Thu Mar 31 01:04:35 2005 From: jfouhy at paradise.net.nz (jfouhy@paradise.net.nz) Date: Thu Mar 31 01:04:43 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <BAY20-F12BE920DB363A5DE5C03B9B3460@phx.gbl> References: <BAY20-F12BE920DB363A5DE5C03B9B3460@phx.gbl> Message-ID: <1112223875.424b3083469ed@www.paradise.net.nz> Quoting John Carmona <jeannot18@hotmail.com>: > Hi John, thanks for the reply. Hey John, Please reply to the list, rather than to people directly. Clicking "reply to all" is probably what you want. > Ok No. 1, I have read about "ctime" which convert a time expressed in > seconds since the epoch to a string representing local time Nah, it's much, much simpler than that. time.time just returns a floating point number. How do you convert a number into a string? > No. 3 why do I need to convert them into an integer, if I manage to get > the last 2 character this will be a whole number, no? Programming languages differentiate between numbers and strings. 32 is a number; you can do computations with it (add, multply, etc). "32" is a string; this means it is the character "3" followed by the character "2". Python (and most other programming languages) treats them very differently. example: >>> x = 32 >>> x + 1 33 >>> x * 3 / 4 24 >>> s = "32" >>> s + "1" '321' >>> s + "foo" '32foo' You have to decide what you need. Your program compars numbers with the answer (your random number). In order to do this comparison, you need to have your answer as a number, not as a string. Hope this helps. -- John. From dprestes at atlas.ucpel.tche.br Thu Mar 31 04:19:21 2005 From: dprestes at atlas.ucpel.tche.br (Diego Galho Prestes) Date: Thu Mar 31 01:07:08 2005 Subject: [Tutor] Sorting more than one list Message-ID: <1112235561.1983.7.camel@rossum> Hi! I need to sort 4 lists but I need that they make the "sort together". I'll sort just one but when I change the position of the items of the 1st list I have to change the positions of the other 3 lists. Can I do this just using the sort() method of the list object? If I can't, someone know a site that have one sort method in python that its easily to implement and fast? Tks, Diego From cyresse at gmail.com Thu Mar 31 01:20:06 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Mar 31 01:20:10 2005 Subject: [Tutor] Re: [Pythoncard-users] childWindow.Raise() works on Windows, not on Mac In-Reply-To: <OF22B18AA8.8A41DC36-ON86256FD4.007E4CDF-86256FD4.007EA5B0@omsdal.com> References: <f2ff2d05032113555926183e@mail.gmail.com> <OF22B18AA8.8A41DC36-ON86256FD4.007E4CDF-86256FD4.007EA5B0@omsdal.com> Message-ID: <f2ff2d05033015205f6662f3@mail.gmail.com> Hi Brad, AFAIK, and Kevin Altis will no doubt correct me if I'm wrong... Class Parent(model.Background): def on_button1_mouseClick(self, event): x = model.ChildWindow(self, child.Child) x.id_emp = 20 Class Child(model.Background) def on_initialize(self, event): self.getClient(self.id_emp) So, from what I understand, the event queue would go like this User clicks button1, a new event triggers, which runs the method. That method creates a new event, Child initialize. But, the initalise event waits in the queue until the on_button1_mouseClick finishes. So that method can take all the time in the world to do what it wants, and Child will only initialise when it's done. Which is why you need to thread GUI stuff that's waits a long time for something to return to avoid 'hanging', because the screen won't repaint (which is an event) until the prior event triggered method finishes. Make sense? If it doesn't, let me know. Regards, Liam Clarke On Wed, 30 Mar 2005 17:03:19 -0600, brad.allen@omsdal.com <brad.allen@omsdal.com> wrote: > > I have a question about this approach. It does work, but I don't understand > it as well > as I'd like and I worry that it depends too much on timing. When does the > child > window's on_initialize run? What if on a really fast computer it runs before > the > childWindow.id_emp is bound? > > > pythoncard-users-admin@lists.sourceforge.net wrote on 03/21/2005 03:55:47 > PM: > > > > Hi Brad, > > > > You need to put the raise method in a method of the childWindow. > > I'm on XP, and calling the childWindow's raise method from the > > originating method as above never works for me. > > > > i.e. > > > > def on_empMultiColumnList_itemActivated(self, event): > > #Do stuff to derive id_emp > > childWindow = model.childWindow(self, empDetail.bgEmpDetail) > > childWindow.id_emp = id_emp > > > > > > and in empDetail - > > > > class bgEmpDetail(model.Background): > > def on_initialise(self, event): > > #This will need explaining > > self.popuulateFields(self.id_emp) > > self.Raise() > > > > See, what happens is that when a child window is created, the method > > that created finishes before the child window's on_initialise gets > > called. > > > > At the mo, my thing with childWindow.id_emp = id_emp is the only way > > of passing other parameters to the on_initialise() method. > > > > So, you can pass the parameters in, and then your child windows > > initialisation can act on them. > > > > And, sticking Raise() in the child windows init method fixed your > > problem for me. > > > > > > I hope it helps. If it's confusing at all, let me know and I'll try > > and explanify further. > > > > > > Regards, > > > > Liam Clarke > > > > > > > > On Mon, 21 Mar 2005 11:11:40 -0600, brad.allen@omsdal.com > > <brad.allen@omsdal.com> wrote: > > > > > > The Raise method for a child window seems not to work on the Mac, but > does > > > work under Windows. On the Mac, the child window starts to pop in front > of > > > the parent window, but then it withdraws behind. From looking at > message > > > watcher, It's almost as if the second click in my doubleclick is > bringing > > > the parent window forward. > > > > > > Is there something else I should be doing other than Raise(), or is > this a > > > bug? > > > > > > Here is the method runs when I doubleclick my multicolumnlist: > > > > > > def on_empMultiColumnList_itemActivated(self, event): > > > """When an entry is double clicked""" > > > indexClicked = event.m_itemIndex > > > base = self.components > > > rows = base.empMultiColumnList.GetSelectedItems() > > > if len(rows) == 0: > > > return > > > print rows > > > id_emp = rows[0][0] > > > empDetail.id_emp = id_emp > > > self.detailWindow = > > > model.childWindow(self,empDetail.bgEmpDetail) > > > self.detailWindow.populateFields(id_emp) > > > self.detailWindow.Raise() > > > > > > > > > I'm running PythonCard .81, wxPython 2.5.4.1, Python 2.3, Mac OS > 10.3.8. > > > > > > > > > -- > > '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. > > > > > > ------------------------------------------------------- > > SF email is sponsored by - The IT Product Guide > > Read honest & candid reviews on hundreds of IT Products from real users. > > Discover which products truly live up to the hype. Start reading now. > > http://ads.osdn.com/?ad_id=6595&alloc_id=14396&op=click > > _______________________________________________ > > Pythoncard-users mailing list > > Pythoncard-users@lists.sourceforge.net > > https://lists.sourceforge.net/lists/listinfo/pythoncard-users > -- '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. From maxnoel_fr at yahoo.fr Thu Mar 31 01:20:15 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Mar 31 01:20:20 2005 Subject: [Tutor] Sorting more than one list In-Reply-To: <1112235561.1983.7.camel@rossum> References: <1112235561.1983.7.camel@rossum> Message-ID: <44e4ef6e49542a7cc725296adbb61675@yahoo.fr> On Mar 31, 2005, at 04:19, Diego Galho Prestes wrote: > Hi! > > I need to sort 4 lists but I need that they make the "sort together". > I'll sort just one but when I change the position of the items of the > 1st list I have to change the positions of the other 3 lists. Can I do > this just using the sort() method of the list object? > If I can't, someone know a site that have one sort method in python > that > its easily to implement and fast? > > Tks, > Diego You can do that with zip(). >>> zip([1, 2, 3], [3, 2, 1]) [(1, 3), (2, 2), (3, 1)] It works with any number of lists. If you put the list you want to sort against as the first argument to zip, all you have to do is to then sort() the resulting list of tuples, and to "unzip" it, which should be trivial. >>> a = zip([3, 2, 1], [1, 2, 3]) >>> a [(3, 1), (2, 2), (1, 3)] >>> a.sort() >>> a [(1, 3), (2, 2), (3, 1)] -- 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?" From kent37 at tds.net Thu Mar 31 01:28:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 31 01:28:57 2005 Subject: [Tutor] Sorting more than one list In-Reply-To: <1112235561.1983.7.camel@rossum> References: <1112235561.1983.7.camel@rossum> Message-ID: <424B3635.40303@tds.net> Diego Galho Prestes wrote: > Hi! > > I need to sort 4 lists but I need that they make the "sort together". > I'll sort just one but when I change the position of the items of the > 1st list I have to change the positions of the other 3 lists. Can I do > this just using the sort() method of the list object? You can zip the lists together into a single list of 4-tuples. Sort this list and then use zip() again to create the three original lists. Here is an example using just three lists: >>> a=[2,1,4,3] >>> b=[1,2,3,4] >>> c=[5,6,7,8] >>> together = zip(a,b,c) >>> together [(2, 1, 5), (1, 2, 6), (4, 3, 7), (3, 4, 8)] >>> together.sort() >>> together [(1, 2, 6), (2, 1, 5), (3, 4, 8), (4, 3, 7)] >>> a,b,c = zip(*together) >>> a (1, 2, 3, 4) >>> b (2, 1, 4, 3) >>> c (6, 5, 8, 7) But I would consider just keeping the list of 4-tuples as your primary data structure instead of keeping four parallel lists. Kent From bvande at po-box.mcgill.ca Thu Mar 31 01:28:51 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Mar 31 01:29:19 2005 Subject: [Tutor] Sorting more than one list In-Reply-To: <1112235561.1983.7.camel@rossum> References: <1112235561.1983.7.camel@rossum> Message-ID: <424B3633.1070807@po-box.mcgill.ca> Diego Galho Prestes said unto the world upon 2005-03-30 21:19: > Hi! > > I need to sort 4 lists but I need that they make the "sort together". > I'll sort just one but when I change the position of the items of the > 1st list I have to change the positions of the other 3 lists. Can I do > this just using the sort() method of the list object? > If I can't, someone know a site that have one sort method in python that > its easily to implement and fast? > > Tks, > Diego > Hi Diego, I'm not quite following your question. Why can't you just sort each list one at a time? Is it that you want a quick way to do that all at once, rather than writing 4 separate sort statements? If that is what you need, perhaps this helps?: >>> def bulk_sort(*lists): for a_list in lists: a_list.sort() >>> list_1 = [3, 2, 5, 7, 1] >>> list_2 = [4, 3, 7, 2] >>> list_3 = [3, 2, 1] >>> bulk_sort(list_1, list_2, list_3) >>> list_1 [1, 2, 3, 5, 7] >>> list_2 [2, 3, 4, 7] >>> list_3 [1, 2, 3] >>> If that's not what you meant, perhaps you can clarify your desire? HTH, Brian vdB From bvande at po-box.mcgill.ca Thu Mar 31 01:42:05 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Mar 31 01:42:21 2005 Subject: [Tutor] Sorting more than one list In-Reply-To: <424B3633.1070807@po-box.mcgill.ca> References: <1112235561.1983.7.camel@rossum> <424B3633.1070807@po-box.mcgill.ca> Message-ID: <424B394D.4010708@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2005-03-30 18:28: > Diego Galho Prestes said unto the world upon 2005-03-30 21:19: > >> Hi! >> >> I need to sort 4 lists but I need that they make the "sort together". >> I'll sort just one but when I change the position of the items of the >> 1st list I have to change the positions of the other 3 lists. Can I do >> this just using the sort() method of the list object? >> If I can't, someone know a site that have one sort method in python that >> its easily to implement and fast? >> >> Tks, Diego >> > > Hi Diego, > > I'm not quite following your question. Why can't you just sort each list > one at a time? Is it that you want a quick way to do that all at once, > rather than writing 4 separate sort statements? <SNIP code to do something else> > If that's not what you meant, perhaps you can clarify your desire? > > HTH, > > Brian vdB I see from Kent and Max's replies that the question was clear, but at least one reader wasn't. Oops. :-) Brian From jeannot18 at hotmail.com Thu Mar 31 01:43:12 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu Mar 31 01:43:16 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <1112223875.424b3083469ed@www.paradise.net.nz> Message-ID: <BAY20-F40858E478B7A01705CCCAFB3460@phx.gbl> John, Thanks firstly to point about emailing back using the "Reply to all" option. Thanks also about the explanation about the difference about the difference between 32 and "32", being a number and a string respectively, your explanation was very clear (you can see now my level in programming, but it is what I like about it, learning so much every day). Ok your explanation make a bit more sense to my problem but I am not here just now. It probably will take me some effort to work it out. Cheers JC From kent37 at tds.net Thu Mar 31 01:56:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 31 01:56:25 2005 Subject: [Tutor] Launching a file browser In-Reply-To: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> Message-ID: <424B3CA7.9010906@tds.net> Mike Hall wrote: > I looked over the global module index and the closest thing I could find > relating to my os (osx) was EasyDialogs, which has a few functions > pertaining to this, "AskFileForOpen()" being one. Calling any function > within EasyDialogs however yields an Apple Event error: > > AE.AEInteractWithUser(50000000) > MacOS.Error: (-1713, 'no user interaction is allowed') It's been too long since I used Python on MacOSX, but IIRC you can't just run a Python GUI program from the shell. Or something like that...you should ask this one on the python-mac SIG mailing list: http://www.python.org/sigs/pythonmac-sig/ Kent From oasf2004 at yahoo.com Thu Mar 31 06:08:58 2005 From: oasf2004 at yahoo.com (Hoffmann) Date: Thu Mar 31 06:09:03 2005 Subject: [Tutor] What is the best book to start? In-Reply-To: 6667 Message-ID: <20050331040859.6589.qmail@web60008.mail.yahoo.com> Hi All, I am starting to studying Python. I have some previous experience with C (beginner level). Could, anyone, please, suggest a good Python book? I have both "Learning Python" by Lutz & Ascher, and "Python How to Program" by Deitel and others. Are those good books? Thanks. Hoffmann __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From leec03273 at mac.com Thu Mar 31 06:30:11 2005 From: leec03273 at mac.com (Lee Cullens) Date: Thu Mar 31 06:30:25 2005 Subject: [Tutor] What is the best book to start? In-Reply-To: <20050331040859.6589.qmail@web60008.mail.yahoo.com> References: <20050331040859.6589.qmail@web60008.mail.yahoo.com> Message-ID: <682de3f2ee009b076423b148821e2bee@mac.com> I can only comment on what I know and I have the O'Reilly Python series which begins with the "Learning Python" book you have (if you have the 2nd ed.). Just getting started with Python myself. The first book has gone quite fast, but then I'm a retired software engineer. Even so, I think it would be very good for someone with limited programming experience. Now get your nose back in that book :~) Lee C On Mar 30, 2005, at 11:08 PM, Hoffmann wrote: > Hi All, > > I am starting to studying Python. I have some previous > experience with C (beginner level). Could, anyone, > please, suggest a good Python book? I have both > "Learning Python" by Lutz & Ascher, and "Python How to > Program" by Deitel and others. Are those good books? > Thanks. > Hoffmann > From python at bernardlebel.com Thu Mar 31 06:36:13 2005 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Mar 31 06:34:19 2005 Subject: [Tutor] What is the best book to start? In-Reply-To: <20050331040859.6589.qmail@web60008.mail.yahoo.com> References: <20050331040859.6589.qmail@web60008.mail.yahoo.com> Message-ID: <424B7E3D.4030103@bernardlebel.com> Hoffmann wrote: > Hi All, > > I am starting to studying Python. I have some previous > experience with C (beginner level). Could, anyone, > please, suggest a good Python book? I have both > "Learning Python" by Lutz & Ascher, and "Python How to > Program" by Deitel and others. Are those good books? > Thanks. > Hoffmann I have only the former, and am totally happy with it. Very clear and well put book. A great investment. Cheers Bernard From kenneth.gomez at gmail.com Thu Mar 31 06:38:59 2005 From: kenneth.gomez at gmail.com (Kenneth Gomez) Date: Thu Mar 31 06:39:07 2005 Subject: [Tutor] What is the best book to start? In-Reply-To: <424B7E3D.4030103@bernardlebel.com> References: <20050331040859.6589.qmail@web60008.mail.yahoo.com> <424B7E3D.4030103@bernardlebel.com> Message-ID: <e5d26c3c0503302038789d07de@mail.gmail.com> I have the Deitel book. Good book. I think you have two good books. Start with one and digest it. -KBG- On Wed, 30 Mar 2005 23:36:13 -0500, Bernard Lebel <python@bernardlebel.com> wrote: > Hoffmann wrote: > > Hi All, > > > > I am starting to studying Python. I have some previous > > experience with C (beginner level). Could, anyone, > > please, suggest a good Python book? I have both > > "Learning Python" by Lutz & Ascher, and "Python How to > > Program" by Deitel and others. Are those good books? > > Thanks. > > Hoffmann > > I have only the former, and am totally happy with it. Very clear and > well put book. A great investment. > > Cheers > Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Cheers, Kenneth Gomez. http://www.kgomez.com "Sometimes I get the feeling that GOD has pets and I am not one of them" From garnaez at gmail.com Thu Mar 31 07:05:19 2005 From: garnaez at gmail.com (gerardo arnaez) Date: Thu Mar 31 07:05:31 2005 Subject: [Tutor] What is the best book to start? In-Reply-To: <20050331040859.6589.qmail@web60008.mail.yahoo.com> References: <20050331040859.6589.qmail@web60008.mail.yahoo.com> Message-ID: <148eea7105033021057544da2f@mail.gmail.com> I really think alan gauld books, learning how to program is one of the best esp if you are new. On Wed, 30 Mar 2005 20:08:58 -0800 (PST), Hoffmann <oasf2004@yahoo.com> wrote: > Hi All, > > I am starting to studying Python. I have some previous > experience with C (beginner level). Could, anyone, > please, suggest a good Python book? I have both > "Learning Python" by Lutz & Ascher, and "Python How to > Program" by Deitel and others. Are those good books? > Thanks. > Hoffmann > > > __________________________________ > Do you Yahoo!? > Yahoo! Small Business - Try our new resources site! > http://smallbusiness.yahoo.com/resources/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From nbbalane at gmail.com Thu Mar 31 07:13:42 2005 From: nbbalane at gmail.com (jrlen balane) Date: Thu Mar 31 07:13:45 2005 Subject: [Tutor] how to setup gnu.py Message-ID: <2cad2090050330211349889b8f@mail.gmail.com> hi! i don't know if this is the proper forum but i'll ask anyway... how am i going to setup gnu.py(or gnuplot.py) gnuplot with python??? From cyresse at gmail.com Thu Mar 31 07:46:18 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Mar 31 07:46:23 2005 Subject: [Tutor] wxPython / Tkinter Grid Message-ID: <f2ff2d050330214613a10151@mail.gmail.com> Hi, I know a wxPython grid is totally different to a Tkinter grid, but is there a Tkinter equivalent of a wxPython grid? I'm finding wxPython to be fiddly and restrictive... 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. From maxnoel_fr at yahoo.fr Thu Mar 31 10:21:19 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Mar 31 10:21:23 2005 Subject: [Tutor] Launching a file browser In-Reply-To: <424B3CA7.9010906@tds.net> References: <255f091b34be789bfc3be0f547f860fd@critterpixstudios.com> <424B3CA7.9010906@tds.net> Message-ID: <fae3747750e1ec8befc4501fcd7e6579@yahoo.fr> On Mar 31, 2005, at 01:56, Kent Johnson wrote: > Mike Hall wrote: >> I looked over the global module index and the closest thing I could >> find relating to my os (osx) was EasyDialogs, which has a few >> functions pertaining to this, "AskFileForOpen()" being one. Calling >> any function within EasyDialogs however yields an Apple Event error: >> AE.AEInteractWithUser(50000000) >> MacOS.Error: (-1713, 'no user interaction is allowed') > > It's been too long since I used Python on MacOSX, but IIRC you can't > just run a Python GUI program from the shell. Or something like > that...you should ask this one on the python-mac SIG mailing list: > http://www.python.org/sigs/pythonmac-sig/ > > Kent You have to launch your script with pythonw, not with python. -- 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?" From dyoo at hkn.eecs.berkeley.edu Thu Mar 31 11:19:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 31 11:19:32 2005 Subject: [Tutor] a FIFO with fixed capacity? In-Reply-To: <5e183f3d050330142970d7d943@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503310049320.14511-100000@hkn.eecs.berkeley.edu> On Wed, 30 Mar 2005, Marcus Goldfish wrote: > I need to implement a FIFO with a fixed maximum capacity. Hi Marcus, Out of curiosity, why do you require a first-in-first-out queue with a maximum capacity? > Would limiting the max capacity of the FIFO improve performance by > allowing one to preallocate the FIFO buffer? Possibly, but at the cost of having a FIFO that can get full. Depending on the domain, this might be ok for you. But most programs suffer from hardcoded limits that really shouldn't have been hardcoded in the first place. You may want to see if having a queue with unlimited size is really a performance drag on your system: have you done any profiling yet? The second implementation that you quoted earlier: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/210459 is similar to a nicer one by Jeremy Fincher: ###### class ListSubclassFifo(list): __slots__ = ('back',) def __init__(self): self.back = [] def enqueue(self, elt): self.back.append(elt) def dequeue(self): if self: return self.pop() else: self.back.reverse() self[:] = self.back self.back = [] return self.pop() ###### (See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436) Since these implementations guarantee O(1) "constant" time access for a queue, even without a hardcoded bound limit, you aren't losing much. Can you use this implementation? Finally, there's a 'deque' in the 'collections' Standard Library module that you might be able to use: http://www.python.org/doc/lib/module-collections.html which also should define constant-time guarantees for insertion and removal. So you might just be able to use that, and not have to copy-and-paste any code at all. *grin* Best of wishes to you! From thomas.s.mark at gmail.com Thu Mar 31 15:49:09 2005 From: thomas.s.mark at gmail.com (Mark Thomas) Date: Thu Mar 31 15:49:11 2005 Subject: [Tutor] Cryptography Toolkit Message-ID: <7b9699030503310549339627df@mail.gmail.com> Does anyone have some examples on the use of A.M. Kuchling's Python Cryptography Toolkit? I've tried his examples but get "AttributeError" and "TypeError". What I'm trying to do is encrypt/decrypt a file. I'm using Python 2.3 on xp pro. Thanks -- _ ( ) Mark Thomas ASCII ribbon campaign X www.theswamp.org - against HTML email / \ From kent37 at tds.net Thu Mar 31 16:14:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 31 16:14:07 2005 Subject: [Tutor] Cryptography Toolkit In-Reply-To: <7b9699030503310549339627df@mail.gmail.com> References: <7b9699030503310549339627df@mail.gmail.com> Message-ID: <424C05AB.3030104@tds.net> Mark Thomas wrote: > Does anyone have some examples on the use of A.M. Kuchling's Python > Cryptography Toolkit? I've tried his examples but get "AttributeError" > and "TypeError". What I'm trying to do is encrypt/decrypt a file. I'm > using Python 2.3 on xp pro. If you post your code and the complete error message including the stack trace we may be able to help. Kent From thomas.s.mark at gmail.com Thu Mar 31 16:35:47 2005 From: thomas.s.mark at gmail.com (Mark Thomas) Date: Thu Mar 31 16:35:52 2005 Subject: [Tutor] Cryptography Toolkit In-Reply-To: <424C05AB.3030104@tds.net> References: <7b9699030503310549339627df@mail.gmail.com> <424C05AB.3030104@tds.net> Message-ID: <7b969903050331063563900cc2@mail.gmail.com> On Thu, 31 Mar 2005 09:14:03 -0500, Kent Johnson <kent37@tds.net> wrote: > If you post your code and the complete error message including the stack trace we may be able to help. > > Kent Thanks Ken I'm getting closer to making this work using the XOR cipher. Here's what I'm doing. <from python> from Crypto.Cipher import XOR obj_xor = XOR.new("string") str_encrypt = "encrypt this string" xored = obj_xor.encrypt(str_encrypt) xored '\x16\x1a\x11\x1b\x17\x17\x07T\x06\x01\x07\x14S\x07\x06\x1b\x07\t\x14' obj_xor.decrypt(xored) "bhxupds&oo`g'uou`z`" <== *confused by this output* </from python> Close but no cigar!! *grin* -- _ ( ) Mark Thomas ASCII ribbon campaign X www.theswamp.org - against HTML email / \ From ewald.ertl at hartter.com Thu Mar 31 17:07:14 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu Mar 31 17:07:19 2005 Subject: [Tutor] Number of socketdescriptors > 250 and open() failed with to many open files Message-ID: <20050331170714.00006899@sunray1> Hi! In a class derived from thread I open a socket-Connection to a remote Server. Here I start about 500 Thread's on a solaris-System. Sofar there is no problem, when the filedescriptorlimit is set high enough with ulimit -n. My Problem is, when a function in the class tries to open a regular file in the filesystem. Because of some limitations of the FILE-Structure ( in C ) it's not possible to open more files than 255. I think, that this is the problem here in python, when open() delivers "too many open files". In my C-Daemon I duplicated the socket-descriptors with fcntl to start after a offset with e.g. fcntl( socket, F_DUP, 100 ). And after this I use the new descriptor and close the old one. So there are everytime some descriptors below 255 ready for opening regular files. I tried the same thing in python. socket.fileno() delivers the descriptor of the opened socket. The fcntl-Call in the module fcntl does also succeed. But after this I need a socket-Object for working on with the new filedescriptor. Constructing a new socket-Object with socket.fromfd() does not work, because this takes a new descriptor at the same low offset. Is there any possibility to get a socket-Object which uses the allready obtained filedescriptor from fcntl()? Thanks Ewald From alan.gauld at freenet.co.uk Thu Mar 31 18:37:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 31 18:37:30 2005 Subject: [Tutor] Float precision untrustworthy~~~ References: <000901c5340d$52bd6410$da5428cf@JSLAPTOP> <5d0204a1050330100579512ab8@mail.gmail.com> Message-ID: <017d01c5360f$f3e249b0$61cb8751@xp> > between binary and decimal representation. Just as a phrase that's > translated from English into Russian and then back to English again > can have its meaning shifted, Urban legend ,maybe but illustrates the point well: An early language translator app was fed 'Out of sight, out of mind' and then the result fed back in for reverse translation. The output was: 'Invisible, lunatic' :-) Alan G. From alan.gauld at freenet.co.uk Thu Mar 31 18:32:03 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 31 18:38:17 2005 Subject: [Tutor] Class and methods? References: <d082fff8050330083841cedec5@mail.gmail.com> <013701c53569$9103c9f0$61cb8751@xp> <d082fff805033014444abaa73e@mail.gmail.com> Message-ID: <016101c5360f$2c2f16a0$61cb8751@xp> > I am sorta starting to get it. So you could use __init__ to ask for a > file name to see if there is one in a folder or not if there is then > open that file and conitue where that file left off. If its not there > create a new file with that name, then start the program? Or do I have > that all wrong? There is nothing to stop you doing that, but in general init should not include interactive operations. It would be better to capture the filemname before creating the object and pass the filename into init as a parameter. Once inside init you can check if the filename is valid and either open the file or issue an error(raise an exception maybe?) or open a default filename instead, whatever you like. init is just a normal method except that it gets called first and is *intended* to initialise the internal attributes of the object. I'm not sure what you mean by "start the program", in general, after init completes, your program will continue from where you created the object. class C: def __init__(self, val): self.val = val print 'finished initialising' def main(): # my main program... v = int(raw_input('Type a number> ')) c = C(v) # pass in the value for n in range(c.val): print 'hello there' main() So programme flow here is that we call main(), main calls C(v) which internally calls C.__Init__(c,v) We then return to main() to print out the hello messages and terminate HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Mar 31 18:41:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 31 18:41:19 2005 Subject: [Tutor] I am puzzled - help needed References: <BAY20-F162E3C9EADCC828881CF54B3460@phx.gbl> Message-ID: <018401c53610$7a1f3790$61cb8751@xp> > exercise. I need to rewrite the high_low.py program (see below) to use the > last two digits of time at that moment to be the "random number". This is > using the import time module. > > I just can't work out how to do that, I have been looking at it for the past > 2,5 hours but can't break it. Has anyone done it in order for me to study > it. > There are several ways, one is to convert the time number into a string and then extract the last two digits and convert back to a number. n = time.time() s = str(n) ran = s[-2:] # last two characters of the string ran = int(ran) # convert back to a number Another option is to divide by 100 and take the remainder... HTH, Alan G. From magoldfish at gmail.com Thu Mar 31 20:22:04 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Thu Mar 31 20:22:12 2005 Subject: [Tutor] a FIFO with fixed capacity? In-Reply-To: <Pine.LNX.4.44.0503310049320.14511-100000@hkn.eecs.berkeley.edu> References: <5e183f3d050330142970d7d943@mail.gmail.com> <Pine.LNX.4.44.0503310049320.14511-100000@hkn.eecs.berkeley.edu> Message-ID: <5e183f3d05033110226516a560@mail.gmail.com> Danny, Thanks for the informative response. After I sent the email I realized that a circular buffer is a FIFO with fixed capacity, and that is what I want to implement. I think I recall seeing a recipe in the Python Cookbook (1st). If you or anyone else know of other recipes/implementations please let me know so I can save on the cut-and-paste. :) Marcus ps -- as for the need for a circular buffer vs. FIFO: I think my dsp background pushed me toward the CB. My app involves data acquisition for extended periods of time. I can't grow the FIFO infinitely, but it is no big deal if a few samples get overwritten. Does this make sense? On Thu, 31 Mar 2005 01:19:24 -0800 (PST), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Wed, 30 Mar 2005, Marcus Goldfish wrote: > > > I need to implement a FIFO with a fixed maximum capacity. > > Hi Marcus, > > Out of curiosity, why do you require a first-in-first-out queue with a > maximum capacity? > > > > Would limiting the max capacity of the FIFO improve performance by > > allowing one to preallocate the FIFO buffer? > > Possibly, but at the cost of having a FIFO that can get full. Depending > on the domain, this might be ok for you. But most programs suffer from > hardcoded limits that really shouldn't have been hardcoded in the first > place. You may want to see if having a queue with unlimited size is > really a performance drag on your system: have you done any profiling yet? > > The second implementation that you quoted earlier: > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/210459 > > is similar to a nicer one by Jeremy Fincher: > > ###### > class ListSubclassFifo(list): > __slots__ = ('back',) > def __init__(self): > self.back = [] > def enqueue(self, elt): > self.back.append(elt) > def dequeue(self): > if self: > return self.pop() > else: > self.back.reverse() > self[:] = self.back > self.back = [] > return self.pop() > ###### > > (See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436) > > Since these implementations guarantee O(1) "constant" time access for a > queue, even without a hardcoded bound limit, you aren't losing much. Can > you use this implementation? > > Finally, there's a 'deque' in the 'collections' Standard Library module > that you might be able to use: > > http://www.python.org/doc/lib/module-collections.html > > which also should define constant-time guarantees for insertion and > removal. So you might just be able to use that, and not have to > copy-and-paste any code at all. *grin* > > Best of wishes to you! > > From jeannot18 at hotmail.com Thu Mar 31 20:58:53 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu Mar 31 20:58:57 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <018401c53610$7a1f3790$61cb8751@xp> Message-ID: <BAY20-F300C8C7422DBBFD120C3C6B3470@phx.gbl> Alan and John thanks for the help. I have now this bit of script but it is not running. ---------------------------------------------------------------------------------------------------------- from time import * n = time() s = str(n) numb = s[-2:] # last two characters of the string numb = int(numb) # convert back to a number guess = (raw_input('Enter a number: ')) if guess == numb: print ("Bravo, you have just won the right to play again!") elif guess < numb: print "You are just a bit too low, try again" else: print "You are just a bit too high, try again" print "The End" ---------------------------------------------------------------------------------------------------------- If i write the following line: "n = time.time() I get the following error message: --------------------------------------------------------------------------------------------------- Traceback (most recent call last): File "C:/Python24/Example/high_lowtest.py", line 3, in -toplevel- n = time.time() AttributeError: 'builtin_function_or_method' object has no attribute 'time' -------------------------------------------------------------------------------------------------------- I feel like an idiot asking what is probably very basics questions but my desire to learn is quite high right now and I don't want to lose it, thanks again From kent37 at tds.net Thu Mar 31 21:02:03 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 31 21:02:06 2005 Subject: [Tutor] a FIFO with fixed capacity? In-Reply-To: <5e183f3d05033110226516a560@mail.gmail.com> References: <5e183f3d050330142970d7d943@mail.gmail.com> <Pine.LNX.4.44.0503310049320.14511-100000@hkn.eecs.berkeley.edu> <5e183f3d05033110226516a560@mail.gmail.com> Message-ID: <424C492B.5080604@tds.net> Marcus Goldfish wrote: > Danny, > > Thanks for the informative response. After I sent the email I > realized that a circular buffer is a FIFO with fixed capacity, and > that is what I want to implement. I think I recall seeing a recipe in > the Python Cookbook (1st). > > If you or anyone else know of other recipes/implementations please let > me know so I can save on the cut-and-paste. :) Here is a simple ring buffer implemented on top of deque: from collections import deque class ring_buffer(deque): def __init__(self, capacity): deque.__init__(self) assert capacity > 0 self.capacity = capacity def append(self, x): while len(self) >= self.capacity: self.popleft() deque.append(self, x) rb = ring_buffer(3) for i in range(5): rb.append(i) print list(rb) Kent > > Marcus > > ps -- as for the need for a circular buffer vs. FIFO: I think my dsp > background pushed me toward the CB. My app involves data acquisition > for extended periods of time. I can't grow the FIFO infinitely, but > it is no big deal if a few samples get overwritten. Does this make > sense? > > > On Thu, 31 Mar 2005 01:19:24 -0800 (PST), Danny Yoo > <dyoo@hkn.eecs.berkeley.edu> wrote: > >> >>On Wed, 30 Mar 2005, Marcus Goldfish wrote: >> >> >>>I need to implement a FIFO with a fixed maximum capacity. >> >>Hi Marcus, >> >>Out of curiosity, why do you require a first-in-first-out queue with a >>maximum capacity? >> >> >> >>>Would limiting the max capacity of the FIFO improve performance by >>>allowing one to preallocate the FIFO buffer? >> >>Possibly, but at the cost of having a FIFO that can get full. Depending >>on the domain, this might be ok for you. But most programs suffer from >>hardcoded limits that really shouldn't have been hardcoded in the first >>place. You may want to see if having a queue with unlimited size is >>really a performance drag on your system: have you done any profiling yet? >> >>The second implementation that you quoted earlier: >> >> >>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/210459 >> >>is similar to a nicer one by Jeremy Fincher: >> >>###### >>class ListSubclassFifo(list): >> __slots__ = ('back',) >> def __init__(self): >> self.back = [] >> def enqueue(self, elt): >> self.back.append(elt) >> def dequeue(self): >> if self: >> return self.pop() >> else: >> self.back.reverse() >> self[:] = self.back >> self.back = [] >> return self.pop() >>###### >> >>(See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68436) >> >>Since these implementations guarantee O(1) "constant" time access for a >>queue, even without a hardcoded bound limit, you aren't losing much. Can >>you use this implementation? >> >>Finally, there's a 'deque' in the 'collections' Standard Library module >>that you might be able to use: >> >> http://www.python.org/doc/lib/module-collections.html >> >>which also should define constant-time guarantees for insertion and >>removal. So you might just be able to use that, and not have to >>copy-and-paste any code at all. *grin* >> >>Best of wishes to you! >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Mar 31 21:19:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Mar 31 21:19:52 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <BAY20-F300C8C7422DBBFD120C3C6B3470@phx.gbl> References: <BAY20-F300C8C7422DBBFD120C3C6B3470@phx.gbl> Message-ID: <424C4D55.5080704@tds.net> You are just a little confused about imports. If I >>> import time then the name 'time' is bound to the time module: >>> time <module 'time' (built-in)> The time() function is an attribute of the time module: >>> time.time <built-in function time> >>> time.time() 1112296322.9560001 Alternatively, I can import the time function directly: >>> from time import time Now the name 'time' is bound to the time() function: >>> time <built-in function time> >>> time() 1112296332.8610001 and time.time gives an error: >>> time.time Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'builtin_function_or_method' object has no attribute 'time' When you say 'from time import *' that means bring *all* the names from the time module into the current namespace. It's like saying from time import accept2dyear from time import altzone from time import asctime ... from time import time ... so then when you try to access time.time you get the AttributeError. Kent John Carmona wrote: > Alan and John thanks for the help. I have now this bit of script but it > is not running. > > ---------------------------------------------------------------------------------------------------------- > > from time import * > > n = time() > s = str(n) > numb = s[-2:] # last two characters of the string > numb = int(numb) # convert back to a number > guess = (raw_input('Enter a number: ')) > > if guess == numb: > print ("Bravo, you have just won the right to play again!") > > elif guess < numb: > print "You are just a bit too low, try again" > > else: > print "You are just a bit too high, try again" > > print "The End" > ---------------------------------------------------------------------------------------------------------- > > > If i write the following line: > "n = time.time() > > I get the following error message: > > --------------------------------------------------------------------------------------------------- > > Traceback (most recent call last): > File "C:/Python24/Example/high_lowtest.py", line 3, in -toplevel- > n = time.time() > AttributeError: 'builtin_function_or_method' object has no attribute 'time' > -------------------------------------------------------------------------------------------------------- > > I feel like an idiot asking what is probably very basics questions but > my desire to learn is quite high right now and I don't want to lose it, > thanks again > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeannot18 at hotmail.com Thu Mar 31 22:19:06 2005 From: jeannot18 at hotmail.com (John Carmona) Date: Thu Mar 31 22:19:10 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <424C4D55.5080704@tds.net> Message-ID: <BAY20-F32E0AFB3EA01BEED470958B3470@phx.gbl> Thanks Kent I kind of see what you are trying to explain to me, it makes it easier by trying the different combination. So even is I change the first line to >>>import time My script is still not working properly, I am obviously missing a statement somewhere, the script return: >>> Enter a number: 25 You are just a bit too high, try again The End >>> The script exits and don't give another try, could you enlight me in this one, thanks JC From dyoo at hkn.eecs.berkeley.edu Thu Mar 31 22:52:57 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 31 22:53:00 2005 Subject: [Tutor] I am puzzled - help needed In-Reply-To: <BAY20-F32E0AFB3EA01BEED470958B3470@phx.gbl> Message-ID: <Pine.LNX.4.44.0503311251310.30233-100000@hkn.eecs.berkeley.edu> > My script is still not working properly, I am obviously missing a > statement somewhere, the script return: > > >>> > Enter a number: 25 > You are just a bit too high, try again > The End > >>> > > The script exits and don't give another try, could you enlight me in > this one, thanks Hi John, What does your program look like now? Just copy-and-paste it in in your reply, and we can take a fresh look at it. From alan.gauld at freenet.co.uk Thu Mar 31 22:56:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 31 22:56:21 2005 Subject: [Tutor] A simple question about creating a program References: <d082fff8050330130079b4c91b@mail.gmail.com> Message-ID: <01a301c53634$1ca8c8f0$61cb8751@xp> > I was wondering, can you make a program the uses alot of classes do > the exact same thing with out useing classes? Yes you can always write a program without classes but it may be a lot more work and its likely to be a lot harder to maintain. Especially if its a big program. However if you use a language like Python its very difficult to write a program that doesn't use any classes because the built in types are clases, or objects. And many of the modules in the library have classes in them so you would need to reinvent all of that functionality yourself! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Mar 31 22:58:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 31 22:58:39 2005 Subject: [Tutor] a FIFO with fixed capacity? References: <5e183f3d050330142970d7d943@mail.gmail.com> Message-ID: <01ac01c53634$6edd66d0$61cb8751@xp> > Would limiting the max capacity of the FIFO improve performance by > allowing one to preallocate the FIFO buffer? In a language like C it would help but in Python there's not much likliehood of advantage. BUt if you were writing a C module to integrate with Python then yes it might be an idea to allow the size to be set. Alan G From alan.gauld at freenet.co.uk Thu Mar 31 23:07:18 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Mar 31 23:07:08 2005 Subject: [Tutor] A simple question about creating a program References: <d082fff8050330130079b4c91b@mail.gmail.com> <e268b8144f73d60e0100d5433a33a356@yahoo.fr> Message-ID: <01b301c53635$a034ab20$61cb8751@xp> Just to be picky... > code to be executed by the processor. Machine language is not > object-oriented. In some cases it is. The Rekursiv computer by Linn systems had a CPU that had an OO machine language which supported parallelism by exposing 'threads' as active objects at the machine code level. But if we leave experimental architectures aside and deal with the 99.99% of mainstream you are of coure correct :-) > It's not even procedural, or anything. And again some chips have been built with Forth as their native machine code (or more accurately with a FOrth intetpreter as their microcode) and it is procedural. And again such chips, while available commercially never exactly made it to mainstream. And if Sun ever get round to finishing their JVM on a chip we'll have a chip that is both OO and procedural! > Any program can be written in any (Turing-complete) programming > language. And again thats only true for algorithmically biased programs, event driven code integrated with the external environment needs to be more than simply Turing complete. A Turing complete language may have no I/O capability or interface to OS or hardware events, thus making event driven code impossible. But again I'm being picky, it must be the time of night! Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Mar 31 23:20:35 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Mar 31 23:20:43 2005 Subject: [Tutor] a FIFO with fixed capacity? In-Reply-To: <5e183f3d05033110226516a560@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0503311309260.30233-100000@hkn.eecs.berkeley.edu> > ps -- as for the need for a circular buffer vs. FIFO: I think my dsp > background pushed me toward the CB. My app involves data acquisition > for extended periods of time. I can't grow the FIFO infinitely, but it > is no big deal if a few samples get overwritten. Does this make sense? Hi Marcus, Let me make sure I understand. Let's imagine that we have such a CircularQueue, with methods: push(element) pop() isEmpty() Would the following test code capture how you expect the buffer to behave? ###### Warning, untested code, since I don't have a circular queue ###### implementation handy yet. *grin* Let's do some test-driven ###### development. ###### import unittest class TestCircularQueue(unittest.testCase): def testSimpleQueue(self): queue = CircularQueue(capacity=3) queue.push("a") queue.push("b") queue.push("c") self.assertEquals(False, queue.isEmpty()) self.assertEquals("a", queue.pop()) self.assertEquals("b", queue.pop()) self.assertEquals("c", queue.pop()) self.assertEquals(True, queue.isEmpty()) def testOverflowWrapsQueue(self): queue = CircularQueue(capacity=3) queue.push("a") queue.push("b") queue.push("c") queue.push("d") self.assertEquals("b", queue.pop()) self.assertEquals("c", queue.pop()) self.assertEquals("d", queue.pop()) self.assertEquals(True, queue.isEmpty()) ###### I'm writing this as a unit test so that we can concretely see if my understanding of the behavior is the same at the one you expect to see. Does this match? Best of wishes to you! From magoldfish at gmail.com Thu Mar 31 23:31:53 2005 From: magoldfish at gmail.com (Marcus Goldfish) Date: Thu Mar 31 23:31:59 2005 Subject: [Tutor] a FIFO with fixed capacity? In-Reply-To: <Pine.LNX.4.44.0503311309260.30233-100000@hkn.eecs.berkeley.edu> References: <5e183f3d05033110226516a560@mail.gmail.com> <Pine.LNX.4.44.0503311309260.30233-100000@hkn.eecs.berkeley.edu> Message-ID: <5e183f3d0503311331654c416@mail.gmail.com> > Let me make sure I understand. Let's imagine that we have such a > CircularQueue, with methods: > > push(element) > pop() > isEmpty() > > [example unittest code] Danny, Yes, it looks like that is a valid unittest for a circular buffer. An enhancement is to modify the accessors: push(element) --> push(sequence) pop() --> pop(N) If pushing caused an overwrite, the consumer could be notified, perhaps by an overwrite exception. Marcus