From idiot1 at netzero.net Wed Oct 1 00:42:13 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Oct 1 00:41:20 2003 Subject: [Tutor] Complaint about maximum recursion In-Reply-To: <3F7A06A0.1040200@pobox.com> References: <3F7A06A0.1040200@pobox.com> Message-ID: <3F7A5B25.1020401@netzero.net> well, off hand I would guess that the thing is exausting some preset limit on system resources, and the language kicked in to keep the computer from crashing. After 50 recursions, it ought to do something to terminate it! Now if it is definately going to terminate, and do it before the system barks and barfs, maybe there is a way to set the trigger level higher- or maybe this just means you need to go buy another stick of memory??? hmmm, I should write a recursive function in idle with no end with a printout of it's depth, and see how bad it gets before I have to reboot the box. Sort of a suicide mission, but intresting, and I got all my chores done today, so what the hell... Jonathan Hayward http://JonathansCorner.com wrote: > My script now gets this error on starting up. What is wrong if a 50-line > stack trace complains about excessive recursion? > > Traceback (most recent call last): > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 3878, in ? > multitasking.start_oracle() > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 2288, in start_oracle > server_init() > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 3802, in server_init > section.get_documents(1) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 2614, in get_documents > self.possibly_include_files_from_directory, "") > File "/usr/lib/python2.2/posixpath.py", line 287, in walk > walk(name, func, arg) > File "/usr/lib/python2.2/posixpath.py", line 279, in walk > func(arg, top, names) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 2681, in possibly_include_files_from_directory > self) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 857, in get_document > return webpage(filename, section) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 2805, in __init__ > document.__init__(self, filename, section) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 637, in __init__ > self.process() > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 808, in process > self.compute_title() > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 2948, in compute_title > self.title = self.get_tag_contents("title", self.get_file_contents()) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 763, in get_tag_contents > internal = self.get_tag_contents_internal(tag, file_contents) > File "/home/jonathan/creations/software/inventions/datamine/fathersd", > line 772, in get_tag_contents_internal > return my_re.findall(file_contents) > RuntimeError: maximum recursion limit exceeded > > > TIA, > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From idiot1 at netzero.net Wed Oct 1 00:53:58 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Oct 1 00:53:03 2003 Subject: [Tutor] rre: Recursion error Message-ID: <3F7A5DE6.8090207@netzero.net> Well, I tried this: def test(count): print count count=count+1 test(count) and when the count got to 346, I chickened out and hit ^C, and got a HUGE error report back. I will spare the list. But it went WELL past 50 recursions. Of course, this was a small and simple function, and did not tax the stack at all heavily per recursion. -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From thomi at imail.net.nz Wed Oct 1 00:56:51 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Wed Oct 1 00:56:59 2003 Subject: [Tutor] rre: Recursion error In-Reply-To: <3F7A5DE6.8090207@netzero.net> References: <3F7A5DE6.8090207@netzero.net> Message-ID: <200310011656.51453.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Wed, 01 Oct 2003 16:53, Kirk Bailey wrote: > Well, I tried this: > > def test(count): > print count > count=count+1 > test(count) > It might also be interesting to see how long it takes between recursions, and graph it...hmmm... might try this on an old 486.... ; ) - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/el6T2tSuYV7JfuERAp81AJ9qdx5HhQrcPGLdUzxecWIufBw4CQCePFc5 PnEdCj47ZZkBmlwcxrqSH8Y= =0Ic4 -----END PGP SIGNATURE----- From project5 at redrival.net Wed Oct 1 01:43:54 2003 From: project5 at redrival.net (Andrei) Date: Wed Oct 1 01:45:58 2003 Subject: [Tutor] Re: rre: Recursion error In-Reply-To: <3F7A5DE6.8090207@netzero.net> References: <3F7A5DE6.8090207@netzero.net> Message-ID: Kirk Bailey wrote: > Well, I tried this: > > def test(count): > print count > count=count+1 > test(count) Tried that only I do the count increase inside the function call. > and when the count got to 346, I chickened out and hit ^C, and got a Got up to 984, nothing interesting happens: 983 984 Traceback (most recent call last): File "", line 1, in ? File "", line 3, in test I don't have to wait at all, the traceback appears virtually instantaneously. I couldn't even stop it at 300 if I wanted to :). But that's in wxPython, perhaps Tk is slower and that's why you didn't get that far. The limit seems to be pretty much fixed, memory use is negligeable. > HUGE error report back. I will spare the list. But it went WELL past 50 > recursions. Of course, this was a small and simple function, and did not > tax the stack at all heavily per recursion. Tried more memory consuming test too: >>> class X(object): ... def __init__(self, i): ... self.list = [10,10,10,10,10,10,10,10,10,10]*i ... >>> def test(i): ... l.append(X(i)) ... print i ... test(i+1) ... >>> l = [] >>> test(0) >>> len(l[-1].list) 9850 Stops at 984 too, but eats about 22MB of mem. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From krier115 at student.liu.se Wed Oct 1 01:47:32 2003 From: krier115 at student.liu.se (Kristoffer Erlandsson) Date: Wed Oct 1 01:47:45 2003 Subject: [Tutor] Complaint about maximum recursion In-Reply-To: <3F7A06A0.1040200@pobox.com> References: <3F7A06A0.1040200@pobox.com> Message-ID: <20031001054732.GA14599@n14.ryd.student.liu.se> On Tue, Sep 30, 2003 at 11:41:36PM +0100, Jonathan Hayward http://JonathansCorner.com wrote: [snip] > line 772, in get_tag_contents_internal > return my_re.findall(file_contents) > RuntimeError: maximum recursion limit exceeded The problem here is that regular expressions with non-greedy qualifiers (*? etc) are implemented using recursion. Either try rewriting them to greedy ones, or if you are sure you are just exceeding the limit by a small amount you can use sys.setrecursionlimit(n) to increase the limit. sys.getrecursionlimit() shows you the current limit. 1000 by default on my system. Hope this helps a bit :) Regards, -- Kristoffer Erlandsson http://errl.info From mwagman at charter.net Wed Oct 1 06:40:52 2003 From: mwagman at charter.net (Mike Wagman) Date: Wed Oct 1 06:34:56 2003 Subject: [Tutor] Re: rre: Recursion error In-Reply-To: References: <3F7A5DE6.8090207@netzero.net> Message-ID: <1065004848.2862.1.camel@66-188-81-143.mad.wi.charter.com> I got up to 999 then got File "count.py", line 4, in test test(count) RuntimeError: maximum recursion depth exceeded On Wed, 2003-10-01 at 00:43, Andrei wrote: > Kirk Bailey wrote: > > > Well, I tried this: > > > > def test(count): > > print count > > count=count+1 > > test(count) > > Tried that only I do the count increase inside the function call. > > > and when the count got to 346, I chickened out and hit ^C, and got a > > Got up to 984, nothing interesting happens: > > 983 > 984 > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in test > > I don't have to wait at all, the traceback appears virtually instantaneously. I > couldn't even stop it at 300 if I wanted to :). But that's in wxPython, perhaps > Tk is slower and that's why you didn't get that far. The limit seems to be > pretty much fixed, memory use is negligeable. > > > HUGE error report back. I will spare the list. But it went WELL past 50 > > recursions. Of course, this was a small and simple function, and did not > > tax the stack at all heavily per recursion. > > Tried more memory consuming test too: > > >>> class X(object): > ... def __init__(self, i): > ... self.list = [10,10,10,10,10,10,10,10,10,10]*i > ... > >>> def test(i): > ... l.append(X(i)) > ... print i > ... test(i+1) > ... > >>> l = [] > >>> test(0) > > >>> len(l[-1].list) > 9850 > > Stops at 984 too, but eats about 22MB of mem. From amk at amk.ca Wed Oct 1 07:38:27 2003 From: amk at amk.ca (amk@amk.ca) Date: Wed Oct 1 07:38:33 2003 Subject: [Tutor] Complaint about maximum recursion In-Reply-To: <20031001054732.GA14599@n14.ryd.student.liu.se> References: <3F7A06A0.1040200@pobox.com> <20031001054732.GA14599@n14.ryd.student.liu.se> Message-ID: <20031001113827.GA24069@rogue.amk.ca> On Wed, Oct 01, 2003 at 07:47:32AM +0200, Kristoffer Erlandsson wrote: > greedy ones, or if you are sure you are just exceeding the limit by a > small amount you can use sys.setrecursionlimit(n) to increase the limit. No, this won't work. sys.setrecursionlimit() sets how deep Python code can recurse. The recursion inside the regex engine is in C code, and it uses a hard-wired limit (USE_RECURSION_LIMIT, set to 10000 on most platforms. --amk From ajstec at bol.com.br Wed Oct 1 11:35:17 2003 From: ajstec at bol.com.br (ajstec) Date: Wed Oct 1 11:41:18 2003 Subject: [Tutor] insert in postgresql Message-ID: Hi all, I am using pypgsql, and try : >>> a='cat' >>> b='dog' >>> db.query("insert into curso values (default,"%(a)","%(b)")") SyntaxError: invalid syntax Howto ? It? (Bye) ! Adilton Silva Recife - Brasil __________________________________________________________________________ Acabe com aquelas janelinhas que pulam na sua tela. AntiPop-up UOL - ? gr?tis! http://antipopup.uol.com.br/ From godoy at metalab.unc.edu Wed Oct 1 11:49:49 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Wed Oct 1 11:50:26 2003 Subject: [Tutor] insert in postgresql In-Reply-To: (ajstec@bol.com.br's message of "Wed, 1 Oct 2003 15:35:17 +0000") References: Message-ID: "ajstec" writes: > Hi all, > > I am using pypgsql, and try : > >>>> a='cat' >>>> b='dog' >>>> db.query("insert into curso values > (default,"%(a)","%(b)")") > SyntaxError: invalid syntax > > Howto ? > > It? (Bye) ! Ol? Adilton. :-) Muito calor por a?? You statement is wrong 'cause you're mixing the quotes. Try it like that: db.query("insert into curso values (default, %s, %s)" % (a, b)) If I got it correctly and 'default' is also a value and not a variable name. See you, -- Godoy. From bgailer at alum.rpi.edu Wed Oct 1 11:46:50 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Oct 1 12:13:19 2003 Subject: [Tutor] Efficient way to join files In-Reply-To: <3F7A3067.1000409@telgua.com.gt> References: <3F7A3067.1000409@telgua.com.gt> Message-ID: <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253> At 07:39 PM 9/30/2003, H?ctor Villafuerte D. wrote: >Hi all, >I need to join multiple files. >Is there a more efficient way to do it than using >fileinput.input(file) and looping through those files? >Thanks in advance, On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... destinationfile").read() Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003 From pythontutor at venix.com Wed Oct 1 12:19:30 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Oct 1 12:19:35 2003 Subject: [Tutor] conversion confusion In-Reply-To: References: Message-ID: <3F7AFE92.7030603@venix.com> int(value2add,16) requires that value2add be a string with characters from the set: 0123456789abcdefABCDEF It won't work with any old string, such as 'm'. The CRC equation doesn't work with strings, it works with integers. To turn a single character into its integer representation, python provides the ord function. CRCval = ord('m') ^ int(seed,16) You shouldn't need any hex values within your processing. Having said that, to turn the hex string '6d' into an integer, you'd use the int function: int('6d',16) which equals 109 ord('m') also equals 109 If you want to post the problem code, we can probably help. I'd expect your code should look something like: input_char = serial.get_a_character() # I made up the function name CRCval = ord(input_char) ^ int(seed,16) print "input_char(hex): %x CRC(hex): %x" % (input_char, CRCval) One other point. Your device documentation may show stuff in terms of C programming code. In C, 'm' is actually an integer not a string. So a C programmer can write: 'n' - 'm' and get a result of 1. In python, we'd write: ord('n') - ord('m') and also get 1. Hope this helps. Try giving us a code snippet if necessary. Stanfield, Vicki {D167~Indianapolis} wrote: > Well, I still can't get this to work right. It works fine when the value2add is a small number, but when it is an 'm' or some other letter, it doesn't work. If I fake it out and send the 'm' as a string representation of its hex value ('6d'), it will work. So the problem must be that after I hexlify the 'm', it is numeric rather than a string which is what the equation which follows wants. > > CRCval=int(value2add,16) ^ int(seed,16) > > How does one turn a hex number 6d into a string so that the equation will happily take it? I may be going about things strangely, but the value comes in as an 'm' and needs to be a string '6d'. How do I get from one to the other? > > --vicki > > P.S. I apologize if I am being dense here; some parts of this come easy and some with great difficulty. > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From hec.villafuerte at telgua.com.gt Wed Oct 1 14:58:29 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Wed Oct 1 12:58:15 2003 Subject: [Tutor] Efficient way to join files In-Reply-To: <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253> References: <3F7A3067.1000409@telgua.com.gt> <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253> Message-ID: <3F7B23D5.9010606@telgua.com.gt> Bob Gailer wrote: > On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... > destinationfile").read() hmmm, interesting... what a nice way to call DOS commands... Yes, I'm currently working in Windows, but I would like to make my code as platform independent as possible (I also use Linux... actually it's my favourite OS! but that's another story...) Thanks for your suggestions! From ajstec at bol.com.br Wed Oct 1 13:02:46 2003 From: ajstec at bol.com.br (ajstec) Date: Wed Oct 1 13:02:51 2003 Subject: [Tutor] insert in postgresql Message-ID: ---------- In?cio da mensagem original ----------- De: tutor-bounces@python.org Para: "ajstec" ajstec@bol.com.br Cc: "tutor" tutor@python.org Data: Wed, 01 Oct 2003 12:49:49 -0300 Assunto: Re: [Tutor] insert in postgresql > "ajstec" writes: > > > Hi all, > > > > I am using pypgsql, and try : > > > >>>> a='cat' > >>>> b='dog' > >>>> db.query("insert into curso values > > (default,"%(a)","%(b)")") > > SyntaxError: invalid syntax > > > > Howto ? > > > > It? (Bye) ! > > Ol? Adilton. :-) Muito calor por a?? > > > You statement is wrong 'cause you're mixing the quotes. > > Try it like that: > > db.query("insert into curso values (default, %s, %s)" % (a, b)) > > If I got it correctly and 'default' is also a value and not a variable > name. > > > See you, > -- > Godoy. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Oi, :-) s? 31 graus I tried diverse formats but ... db.query("insert into curso values (default,%s,%s)"%(a,b)) Traceback (most recent call last): File "", line 1, in ? db.query("insert into curso values (default,%s,%s)"%(a,b)) _pg.error: ERROR: Attribute "cat" not found Voc? ? brasileiro ? __________________________________________________________________________ Acabe com aquelas janelinhas que pulam na sua tela. AntiPop-up UOL - ? gr?tis! http://antipopup.uol.com.br/ From jeff at ccvcorp.com Wed Oct 1 13:25:10 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Oct 1 13:21:32 2003 Subject: [Tutor] Efficient way to join files References: <3F7A3067.1000409@telgua.com.gt> <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253> Message-ID: <3F7B0DF6.1020809@ccvcorp.com> Bob Gailer wrote: > At 07:39 PM 9/30/2003, H?ctor Villafuerte D. wrote: > >> Hi all, >> I need to join multiple files. >> Is there a more efficient way to do it than using >> fileinput.input(file) and looping through those files? >> Thanks in advance, > > > On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... > destinationfile").read() I think that it would be a bit of a stretch to call this "more efficient", at least if one thinks at all about the implementation of this code. (Maybe this just depends on one's definition of "efficiency"...) You are proposing, here, to get the OS to read all the files and append them to another (new) file, and then read in the new file. That's, at a minimum, an extra hard drive read and hard drive write for each of those files. Using fileinput, or otherwise looping through a list of files, doesn't do that. This solution may take fewer lines of code, but LoC count isn't necessarily related to real efficiency in any meaningful way. I would also say that it's more clear to state, in code, "take this list of files and process them one at a time, with this procedure..." than to state "Get someone else to collect all of these files and copy them into a new one, and then take that new file and do this..." It is simplest to write a procedure that pretends to be dealing with only a single file, to be sure. However, I think that the correct abstraction is to have a function that is passed a single file, and that deals with multiple files by getting them passed to it in sequence, rather than to write something that handles multiple files by squeezing them all together into an undifferentiated mass. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Wed Oct 1 14:05:57 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 1 14:06:10 2003 Subject: [Tutor] Complaint about maximum recursion In-Reply-To: <20031001054732.GA14599@n14.ryd.student.liu.se> Message-ID: On Wed, 1 Oct 2003, Kristoffer Erlandsson wrote: > On Tue, Sep 30, 2003 at 11:41:36PM +0100, Jonathan Hayward http://JonathansCorner.com wrote: > [snip] > > line 772, in get_tag_contents_internal > > return my_re.findall(file_contents) > > RuntimeError: maximum recursion limit exceeded > > The problem here is that regular expressions with non-greedy qualifiers > (*? etc) are implemented using recursion. Either try rewriting them to > greedy ones, or if you are sure you are just exceeding the limit by a > small amount you can use sys.setrecursionlimit(n) to increase the limit. > sys.getrecursionlimit() shows you the current limit. 1000 by default on > my system. Hi Jonathan, Yes, I agree with Kristoffer --- it looks like the regular expression is causing the recursion to overflow. It's a known problem: http://www.python.org/doc/current/lib/node108.html that occurs with nongreedy matching (*?). But in Python 2.3, the regular expression engine adjusted to handle certain situations in a way that won't break. Can you try using Python 2.3 and see if that clears up the problem? From dyoo at hkn.eecs.berkeley.edu Wed Oct 1 14:17:59 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 1 14:18:06 2003 Subject: [Tutor] Efficient way to join files In-Reply-To: <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253> Message-ID: On Wed, 1 Oct 2003, Bob Gailer wrote: > At 07:39 PM 9/30/2003, H=E9ctor Villafuerte D. wrote: > > >I need to join multiple files. Hi Hector, Do you need to do this physically, or can you just use an iterator on multiple files? If you can use an iterator, then the 'itertools' module will be useful: http://www.python.org/doc/current/lib/itertools-functions.html In particular, we can "chain" files together by doing something like this: ### """A small 'cat'-like utility that takes files from the command line, and prints them all.""" import itertools import sys files =3D map(open, sys.argv[1:]) all_files =3D itertools.chain(*files) for line in all_files: sys.stdout.write(line) ### But that being said, the 'fileinput' module does something like this already with its input() function! *grin* According to: http://www.python.org/doc/current/lib/module-fileinput.html fileinput.input() can take in a list of files. We can recode the above as: ### #!/usr/local/bin/python """A small 'cat'-like utility that takes files from the command line, and prints them all.""" import fileinput import sys all_files =3D fileinput.input(sys.argv[1:]) for line in all_files: sys.stdout.write(line) ### Please feel free to ask more questions. Good luck to you! From hec.villafuerte at telgua.com.gt Wed Oct 1 16:21:59 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Wed Oct 1 14:21:44 2003 Subject: [Tutor] Efficient way to join files In-Reply-To: <3F7B0DF6.1020809@ccvcorp.com> References: <3F7A3067.1000409@telgua.com.gt> <6.0.0.22.0.20031001093312.04a8b4e8@66.28.54.253> <3F7B0DF6.1020809@ccvcorp.com> Message-ID: <3F7B3767.1020907@telgua.com.gt> Jeff Shannon wrote: > Bob Gailer wrote: > >> On Windows? os.popen("copy sourcefile1 + sourcefile2 + ... >> destinationfile").read() > > > I think that it would be a bit of a stretch to call this "more > efficient", at least if one thinks at all about the implementation of > this code. (Maybe this just depends on one's definition of > "efficiency"...) > > You are proposing, here, to get the OS to read all the files and > append them to another (new) file, and then read in the new file. > That's, at a minimum, an extra hard drive read and hard drive write > for each of those files. Using fileinput, or otherwise looping > through a list of files, doesn't do that. This solution may take > fewer lines of code, but LoC count isn't necessarily related to real > efficiency in any meaningful way. > > I would also say that it's more clear to state, in code, "take this > list of files and process them one at a time, with this procedure..." > than to state "Get someone else to collect all of these files and copy > them into a new one, and then take that new file and do this..." > > It is simplest to write a procedure that pretends to be dealing with > only a single file, to be sure. However, I think that the correct > abstraction is to have a function that is passed a single file, and > that deals with multiple files by getting them passed to it in > sequence, rather than to write something that handles multiple files > by squeezing them all together into an undifferentiated mass. I was reading that there is a Python Profiler! I'll take a look at it and post which method resulted "more efficient". This language is really nice! Pardon my excitement, but before Python I only knew C/C++, assembler for PIC's and VB (which I didn't like) This is my second week with python and I have a strong feeling that this relationship will be a long one ;) From missive at hotmail.com Wed Oct 1 17:50:28 2003 From: missive at hotmail.com (Lee Harr) Date: Wed Oct 1 17:50:34 2003 Subject: [Tutor] Re: insert in postgresql Message-ID: >>>a='cat' >>>b='dog' >>>db.query("insert into curso values (default,"%(a)","%(b)")")^M SyntaxError: invalid syntax In python, the single(') and double(") quotes are interchangeable, and either one can be used to make a triple(""") quote. This is useful, because a single quote string can contain double quotes and vice versa. A triple quoted string can contain either one. I would do it like this: a = 'cat' b = 'dog' q = """insert into cursor values (default '%(a)s', '%(b)s')""" % vars() db.query(q) One nice thing about triple quotes is that they can contain newlines: q = """ INSERT INTO cursor (foo, bar, baz) VALUES (default, '%(a)s', '%(b)s') """ % vars() Note that it is always a good idea to include the fields you are inserting into just in case your db structure changes in the future. _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From amonroe at columbus.rr.com Wed Oct 1 19:52:59 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Oct 1 19:53:08 2003 Subject: [Tutor] mailing list archive reader In-Reply-To: References: Message-ID: <39359930883.20031001195259@columbus.rr.com> > is there a program that can read the mailing list archives from a > local flie and format them like the online options (ie date, thread, > author). i downloaded each months archies but the seem to be huge > flat files with alot of repition for threads. i looked into mailman Check out www.gmane.org You can read the mailing list with a newsreader. Alan From godoy at metalab.unc.edu Wed Oct 1 22:34:47 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Wed Oct 1 22:35:19 2003 Subject: [Tutor] insert in postgresql In-Reply-To: (ajstec@bol.com.br's message of "Wed, 1 Oct 2003 17:02:46 +0000") References: Message-ID: "ajstec" writes: > Oi, :-) s? 31 graus Bem mais quente que em Curitiba. > I tried diverse formats but ... > > db.query("insert into curso values (default,%s,%s)"%(a,b)) > Traceback (most recent call last): > File "", line 1, in ? > db.query("insert into curso values > (default,%s,%s)"%(a,b)) > _pg.error: ERROR: Attribute "cat" not found > See that you have a '^M' char there. You've probably pressed ENTER in the middle of the string. To use newlines you have to use triple quotes (either single or double quotes). An example was provided in a previous message. > Voc? ? brasileiro ? Yes, I'm Brazilian. :-) Living in the South, though. :-) -- Godoy. From ronan at melim.com.br Thu Oct 2 16:52:12 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Thu Oct 2 16:51:10 2003 Subject: [Tutor] Copy files Message-ID: <200310021752.12721.ronan@melim.com.br> Hello, Is there some python function to make a copy of a file? I'd like to do it as with a native function like os.unlink, os.mkdir, but I'm not finding a function that do it. Thanks Ronan From project5 at redrival.net Thu Oct 2 17:09:54 2003 From: project5 at redrival.net (Andrei) Date: Thu Oct 2 17:10:56 2003 Subject: [Tutor] Re: Copy files In-Reply-To: <200310021752.12721.ronan@melim.com.br> References: <200310021752.12721.ronan@melim.com.br> Message-ID: > Is there some python function to make a copy of a file? > > I'd like to do it as with a native function like os.unlink, > os.mkdir, but I'm not finding a function that do it. Look at the shutil module. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From Christian.Zandbergen at swisslife.ch Fri Oct 3 06:09:59 2003 From: Christian.Zandbergen at swisslife.ch (Zandbergen Christian) Date: Fri Oct 3 06:10:07 2003 Subject: [Tutor] Window pathnames Message-ID: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch> Hi I try to open a file with python 2.1.3 (deployed with Zope) and the following Error occures: Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. >>> open("C:\\dslfjsl\jlsfjslfsj") Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'C:\\dslfjsl\\jlsfjslfsj' It seems that one backslash always returns a double backslash. With Python 2.3 it's OK. But since I want it to used in conjunction with Zope I have to stick to Python 2.1.3 or not ...... Christian From gerrit at nl.linux.org Fri Oct 3 06:12:05 2003 From: gerrit at nl.linux.org (Gerrit Holl) Date: Fri Oct 3 06:12:24 2003 Subject: [Tutor] Window pathnames In-Reply-To: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch> References: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch> Message-ID: <20031003101205.GA24665@nl.linux.org> > and the following Error occures: > > Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on > win32 > Type "copyright", "credits" or "license" for more information. > >>> open("C:\\dslfjsl\jlsfjslfsj") > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 2] No such file or directory: > 'C:\\dslfjsl\\jlsfjslfsj' > > > It seems that one backslash always returns a double backslash. Have you tried to prepend the string with 'r' (e.g. r'C:\aaa\bbb')? Gerrit. -- Mozilla _is_ the web: it grows faster than you can download it. 1011001 1101111 1110101 1110010 1110011 0101100 1000111 1100101 1110010 1110010 1101001 1110100 From project5 at redrival.net Fri Oct 3 06:19:31 2003 From: project5 at redrival.net (Andrei) Date: Fri Oct 3 06:21:36 2003 Subject: [Tutor] Re: Window pathnames In-Reply-To: <20031003101205.GA24665@nl.linux.org> References: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch> <20031003101205.GA24665@nl.linux.org> Message-ID: Gerrit Holl wrote: > > >>and the following Error occures: >> >> Python 2.1.3 (#35, Apr 8 2002, 17:47:50) [MSC 32 bit (Intel)] on >>win32 >> Type "copyright", "credits" or "license" for more information. >> >>> open("C:\\dslfjsl\jlsfjslfsj") >> Traceback (most recent call last): >> File "", line 1, in ? >> IOError: [Errno 2] No such file or directory: >>'C:\\dslfjsl\\jlsfjslfsj' >> >> >>It seems that one backslash always returns a double backslash. > > > > Have you tried to prepend the string with 'r' (e.g. r'C:\aaa\bbb')? Raw strings in path are not the best idea: if the path happens to end with "\", you may not notice it in your editor, but you'll get a syntax error because the backslash escapes the end quote. Especially a problem if you don't code the path yourself, but it's provided programmatically or by the user. I know because I made this error :). It would be better to just use forward slashes - works under Windows too. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From ronan at melim.com.br Fri Oct 3 08:28:14 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Fri Oct 3 08:27:11 2003 Subject: [Tutor] Re: Copy files In-Reply-To: References: <200310021752.12721.ronan@melim.com.br> Message-ID: <200310030928.14780.ronan@melim.com.br> Em Qui 02 Out 2003 18:09, Andrei escreveu: > > Is there some python function to make a copy of a file? > > > > I'd like to do it as with a native function like os.unlink, > > os.mkdir, but I'm not finding a function that do it. > > Look at the shutil module. Great!! Thank you very much Andrei. Ronan From pythontutor at venix.com Fri Oct 3 11:49:34 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Fri Oct 3 11:49:41 2003 Subject: [Tutor] http return status when using urllib Message-ID: <3F7D9A8E.3040308@venix.com> I used urllib to post some data to a site and could not find any easy way to determine the HTTP status. When I supplied a deliberately wrong URL I simply got back the Apache error page with no real indication that a problem occurred. I, of course, could read the error message, but there was no simple mechanism for the script to know it had failed. urllib2 raises an exception and includes attributes: code and msg in the exception which reflect the HTTP status line. Obviously, the exception is enough to alert the script that a problem occurred. There was no discussion of error handling in "Python in a Nutshell", "Python Standard Library", or the module docs. I read through the urllib source code and the module clearly goes to extra lengths to prevent an exception. (Yes, I can override this behavior by writing my own class.) Am I missing something in my approach? Does anyone know the rationale for hiding errors (and the status code)? -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From glingl at aon.at Fri Oct 3 16:03:48 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Oct 3 16:05:39 2003 Subject: [Tutor] friday night entertainment (a generator) Message-ID: <3F7DD624.50907@aon.at> Hi, I just wrote a generator which generates all the r-permutations of n distict objects, (this most probably is an old soup, newly cooked up - or a wheel reinvented): def perms(n,r,result=()): if r == 0: yield result for element in n: t = n[:] t.remove(element) for perm in perms(t,r-1,result+(element,)): yield perm >>> for p in perms(range(4),2): print p (0, 1) (0, 2) (0, 3) (1, 0) (1, 2) (1, 3) (2, 0) (2, 1) (2, 3) (3, 0) (3, 1) (3, 2) >>> Do any amendments (concerning efficiency and/or elegance) come to your mind? Any hints or suggestions are highly appreciated Gregor From jeff at ccvcorp.com Fri Oct 3 17:24:46 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Oct 3 17:21:11 2003 Subject: [Tutor] Window pathnames References: <109179A1E3D9D511BEEF00D0B7D4912401BA26C9@ns9875.swisslife.ch> Message-ID: <3F7DE91E.8080806@ccvcorp.com> Zandbergen Christian wrote: > >>> open("C:\\dslfjsl\jlsfjslfsj") > Traceback (most recent call last): > File "", line 1, in ? > IOError: [Errno 2] No such file or directory: > 'C:\\dslfjsl\\jlsfjslfsj' > > > It seems that one backslash always returns a double backslash. That's not quite true. Try typing in a directory name that starts with a 't', for example (like "c:\\stuff\temp"), and you won't get a double backslash in the error message -- but you might see an indication of why all this happens. '\t' isn't really a backslash and a 't', as Python sees it -- instead, it's a single TAB character (ascii code 0x09). So the string I showed above is interpreted by Python as meaning "c:\stuff[TAB]emp". There's a variety of these nonprintable characters, and they're accessed by using a backslash to "escape" the following character -- a backslash in a string says "Treat the next character special", and then the next character indicates *what* to do. So how do you get a backslash, then, if it means to treat the next character as something special? Well, you make the next character another backslash, and the "special" handling in this case is to just print it as it is. When Python is displaying a string using repr() (as error tracebacks do), it shows escape sequences as they would be typed; thus, a string containing a (single) backslash will be displayed by repr() by using two backslashes. Now, not all characters indicate something special when escaped. For instance, '\j' has no special meaning. So Python reads that as two separate characters, a backslash and a 'j', when you type it in. However, when it displays backslashes, it doubles them (so that you don't mistake them for part of an escape code). That's what's happening in your error message. Jeff Shannon Technician/Programmer Credit International From thomi at imail.net.nz Fri Oct 3 20:10:01 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Fri Oct 3 20:10:01 2003 Subject: [Tutor] pointers for python? Message-ID: <200310041210.01431.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi all, In C, you can modify a variable from within a seperate function, by passing a pointer to that function. Is there any way to do this in python? it'd be kinda useful ;) I'm sure i read it in the tutorial a while back, but searching the same tutorials now, I can't seem to find it anywhere... any ideas? to clarify, currently, this: def inc(x): x+=1 a=1 inc(a) print a prints "1" is there a way to get the inc() function to modify the original variable, even though it's not in the function's scope? THanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/fg/Z2tSuYV7JfuERAi0jAJ0WsGXRMBGcuUhaVNR2yx7gdWRCnQCgiqce KED+ZlWXIc+qxewJMdEG+uc= =o6XS -----END PGP SIGNATURE----- From peterabrown at froggy.com.au Fri Oct 3 20:36:34 2003 From: peterabrown at froggy.com.au (Peter Brown) Date: Fri Oct 3 20:36:23 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310041210.01431.thomi@imail.net.nz> Message-ID: <3.0.6.32.20031004103634.009f9900@mail.froggy.com.au> I'm only new to python but this works >>> def inc(x): global y y = x + 1 return y >>> a = 1 >>> inc(a) 2 >>> Peter At 12:10 4/10/2003 +1200, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Hi all, > >In C, you can modify a variable from within a seperate function, by passing a >pointer to that function. Is there any way to do this in python? it'd be >kinda useful ;) > >I'm sure i read it in the tutorial a while back, but searching the same >tutorials now, I can't seem to find it anywhere... any ideas? > >to clarify, currently, this: > >def inc(x): > x+=1 > >a=1 >inc(a) >print a > >prints "1" > >is there a way to get the inc() function to modify the original variable, even >though it's not in the function's scope? > > >THanks, > >- -- >Thomi Richards, >http://once.sourceforge.net/ > > >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.2.3 (GNU/Linux) > >iD8DBQE/fg/Z2tSuYV7JfuERAi0jAJ0WsGXRMBGcuUhaVNR2yx7gdWRCnQCgiqce >KED+ZlWXIc+qxewJMdEG+uc= >=o6XS >-----END PGP SIGNATURE----- > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From op73418 at mail.telepac.pt Fri Oct 3 21:28:01 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Oct 3 21:26:37 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310041210.01431.thomi@imail.net.nz> References: <200310041210.01431.thomi@imail.net.nz> Message-ID: <6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com> On Sat, 4 Oct 2003 12:10:01 +1200, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > > >Hi all, > >In C, you can modify a variable from within a seperate function, by passing a >pointer to that function. Is there any way to do this in python? it'd be >kinda useful ;) > >I'm sure i read it in the tutorial a while back, but searching the same >tutorials now, I can't seem to find it anywhere... any ideas? > >to clarify, currently, this: > >def inc(x): > x+=1 > >a=1 >inc(a) >print a > >prints "1" > >is there a way to get the inc() function to modify the original variable, even >though it's not in the function's scope? > Why not the perfectly Pythonic solution >>> def inc(x): ... return x + 1 ... >>> a = 1 >>> a = inc(a) >>> a 2 It even has no side effects - the function that is. With my best regards, G. Rodrigues From idiot1 at netzero.net Fri Oct 3 21:44:21 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Fri Oct 3 21:54:06 2003 Subject: [Tutor] RE: re Message-ID: <3F7E25F5.10102@netzero.net> Regarding re (regular expressions): %#$^^&*$^@$@! I am fustrated. I want a function to return a list or a string which is a WikiWord split into words, with the split occuring at the Capitalized word. So if I feed it the word ThisIsAWikiWord, it can give me back: 'This Is A Wiki Word' *OR* ['This','Is','A','Wiki','Word'] Well, I got THIS far... >>> def wordsplit(word): return re.split('[A-Z]+',word) >>> wordsplit(word) ['', 'ary', 'ad', 'ittle', 'amb'] >>> word 'MaryHadALittleLamb' >>> Please advise. 'Text Processing in Python' is good, but the RE chapter is not as transparent as I would hope. Clue eagerly saught. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From python at rcn.com Fri Oct 3 22:07:11 2003 From: python at rcn.com (Raymond Hettinger) Date: Fri Oct 3 22:07:40 2003 Subject: [Tutor] RE: re In-Reply-To: <3F7E25F5.10102@netzero.net> Message-ID: <001301c38a1c$396a6fe0$e841fea9@oemcomputer> Try this: re.split('([A-Z][a-z]*)',word)[1:-1] The clue is in the docs for re.split() which say, "If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list". Raymond Hettinger -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Kirk Bailey Sent: Friday, October 03, 2003 9:44 PM To: Tutor Subject: [Tutor] RE: re Regarding re (regular expressions): %#$^^&*$^@$@! I am fustrated. I want a function to return a list or a string which is a WikiWord split into words, with the split occuring at the Capitalized word. So if I feed it the word ThisIsAWikiWord, it can give me back: 'This Is A Wiki Word' *OR* ['This','Is','A','Wiki','Word'] Well, I got THIS far... >>> def wordsplit(word): return re.split('[A-Z]+',word) >>> wordsplit(word) ['', 'ary', 'ad', 'ittle', 'amb'] >>> word 'MaryHadALittleLamb' >>> Please advise. 'Text Processing in Python' is good, but the RE chapter is not as transparent as I would hope. Clue eagerly saught. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ################################################################# ################################################################# ################################################################# ##### ##### ##### ################################################################# ################################################################# ################################################################# From amonroe at columbus.rr.com Fri Oct 3 23:13:02 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Oct 3 23:13:08 2003 Subject: [Tutor] Size of any arbitrary object in bytes? In-Reply-To: <001301c38a1c$396a6fe0$e841fea9@oemcomputer> References: <001301c38a1c$396a6fe0$e841fea9@oemcomputer> Message-ID: <19699236584.20031003231302@columbus.rr.com> Is there a way to find the size of any arbitrary object (list, dictionary, possibly nested) in bytes, without resorting to recursion? I was playing with sqlite again, and the __len__ function of the result set seems to tell me number of records returned, rather than the physical RAM bytes consumed by the result set. Alan From op73418 at mail.telepac.pt Sat Oct 4 07:36:32 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Oct 4 07:35:10 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310041429.14843.thomi@imail.net.nz> References: <200310041210.01431.thomi@imail.net.nz> <6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com> <200310041429.14843.thomi@imail.net.nz> Message-ID: On Sat, 4 Oct 2003 14:29:14 +1200, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 > >On Sat, 04 Oct 2003 13:28, Gon?alo Rodrigues wrote: >> >> Why not the perfectly Pythonic solution >> >> >>> def inc(x): >> >> ... return x + 1 >> ... >> >> >>> a = 1 >> >>> a = inc(a) >> >>> a > > >I waned to do it without having to return a variable.... If it can't be done. >that's fine, but i was hoping to be able to do it without a "return".... P. Brown in another reply gave you another answer involving the global keyword -- but it's ugly and unpythonic IMHO and it only works for global names (e.g. module-level). Right now I can't remember of any other solution -- and I suspect any such would involve some dangerous hackery. Maybe the question should be: why do you want to write C code in Python? In Python, variables are just names referencing an object (said to be binded (bounded?) to that object). The line above a = inc(a) just rebinds the name "a" to whatever inc(a) returns. In C, a variable is more of a placeholder -- a real location in memory -- that's why you need, or at least one of the reasons why you need, all those tricks with pass-by-reference and whatnot. So I repeat my question: Why do you want to write C code in Python? YMMV, but wouldn't it be better just trying to get in the Pythonic mindset? With my best regards, G. Rodrigues From thomi at imail.net.nz Sat Oct 4 08:06:25 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Oct 4 08:06:25 2003 Subject: [Tutor] pointers for python? In-Reply-To: References: <200310041210.01431.thomi@imail.net.nz> <200310041429.14843.thomi@imail.net.nz> Message-ID: <200310050006.27441.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > > Why do you want to write C code in Python? > It was more for experimentation than anything else. I guess i *can* do anything with a return statement. I was playing with GUI toolkits in both C and python (the same toolkit as it turns out), and was looking at the ways the different languages did things. > YMMV, but wouldn't it be better just trying to get in the Pythonic > mindset? Probably ;) Thanks for your help ;) - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD4DBQE/frfD2tSuYV7JfuERAiDnAKCUoIphhm2X9EgKjb0WGnSKvPMdEgCXe5Fh Qj1UxURKex4JVgqF0VnSbw== =Rbob -----END PGP SIGNATURE----- From pythontutor at venix.com Sat Oct 4 12:17:29 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Oct 4 12:17:41 2003 Subject: [Tutor] friday night entertainment (a generator) In-Reply-To: <3F7DD624.50907@aon.at> References: <3F7DD624.50907@aon.at> Message-ID: <3F7EF299.7010909@venix.com> One hidden bug, if passed an r of 0, but n is not empty, the script continues to iterate through the list elements with negative r's. These do no produce results so you won't notice unless you put a print statement into the function. I added: print "n,r,result",n,r,result at the top and got these results: n,r,result (1, 2, 3, 4) 2 () n,r,result [2, 3, 4] 1 (1,) n,r,result [3, 4] 0 (1, 2) (1, 2) n,r,result [4] -1 (1, 2, 3) n,r,result [] -2 (1, 2, 3, 4) n,r,result [3] -1 (1, 2, 4) n,r,result [] -2 (1, 2, 4, 3) n,r,result [2, 4] 0 (1, 3) (1, 3) n,r,result [4] -1 (1, 3, 2) Here's your updated code with two other minor changes: force r to a reasonable value force t to be a list in the case that n is a tuple from __future__ import generators def perms(n,r,result=()): #print "n,r,result",n,r,result r = max(0, min(r, len(n))) # r ranges from 0 to len(n) # change to raise an exception if you prefer if r == 0: yield result else: for element in n: t = list(n[:]) # n could be a tuple t.remove(element) for perm in perms(t,r-1,result+(element,)): yield perm if __name__ == '__main__': n = (1,2,3,4) for p in perms(n,0): print p for p in perms(n,2): print p Hope this helps. Gregor Lingl wrote: > Hi, > > I just wrote a generator which generates > all the r-permutations of n distict objects, > (this most probably is an old soup, newly cooked up - > or a wheel reinvented): > > def perms(n,r,result=()): > if r == 0: > yield result > for element in n: > t = n[:] > t.remove(element) > for perm in perms(t,r-1,result+(element,)): > yield perm > >>> for p in perms(range(4),2): > print p > > (0, 1) > (0, 2) > (0, 3) > (1, 0) > (1, 2) > (1, 3) > (2, 0) > (2, 1) > (2, 3) > (3, 0) > (3, 1) > (3, 2) > >>> > > Do any amendments (concerning efficiency and/or elegance) > come to your mind? > > Any hints or suggestions are highly appreciated > > Gregor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From jim_938 at hotmail.com Sat Oct 4 12:35:44 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Sat Oct 4 12:35:48 2003 Subject: [Tutor] pack module Message-ID: Hello, Can someone please give me some idea about the pack module. I have tried to read it from the documentation. But not clear about it. Statements like pack('>L',0) Where > indicates the endienness. I will highly appriciate any kind of suggestion regarding pack. Thanks in advance. Regards, James _________________________________________________________________ Three simple steps. They guarantee your safety. http://server1.msn.co.in/features/general/SMBvirus/index.asp Protect yourself against the SMB.EXE virus. From kalle at lysator.liu.se Sat Oct 4 13:15:38 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sat Oct 4 13:15:43 2003 Subject: [Tutor] pointers for python? In-Reply-To: References: <200310041210.01431.thomi@imail.net.nz> <6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com> <200310041429.14843.thomi@imail.net.nz> Message-ID: <20031004171538.GK9058@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Gon?alo Rodrigues on modifying function parameters] > P. Brown in another reply gave you another answer involving the > global keyword -- but it's ugly and unpythonic IMHO and it only > works for global names (e.g. module-level). Right now I can't > remember of any other solution -- and I suspect any such would > involve some dangerous hackery. Using some kind of mutable object to wrap the argument is one way to get (most of) the desired behaviour. Example: >>> def inc(x): ... x[0] += 1 ... >>> a = [0] >>> inc(a) >>> a[0] 1 Something similar but better looking could probably be created by defining a class. Remember that the assignment operator can't be used, though. In code such as def set2(x): x[0] = 2 what looks as a variable assignment is really an item assignment. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE/fwAadNeA1787sd0RAss7AJ9X/ZGCakZys9BvgNKMUGxI1wvu+ACdHVxT 2zFcNFTlpRZh47RTBRuERAA= =L2LE -----END PGP SIGNATURE----- From python at dhumketu.cjb.net Sat Oct 4 11:51:51 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Sat Oct 4 13:50:54 2003 Subject: [Tutor] Re: Project Parallelport In-Reply-To: <20030930111330.GC6822@liposerv.bluecher> References: <20030930111330.GC6822@liposerv.bluecher> Message-ID: <20031004155151.GA300@dhumketu.homeunix.net> +-- Vadim Usenko [python-tutor] [30-09-03 16:43 IST]: | Hi all, | | I am searching for a module in python to connect a programm directly | with the parallel port to build a mini-crossway with some traffic | lights. | Do you have some information for me, please? pyParallel is a module which will allow you communicate with parallel port | | Thanks, | | Vadim | | | | ------------------------------ -- With Best Regards, Shantanoo Mahajan From pythontutor at venix.com Sat Oct 4 14:25:05 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sat Oct 4 14:26:16 2003 Subject: [Tutor] pack function In-Reply-To: References: Message-ID: <3F7F1081.40209@venix.com> (pack is actually in the struct module.) This module allows you to manipulate binary data structures that typically map to C structs, hence the name. The binary structure for things like integers will vary based upon the processor and system architecture. On an Intel X86 processor the bytes that make up an integer are stored with the least significant byte first (little endian) while many other processors would store the most significant byte first (big endian). This is very much analogous to languages that read right-to-left versus left-to-right. I've used struct to handle things like dBase files that have header information that was (presumably) written from a C struct and specifies things like record size, number of fields, and field names. You need to know the specs for your target to know the right thing to do. If your target is a C program on the same kind of system, then Native, which is the default, should generally do the right thing. "Python in a Nutshell" has a good description of struct, but it is not so very different from the module documentation. Jimmy verma wrote: > Hello, > > Can someone please give me some idea about the pack module. I have tried > to read it from the documentation. But not clear about it. > Statements like pack('>L',0) > > Where > indicates the endienness. > > I will highly appriciate any kind of suggestion regarding pack. > > Thanks in advance. > > Regards, > > James > > _________________________________________________________________ > Three simple steps. They guarantee your safety. > http://server1.msn.co.in/features/general/SMBvirus/index.asp Protect > yourself against the SMB.EXE virus. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From guillermo.fernandez at epfl.ch Sat Oct 4 16:15:45 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Sat Oct 4 16:15:56 2003 Subject: [Tutor] global variables Message-ID: <3F7F2A71.3060703@epfl.ch> Hi, Appended is a module I've written to interface to a sqlite database. My problem is I would like to make 'module variables' to address the database and cursor without passing them as arguments to the functions. I've done it with 'global', but: 1) I don't really get the global concept. 2) I feel there must be a cleaner way of doing it. Furthermore, I don't understand why I can address clientmacs, apnames and ipaps inside a function without making them global while I can't with the database, cursor and id variable. If you have any explanation, advice or document I could read, I would be grateful to know it. Thanks! Guille ************************************************************ CODE: #--- Imports import sqlite #Sqlite database interface, Python DB API 2.0 compatible #--- Database global database global cursor global id # TODO: This is immediate operations, must implement security checks! def open(databasename): """Open or create the database and prepares a cursor to operate""" global database global cursor global id database=sqlite.connect(databasename) cursor=database.cursor() def create(): """Create the database tables""" global database global cursor global id id=1 cursor.execute('CREATE TABLE logs(id VARCHAR(10) PRIMARY KEY,\ log VARCHAR(400),\ mmonth VARCHAR(20),\ mday VARCHAR(10),\ mhour VARCHAR(10),\ apname VARCHAR(50),\ ipap VARCHAR(20),\ messagenumber VARCHAR(20),\ apmessage VARCHAR(300),\ year VARCHAR(10),\ apmonth VARCHAR(20),\ apday VARCHAR(10),\ aphour VARCHAR(10),\ messagecode VARCHAR(20),\ message VARCHAR(160),\ clientname VARCHAR(50),\ clientmac VARCHAR(20),\ messageexplanation VARCHAR(200))') cursor.execute('CREATE TABLE clientmacs(clientmac VARCHAR(20))') cursor.execute('CREATE TABLE apnames(apname VARCHAR(200))') cursor.execute('CREATE TABLE ipaps(ipap VARCHAR(20))') def execute(query): """Executes a query that *do not need* a commit over the database""" global database global cursor global id cursor.execute(query) return cursor.fetchall() variables=['mmonth', 'mday', 'mhour', 'apname', 'ipap', 'messagenumber', 'apmessage', 'year', 'apmonth', 'apday', 'aphour', 'messagecode', 'message', 'clientname', 'clientmac', 'messageexplanation'] clientmacs=[] apnames=[] ipaps=[] def addentry(parser): """Inserts an entry to the database""" global database global cursor global id SQLbegin="INSERT INTO logs (id, log, mmonth, mday, mhour, apname, ipap,\ messagenumber, apmessage, year, apmonth,\ apday, aphour, messagecode, message,\ clientname, clientmac, messageexplanation)\ VALUES ( '"+str(id)+"', '" id+=1 SQLend="')" query=SQLbegin+parser.group(0)+"', '" for i in variables: query=query+str(parser.group(i))+"', '" query=query[:-4]+SQLend cursor.execute(query) # We make lists with all relevant data if parser.group('clientmac') not in clientmacs: query="INSERT INTO clientmacs (clientmac) VALUES ('"+\ parser.group('clientmac')+SQLend cursor.execute(query) clientmacs.append(parser.group('clientmac')) if parser.group('apname') not in apnames: query="INSERT INTO apnames (apname) VALUES ('"+\ parser.group('apname')+SQLend cursor.execute(query) clientmacs.append(parser.group('apname')) if parser.group('ipap') not in ipaps: query="INSERT INTO ipaps (ipap) VALUES ('"+\ parser.group('ipap')+SQLend cursor.execute(query) clientmacs.append(parser.group('ipap')) def close(): """Closes the database""" global database global cursor global id id=1 cursor.close() database.commit() database.close() From guillermo.fernandez at epfl.ch Sat Oct 4 16:15:59 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Sat Oct 4 16:16:13 2003 Subject: [Tutor] global variables Message-ID: <3F7F2A7F.1020800@epfl.ch> Hi, Appended is a module I've written to interface to a sqlite database. My problem is I would like to make 'module variables' to address the database and cursor without passing them as arguments to the functions. I've done it with 'global', but: 1) I don't really get the global concept. 2) I feel there must be a cleaner way of doing it. Furthermore, I don't understand why I can address clientmacs, apnames and ipaps inside a function without making them global while I can't with the database, cursor and id variable. If you have any explanation, advice or document I could read, I would be grateful to know it. Thanks! Guille ************************************************************ CODE: #--- Imports import sqlite #Sqlite database interface, Python DB API 2.0 compatible #--- Database global database global cursor global id # TODO: This is immediate operations, must implement security checks! def open(databasename): """Open or create the database and prepares a cursor to operate""" global database global cursor global id database=sqlite.connect(databasename) cursor=database.cursor() def create(): """Create the database tables""" global database global cursor global id id=1 cursor.execute('CREATE TABLE logs(id VARCHAR(10) PRIMARY KEY,\ log VARCHAR(400),\ mmonth VARCHAR(20),\ mday VARCHAR(10),\ mhour VARCHAR(10),\ apname VARCHAR(50),\ ipap VARCHAR(20),\ messagenumber VARCHAR(20),\ apmessage VARCHAR(300),\ year VARCHAR(10),\ apmonth VARCHAR(20),\ apday VARCHAR(10),\ aphour VARCHAR(10),\ messagecode VARCHAR(20),\ message VARCHAR(160),\ clientname VARCHAR(50),\ clientmac VARCHAR(20),\ messageexplanation VARCHAR(200))') cursor.execute('CREATE TABLE clientmacs(clientmac VARCHAR(20))') cursor.execute('CREATE TABLE apnames(apname VARCHAR(200))') cursor.execute('CREATE TABLE ipaps(ipap VARCHAR(20))') def execute(query): """Executes a query that *do not need* a commit over the database""" global database global cursor global id cursor.execute(query) return cursor.fetchall() variables=['mmonth', 'mday', 'mhour', 'apname', 'ipap', 'messagenumber', 'apmessage', 'year', 'apmonth', 'apday', 'aphour', 'messagecode', 'message', 'clientname', 'clientmac', 'messageexplanation'] clientmacs=[] apnames=[] ipaps=[] def addentry(parser): """Inserts an entry to the database""" global database global cursor global id SQLbegin="INSERT INTO logs (id, log, mmonth, mday, mhour, apname, ipap,\ messagenumber, apmessage, year, apmonth,\ apday, aphour, messagecode, message,\ clientname, clientmac, messageexplanation)\ VALUES ( '"+str(id)+"', '" id+=1 SQLend="')" query=SQLbegin+parser.group(0)+"', '" for i in variables: query=query+str(parser.group(i))+"', '" query=query[:-4]+SQLend cursor.execute(query) # We make lists with all relevant data if parser.group('clientmac') not in clientmacs: query="INSERT INTO clientmacs (clientmac) VALUES ('"+\ parser.group('clientmac')+SQLend cursor.execute(query) clientmacs.append(parser.group('clientmac')) if parser.group('apname') not in apnames: query="INSERT INTO apnames (apname) VALUES ('"+\ parser.group('apname')+SQLend cursor.execute(query) clientmacs.append(parser.group('apname')) if parser.group('ipap') not in ipaps: query="INSERT INTO ipaps (ipap) VALUES ('"+\ parser.group('ipap')+SQLend cursor.execute(query) clientmacs.append(parser.group('ipap')) def close(): """Closes the database""" global database global cursor global id id=1 cursor.close() database.commit() database.close() From glingl at aon.at Sat Oct 4 16:58:48 2003 From: glingl at aon.at (Gregor Lingl) Date: Sat Oct 4 17:00:38 2003 Subject: [Tutor] friday night entertainment (a generator) In-Reply-To: <3F7EF299.7010909@venix.com> References: <3F7DD624.50907@aon.at> <3F7EF299.7010909@venix.com> Message-ID: <3F7F3488.8010309@aon.at> Lloyd Kvam schrieb: > One hidden bug, if passed an r of 0, but n is not empty, the > .... > > Here's your updated code with two other minor changes: > force r to a reasonable value > force t to be a list in the case that n is a tuple Thanks for your valuable comments. You pointed out a really bad mistake. It came from transforming an ordinary function with return statements into a generator. I overlooked that a yield statement doesn't terminate the execution of a function/ generator. Have to be more careful next time. Regards, Gregor > > from __future__ import generators > def perms(n,r,result=()): > #print "n,r,result",n,r,result > r = max(0, min(r, len(n))) # r ranges from 0 to len(n) > # change to raise an exception if you > prefer > if r == 0: > yield result > else: > for element in n: > t = list(n[:]) # n could be a tuple > t.remove(element) > for perm in perms(t,r-1,result+(element,)): > yield perm > > if __name__ == '__main__': > n = (1,2,3,4) > for p in perms(n,0): > print p > for p in perms(n,2): > print p > > > Hope this helps. It did! From alan.gauld at blueyonder.co.uk Sat Oct 4 19:00:16 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Oct 4 18:59:33 2003 Subject: [Tutor] pointers for python? References: <200310041210.01431.thomi@imail.net.nz><6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com><200310041429.14843.thomi@imail.net.nz> Message-ID: <00dc01c38acb$47037930$6401a8c0@xp> >> Why not the perfectly Pythonic solution >> >> >>> def inc(x): >> ... return x + 1 >> ... > >I waned to do it without having to return a variable.... If it can't be done. >that's fine, but i was hoping to be able to do it without a "return".... Can you say why? The return method is by far the best technique, its safe and makes the function reusable - it doesn't rely on a variable called x existing somewhere. Its "the right way" to do it. Using globals is possible but extremely bad practice and should be avoided. P. Brown in another reply gave you another answer involving the global keyword -- but it's ugly and unpythonic IMHO and it only works for global names (e.g. module-level). Right now I can't remember of any other solution -- and I suspect any such would involve some dangerous hackery. Maybe the question should be: why do you want to write C code in Python? In Python, variables are just names referencing an object (said to be binded (bounded?) to that object). The line above a = inc(a) just rebinds the name "a" to whatever inc(a) returns. In C, a variable is more of a placeholder -- a real location in memory -- that's why you need, or at least one of the reasons why you need, all those tricks with pass-by-reference and whatnot. So I repeat my question: Why do you want to write C code in Python? YMMV, but wouldn't it be better just trying to get in the Pythonic mindset? With my best regards, G. Rodrigues From thomi at imail.net.nz Sat Oct 4 18:18:09 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Sat Oct 4 19:18:06 2003 Subject: [Tutor] pointers for python? In-Reply-To: <00dc01c38acb$47037930$6401a8c0@xp> References: <200310041210.01431.thomi@imail.net.nz> <00dc01c38acb$47037930$6401a8c0@xp> Message-ID: <200310051118.09631.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > Can you say why? The return method is by far the best technique, > its safe and makes the function reusable - it doesn't rely on a > variable called x existing somewhere. Its "the right way" to do it. well, (for example), supposing you had a situation where a function was passed 3 variables ("A", "B", and "C"). A is an empty pygtk Table element, B is a list of strings. under C, you'd have to pass a pointer to A in order to modify it, correct? It just seemed neater doing someting like this: table = gtk.Table(3,2,gtk.FALSE) fill_table(table,["Label 1 text","label 2 text","Label 3 text"]) than something like this: table = fill_table(gtk.table,["Label 1 text","label 2 text","Label 3 text"]) but that's just me ;) As i said in an earlier mail, the question was purely one of discovery, which arose when comparing C++ and python code ;) > > Using globals is possible but extremely bad practice and should be > avoided. > aye... > Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/f0ch2tSuYV7JfuERAo70AJ9XzovN7Bks2pQwW88Sms5PEHzvqACdEQxP EFvu57W/1AOyzfgGKsTT34s= =GlW4 -----END PGP SIGNATURE----- From idiot1 at netzero.net Sun Oct 5 11:21:59 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Oct 5 11:20:59 2003 Subject: [Tutor] Classes and the like... In-Reply-To: <003001c37f92$79eb91a0$6401a8c0@xp> References: <200309160039.19484.intatia@paradise.net.nz><002f01c37e32$435f00b0$6401a8c0@xp> <200309201356.22820.intatia@paradise.net.nz> <003001c37f92$79eb91a0$6401a8c0@xp> Message-ID: <3F803717.5050304@netzero.net> Alan Gauld wrote: >>Object? What's an object? > > This any help? http://www.tinylist.org/cgi-bin/wikinehesa.py/ObjectOriented BTW, the OOP series of pages in the wiki could use contributions and additional pages. Anyone at all intrested, click and jump in. > :-) > > >>Any ideas on a fairly simple project I could do next? > > > THe ones I always use when trying out a new OO language > for the first time are: > > 1) A Hello World program using a message object > > Initialise it with no parameters it prints Hello World. > Initialise it with a string parameter and it prints the string. > Change the text attribute and it prints the new value. > > 2) A switch. It can have state ON or OFF. You can Set it > to ON or OFF. It can tell you its state. > > 3) A Toggle switch inheriting from the switch above. > It only has 1 extra method which Toggles the state to > the opposite of whatever its current state is. > > 4) A bank of switches that I can manipulate(to tst polymorphism) > > Thats it, after doing that I usually have a good feel of basic > OO programming in whatever language it is. > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From idiot1 at netzero.net Sun Oct 5 11:27:25 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Oct 5 11:26:23 2003 Subject: [Tutor] bug hunt Message-ID: <3F80385D.6050104@netzero.net> The servers do not respect ssi includes. Yet the modules list code to handle such, although I am not up to speed enough to debug them. As this is defined in the modules, I have the qurious duty to repport a possible bug in the cgiHTTPServer.py module. Also, it does not know what to do with the standard .shtml extension, and confuses the browser. Whom should I contact on this matter? Again, here is the basic cgiserver script: #!C:\Python22\pythonw.exe # COPYRIGHT 2003 Steve Holden, free for personal use. # Please visit http://www.holdenweb.com/ to learn more! # import CGIHTTPServer, BaseHTTPServer, os os.chdir ('.\web') # make the web directory current httpd=BaseHTTPServer.HTTPServer(('',8080), CGIHTTPServer.CGIHTTPRequestHandler) httpd.serve_forever() # It handles regular HTML fine, and cgi, and .html files without a glitch. -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From tbstep at tampabay.rr.com Sun Oct 5 13:17:35 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Sun Oct 5 13:21:47 2003 Subject: [Tutor] Recursion confusion Message-ID: <200310051317.35183.tbstep@tampabay.rr.com> I am trying to learn Python better (and programming in general) and have come across something that I am having trouble getting my head around. Can someone tell me if my understanding of recursion is correct here? >>> def factorial(n): ... if n==0: ... return 1 ... else: ... return n*factorial(n-1) >>> factorial(3) 6 So, what is going on here is this: 3 results in the function returning 3* the result of factorial(2), which results in 2 * the result of factorial(1), which results in 1 * the result of factorial(0) which results in 1. So, we have 1*1*2*3. Now, if I were to omit the first condition of n==0, I would get infinite recursion, correct? So, along those lines, for recursion to work, I have to include some sort of conditional terminator. Is that correct? If so, I guess I finally understand it (somewhat anyway :-)) -- Todd Stephens "Good people do not need laws to tell them to act responsibly, while bad people will find a way around the laws." - Plato From erikprice at mac.com Sun Oct 5 14:09:11 2003 From: erikprice at mac.com (Erik Price) Date: Sun Oct 5 13:47:16 2003 Subject: [Tutor] Recursion confusion In-Reply-To: <200310051317.35183.tbstep@tampabay.rr.com> Message-ID: <05556BC3-F75F-11D7-868C-00039351FE6A@mac.com> On Sunday, October 5, 2003, at 01:17 PM, Todd Stephens wrote: > Can someone tell me if my understanding of recursion is correct here? > >>>> def factorial(n): > ... if n==0: > ... return 1 > ... else: > ... return n*factorial(n-1) > >>>> factorial(3) > 6 > > So, what is going on here is this: > 3 results in the function returning 3* the result of factorial(2), > which > results in 2 * the result of factorial(1), which results in 1 * the > result of factorial(0) which results in 1. So, we have 1*1*2*3. Now, > if I were to omit the first condition of n==0, I would get infinite > recursion, correct? So, along those lines, for recursion to work, I > have to include some sort of conditional terminator. Is that correct? > If so, I guess I finally understand it (somewhat anyway :-)) That is all correct. Erik From sigurd at 12move.de Sun Oct 5 14:19:44 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sun Oct 5 14:25:13 2003 Subject: [Tutor] Recursion confusion In-Reply-To: <200310051317.35183.tbstep@tampabay.rr.com> (Todd Stephens's message of "Sun, 5 Oct 2003 13:17:35 -0400") References: <200310051317.35183.tbstep@tampabay.rr.com> Message-ID: On 5 Oct 2003, Todd Stephens <- tbstep@tampabay.rr.com wrote: [...] > So, what is going on here is this: > 3 results in the function returning 3* the result of factorial(2), which > results in 2 * the result of factorial(1), which results in 1 * the > result of factorial(0) which results in 1. So, we have 1*1*2*3. Now, > if I were to omit the first condition of n==0, I would get infinite > recursion, correct? So, along those lines, for recursion to work, I Yes. > have to include some sort of conditional terminator. Is that correct? Yes. Never ever forget that. > If so, I guess I finally understand it (somewhat anyway :-)) Fine. But don't rely too much on recursion in Python. Too deep recursion will cause Python to complain. Try factorial(999) with your code. Python does nothing like eg. Scheme which can optimize recursive algorithms where the recursive function call is in tail position (the last function call in the caller). Better use an iterative version here. (You could increase the maximal recursion depth in Python but than the error would occur only later; I am not sure at the moment but I think stackless Python does not have this problem). Karl -- Please do *not* send copies of replies to me. I read the list From wolf_binary at hotmail.com Sun Oct 5 14:57:04 2003 From: wolf_binary at hotmail.com (Cameron Stoner) Date: Sun Oct 5 14:57:08 2003 Subject: [Tutor] TCP/IP versions Message-ID: I was going through the socket programming documentation and wanted to know what the differences in general are from IPv4 to IPv6? Thanks, Cameron _________________________________________________________________ Help protect your PC. Get a FREE computer virus scan online from McAfee. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From mjekl at clix.pt Sun Oct 5 16:15:07 2003 From: mjekl at clix.pt (mjekl@clix.pt) Date: Sun Oct 5 16:13:27 2003 Subject: [Tutor] function local var problem :-(( Message-ID: Hi, I'm new here and with programming. I've been learning on my own and cannot understand what happens with this function I created. The function is in it's own module that I import into shell. ###### module1.py ###### def printHierarchy(objecto, printList=[]): """Prints a class hierarchy given an object. Works only with single inheritance hierarchies.""" if objecto.__class__.__bases__: printList.append(objecto.__class__.__name__) recurObjecto = objecto.__class__.__bases__[0]() return printHierarchy(recurObjecto, printList) else: printList.append(objecto.__class__.__name__) if not objecto.__class__.__bases__: i = 0 for klass in printList: print i * ' ' + klass i += 1 else: return printList #################### in shell I created a hierarchy of three classes: class Sup; class Sub1(Sup); class Sub2(Sub1) Then: >>> oSub2 = Sub2() >>> printHierarchy(oSub2) Sup Sub1 Sub2 >>> The problem is that if I call the function again I get: >>> printHierarchy(oSub2) Sup Sub1 Sub2 Sup Sub1 Sub2 >>> The problem to me is that I think that the var printList is local and that it is initialized every time the function is called. But results contradict this assumption. So I tried to investigate the namespaces and found no references to var printList. I guess my investigation is bad (In shell I issued dir() and dir(module1) and got nothing. Also tried to use: from module1 import printHierarchy But didn't work either. Can someone please help me? Python 2.2 winXP Txs, Miguel Clix Rapidix - Aumente até 6X a velocidade da sua Internet Adira em http://acesso.clix.pt e comece logo a navegar From amk at amk.ca Sun Oct 5 16:28:35 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun Oct 5 16:28:16 2003 Subject: [Tutor] TCP/IP versions In-Reply-To: Message-ID: <7E8E471B-F772-11D7-933C-0003931BF218@amk.ca> On Sunday, October 5, 2003, at 02:57 PM, Cameron Stoner wrote: > I was going through the socket programming documentation and wanted to > know what the differences in general are from IPv4 to IPv6? See http://www.opus1.com/ipv6/whatisipv6.html . The only change that affects application programmers is the larger address size, from 32-bit to 128-bit addresses. --amk From amk at amk.ca Sun Oct 5 16:31:37 2003 From: amk at amk.ca (A.M. Kuchling) Date: Sun Oct 5 16:31:18 2003 Subject: [Tutor] bug hunt In-Reply-To: <3F80385D.6050104@netzero.net> Message-ID: On Sunday, October 5, 2003, at 11:27 AM, Kirk Bailey wrote: > The servers do not respect ssi includes. Yet the modules list code to > handle such, although I am not up to speed enough to debug them. As > this is defined in the modules, I have the qurious duty to repport a > possible bug in the cgiHTTPServer.py module. I don't believe anything in the Python core has ever supported server-side includes; they're mostly an Apache thing. --amk From pythontutor at venix.com Sun Oct 5 16:36:37 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Oct 5 16:37:13 2003 Subject: [Tutor] function local var problem :-(( In-Reply-To: References: Message-ID: <3F8080D5.9030901@venix.com> This is a common pitfall in Python. The initial empty list is created ONCE, when the function is defined. It is NOT created each time the function is called and that argument is not specified. Since lists are mutable, the default list changes as it is used. The most common solution is usually: def printHierarchy(objecto, printList=None): if printList is None: printList = [] None is immutable so the default value can't be changed. Now we create a new empty list every time no list is supplied. mjekl@clix.pt wrote: > Hi, > > I'm new here and with programming. I've been learning on my own and cannot > understand what happens with this function I created. > > The function is in it's own module that I import into shell. > > ###### module1.py ###### > > def printHierarchy(objecto, printList=[]): > """Prints a class hierarchy given an object. > Works only with single inheritance hierarchies.""" > > if objecto.__class__.__bases__: > printList.append(objecto.__class__.__name__) > recurObjecto = objecto.__class__.__bases__[0]() > return printHierarchy(recurObjecto, printList) > else: > printList.append(objecto.__class__.__name__) > > if not objecto.__class__.__bases__: > i = 0 > for klass in printList: > print i * ' ' + klass > i += 1 > else: > return printList > > #################### > > in shell I created a hierarchy of three classes: > class Sup; class Sub1(Sup); class Sub2(Sub1) > > Then: > >>>>oSub2 = Sub2() >>>>printHierarchy(oSub2) > > Sup > Sub1 > Sub2 > > > The problem is that if I call the function again I get: > >>>>printHierarchy(oSub2) > > Sup > Sub1 > Sub2 > Sup > Sub1 > Sub2 > > > The problem to me is that I think that the var printList is local and that > it is initialized every time the function is called. But results contradict > this assumption. So I tried to investigate the namespaces and found no > references to var printList. I guess my investigation is bad (In shell I > issued dir() and dir(module1) > and got nothing. Also tried to use: > from module1 import printHierarchy > But didn't work either. Can someone please help me? > > Python 2.2 winXP > > Txs, > Miguel > > Clix Rapidix - Aumente at? 6X a velocidade da sua Internet > Adira em http://acesso.clix.pt e comece logo a navegar > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor at venix.com Sun Oct 5 16:39:56 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Oct 5 16:39:54 2003 Subject: [Tutor] function local var problem :-(( In-Reply-To: References: Message-ID: <3F80819C.9060907@venix.com> A good site that lists some other Python pitfalls: http://zephyrfalcon.org/labs/python_pitfalls.html zephyrfalcon.org :: labs :: 10 Python pitfalls #5 is using a mutable variable as a function default. mjekl@clix.pt wrote: > Hi, > > I'm new here and with programming. I've been learning on my own and cannot > understand what happens with this function I created. > > The function is in it's own module that I import into shell. > > ###### module1.py ###### > > def printHierarchy(objecto, printList=[]): > """Prints a class hierarchy given an object. > Works only with single inheritance hierarchies.""" > > if objecto.__class__.__bases__: > printList.append(objecto.__class__.__name__) > recurObjecto = objecto.__class__.__bases__[0]() > return printHierarchy(recurObjecto, printList) > else: > printList.append(objecto.__class__.__name__) > > if not objecto.__class__.__bases__: > i = 0 > for klass in printList: > print i * ' ' + klass > i += 1 > else: > return printList > > #################### > > in shell I created a hierarchy of three classes: > class Sup; class Sub1(Sup); class Sub2(Sub1) > > Then: > >>>>oSub2 = Sub2() >>>>printHierarchy(oSub2) > > Sup > Sub1 > Sub2 > > > The problem is that if I call the function again I get: > >>>>printHierarchy(oSub2) > > Sup > Sub1 > Sub2 > Sup > Sub1 > Sub2 > > > The problem to me is that I think that the var printList is local and that > it is initialized every time the function is called. But results contradict > this assumption. So I tried to investigate the namespaces and found no > references to var printList. I guess my investigation is bad (In shell I > issued dir() and dir(module1) > and got nothing. Also tried to use: > from module1 import printHierarchy > But didn't work either. Can someone please help me? > > Python 2.2 winXP > > Txs, > Miguel > > Clix Rapidix - Aumente at? 6X a velocidade da sua Internet > Adira em http://acesso.clix.pt e comece logo a navegar > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From erikprice at mac.com Sun Oct 5 17:13:03 2003 From: erikprice at mac.com (Erik Price) Date: Sun Oct 5 16:51:10 2003 Subject: [Tutor] function local var problem :-(( In-Reply-To: Message-ID: On Sunday, October 5, 2003, at 04:15 PM, mjekl@clix.pt wrote: > The problem to me is that I think that the var printList is local and > that > it is initialized every time the function is called. But results > contradict > this assumption. So I tried to investigate the namespaces and found no > references to var printList. I guess my investigation is bad (In shell > I > issued dir() and dir(module1) > and got nothing. Also tried to use: > from module1 import printHierarchy > But didn't work either. Can someone please help me? Very tricky, very subtle. I found a relevant quote in Python Essential Reference 2nd Ed by David Beazley (p. 63): Default parameter values are always set to the objects that were supplied as values when the function was defined. For example: a = 10 def foo(x=a): print x a = 5 # reassign 'a' foo() # prints '10' (default value not changed) However, the use of mutable objects as default values can lead to unintended behavior: a = [10] def foo(x=a): print x a.append(20) foo() # prints '[10, 20]' I follow this logic -- the variable is stored in the scope of the function definition itself (the scope where the function is defined). But that would strike me as being your module, and you said that the dir(your module) function didn't display the variable. So I don't know. Hopefully some guru can shed more light on that. Erik From glingl at aon.at Sun Oct 5 16:49:29 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Oct 5 16:51:19 2003 Subject: [Tutor] function local var problem :-(( In-Reply-To: References: Message-ID: <3F8083D9.4020501@aon.at> Hi Miguel, you ran into a well known pitfall, which you can observe in a very simple case here: >>> def test(l=[]): l.append(1) print l >>> test() [1] >>> for i in range(3): test() [1, 1] [1, 1, 1] [1, 1, 1, 1] it occurs if you use an object as default argument which is *mutable*, for instance a list. then l points to an object, which is created only when the function is *defined*, notwhen it is called. As long as there is no new assignment to l, this object is retained and can be changed if it's mutable. This is done in your example and in the one above. Every new function call uses the actual state of l. Remark: As far as I see you could solve your problem by deleting the defaultargument in the definition and then call >>> printHierarchy(oSub2, []) Hope that helps, Gregor mjekl@clix.pt schrieb: >Hi, > >I'm new here and with programming. I've been learning on my own and cannot >understand what happens with this function I created. > >The function is in it's own module that I import into shell. > >###### module1.py ###### > >def printHierarchy(objecto, printList=[]): > """Prints a class hierarchy given an object. > Works only with single inheritance hierarchies.""" > > if objecto.__class__.__bases__: > printList.append(objecto.__class__.__name__) > recurObjecto = objecto.__class__.__bases__[0]() > return printHierarchy(recurObjecto, printList) > else: > printList.append(objecto.__class__.__name__) > > if not objecto.__class__.__bases__: > i = 0 > for klass in printList: > print i * ' ' + klass > i += 1 > else: > return printList > >#################### > >in shell I created a hierarchy of three classes: >class Sup; class Sub1(Sup); class Sub2(Sub1) > >Then: > > >>>>oSub2 = Sub2() >>>>printHierarchy(oSub2) >>>> >>>> >Sup > Sub1 > Sub2 > > > >The problem is that if I call the function again I get: > > >>>>printHierarchy(oSub2) >>>> >>>> >Sup > Sub1 > Sub2 > Sup > Sub1 > Sub2 > > > >The problem to me is that I think that the var printList is local and that >it is initialized every time the function is called. But results contradict >this assumption. So I tried to investigate the namespaces and found no >references to var printList. I guess my investigation is bad (In shell I >issued dir() and dir(module1) >and got nothing. Also tried to use: > from module1 import printHierarchy >But didn't work either. Can someone please help me? > >Python 2.2 winXP > >Txs, >Miguel > >Clix Rapidix - Aumente at? 6X a velocidade da sua Internet >Adira em http://acesso.clix.pt e comece logo a navegar > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From project5 at redrival.net Sun Oct 5 17:45:16 2003 From: project5 at redrival.net (Andrei) Date: Sun Oct 5 17:47:23 2003 Subject: [Tutor] Re: function local var problem :-(( In-Reply-To: <3F80819C.9060907@venix.com> References: <3F80819C.9060907@venix.com> Message-ID: Lloyd Kvam wrote: > A good site that lists some other Python pitfalls: > > http://zephyrfalcon.org/labs/python_pitfalls.html > zephyrfalcon.org :: labs :: 10 Python pitfalls > > #5 is using a mutable variable as a function default. Miguel's sample had me completely puzzled too - more so than when I started with Python and assigned the "a" to "a[3]" and ended up with a list where I could "print a[3][3][3][3][3][3]" - it's easy to notice that the argument in the topmost recursion gets "preserved", but there's no obvious reason. I'd expected this bug to have bitten me when I wasn't looking, but doing a search through my code I noticed I've never used lists as default params - either I was lucky or I read this at some point and it stuck in the back of my head. Reading about the pitfall, I still see no reason for this behaviour, only "This behavior can occasionally be useful. In general, just watch out for unwanted side effects." When is it useful? Btw, Miguel, when I pasted your code in my shell, I got a mix of tabs and spaces (pitfall #1 :)). You could also move "printList.append()" outside the if-else because you do it regardless of the condition and you could get rid of the "if not obejcto.__class__.__bases__", because it's in the else clause which is *only* executed if not objecto.__class__.__bases__ anyway. Result: def doprint(objecto, pl=[]): """Prints a class hierarchy given an object. Works only with single inheritance hierarchies.""" printList = pl[:] # make copy instead of modifying in-place printList.append(objecto.__class__.__name__) if objecto.__class__.__bases__: recurObjecto = objecto.__class__.__bases__[0]() doprint(recurObjecto, printList[:]) else: i = 0 for klass in printList: print i * ' ' + klass i += 1 Seems to work ok, though given the circumstances I'd avoid using the list altogether and making the default param None, converting that to an empty list internally. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From mjekl at clix.pt Sun Oct 5 17:57:32 2003 From: mjekl at clix.pt (mjekl@clix.pt) Date: Sun Oct 5 17:55:47 2003 Subject: [Tutor] function local var problem :-(( Message-ID: Thank you all for the clear explanations. I checked-out the link supplied by Lloyd Kvam. Many Txs Lloyd for the suberb explanation and on-the-spot great link! Hi Gregor, Your right about everything, except that: >>> printHierarchy(oSub2, []) # is a sintax error Best Regards, Miguel > Hi Miguel, > > you ran into a well known pitfall, which you can observe > in a very simple case here: > > >>> def test(l=[]): > l.append(1) > print l > > >>> test() > [1] > >>> for i in range(3): > test() > > [1, 1] > [1, 1, 1] > [1, 1, 1, 1] > > it occurs if you use an object as default argument > which is *mutable*, for instance a list. > > then l points to an object, which is created > only when the function is *defined*, notwhen it > is called. > > As long as there is no new assignment to l, this object > is retained and can be changed if it's mutable. > This is done in your example and in the one above. > Every new function call uses the actual state of l. > > Remark: As far as I see you could solve your problem > by deleting the defaultargument in the definition and then > call > > >>> printHierarchy(oSub2, []) > > Hope that helps, > Gregor > > > mjekl@clix.pt schrieb: > > >Hi, > > > >I'm new here and with programming. I've been learning on my own and cannot > >understand what happens with this function I created. > > > >The function is in it's own module that I import into shell. > > > >###### module1.py ###### > > > >def printHierarchy(objecto, printList=[]): > > """Prints a class hierarchy given an object. > > Works only with single inheritance hierarchies.""" > > > > if objecto.__class__.__bases__: > > printList.append(objecto.__class__.__name__) > > recurObjecto = objecto.__class__.__bases__[0]() > > return printHierarchy(recurObjecto, printList) > > else: > > printList.append(objecto.__class__.__name__) > > > > if not objecto.__class__.__bases__: > > i = 0 > > for klass in printList: > > print i * ' ' + klass > > i += 1 > > else: > > return printList > > > >#################### > > > >in shell I created a hierarchy of three classes: > >class Sup; class Sub1(Sup); class Sub2(Sub1) > > > >Then: > > > > > >>>>oSub2 = Sub2() > >>>>printHierarchy(oSub2) > >>>> > >>>> > >Sup > > Sub1 > > Sub2 > > > > > > > >The problem is that if I call the function again I get: > > > > > >>>>printHierarchy(oSub2) > >>>> > >>>> > >Sup > > Sub1 > > Sub2 > > Sup > > Sub1 > > Sub2 > > > > > > > >The problem to me is that I think that the var printList is local and that > >it is initialized every time the function is called. But results contradict > >this assumption. So I tried to investigate the namespaces and found no > >references to var printList. I guess my investigation is bad (In shell I > >issued dir() and dir(module1) > >and got nothing. Also tried to use: > > from module1 import printHierarchy > >But didn't work either. Can someone please help me? > > > >Python 2.2 winXP > > > >Txs, > >Miguel > > > >Clix Rapidix - Aumente até 6X a velocidade da sua Internet > >Adira em http://acesso.clix.pt e comece logo a navegar > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > Clix Rapidix - Aumente até 6X a velocidade da sua Internet Adira em http://acesso.clix.pt e comece logo a navegar From mjekl at clix.pt Sun Oct 5 18:16:20 2003 From: mjekl at clix.pt (mjekl@clix.pt) Date: Sun Oct 5 18:14:35 2003 Subject: [Tutor] function local var problem :-(( Message-ID: Hi Gregor, I was just in the process of writting an apologie mail. I confused function def with function call, so I tested (the wrong statement): def printHierarchy(objecto, []): # this is wrong And you where talking about the call: >>> printHierarchy(oSub2, []) # this is right I'm sorry for making this mistake. Sincerely, Miguel > > mjekl@clix.pt schrieb: > > >... > >Hi Gregor, > > > >Your right about everything, except that: > > > > > > > >>>>printHierarchy(oSub2, []) # is a sintax error > >>>> > >>>> > > > >Best Regards, > >Miguel > > > > > Hello Miguel? > When I wrote > > >>Remark: As far as I see you could solve your problem > >>by deleting the defaultargument in the definition > >> > I meant that you could write > > def printHierarchy(objecto, printList): > """Prints a class hierarchy given an object. > Works only with single inheritance hierarchies.""" > ... > > deleting the default argument for the second parameter but keeping the > parameter itself. > What is wrong the with > > >>and then > >>call > >> > >> >>> printHierarchy(oSub2, []) > >> > Regards, Gregor > > Clix Rapidix - Aumente até 6X a velocidade da sua Internet Adira em http://acesso.clix.pt e comece logo a navegar From alan.gauld at blueyonder.co.uk Sun Oct 5 18:38:51 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Oct 5 18:37:48 2003 Subject: [Tutor] pointers for python? References: <200310041210.01431.thomi@imail.net.nz><00dc01c38acb$47037930$6401a8c0@xp> <200310051118.09631.thomi@imail.net.nz> Message-ID: <010b01c38b91$734004c0$6401a8c0@xp> > under C, you'd have to pass a pointer to A in order to modify it, > correct? It is one solution but is not even good practice in C. The reason why it's sometimes necessary is that C can only return a single value from a function so where multiple return values might be needed (like scanf say) then passing pointers (or references in C++) is the only solution. But C (unlike Pascal or ADA) does not have a "procedure" construct only a functuion - which by definition has a return value - and pre ANSI didn't even encourage void returns, so that all the standard library functions return a value (even printf - the number of characters printed) So that: > table = gtk.Table(3,2,gtk.FALSE) > fill_table(table,["Label 1 text","label 2 text","Label 3 text"]) Is not good C style either(you are ignoring the return value of fill_table), its just unfortunately one that has become common. (This is why tools like lint will complain about printf() statements where the return value is not used.) > table = fill_table(table,["Label 1 text","label 2 text","Label 3 text"]) This is good style and practice from a computing science point of view regardless of language. Its a matter of improving reliability and reusability if functions don't have side effects - and that includes changing the parameters passed to them. > As i said in an earlier mail, the question was purely one of > discovery, which arose when comparing C++ and python code ;) Incidentally, this is the first time you mentioned C++ instead of C. C++ introduced the concept of references specifically to help deal with this issue and reduce the need to pass pointers. Thus in C++ it is considered preferable to define: void foo(int& i){...} to void foo(int* ip){...} Anyway, these are largely niceties of style and of no real significance in Python where you have no such choices, and you can also define multiple return values (actually a tuple) and so avoid even the scanf problem. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From idiot1 at netzero.net Sun Oct 5 20:21:44 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Oct 5 20:20:48 2003 Subject: [Tutor] bug hunt In-Reply-To: References: Message-ID: <3F80B598.4070809@netzero.net> Pity. The cgiserver module builds a dictionary with all the environment variables in it for a script to use. THEY EXIST ALREADY. But there is no provision for parsing a .shtml script, detecting ssi tags, and replacing them with the required output. Therefore, this server could not handle an imbedded hit counter in a webpage, nor imbed script output as part of a page. And quite a number of servers apart from apache honor ssi. So close, and yet so far... A.M. Kuchling wrote: > > On Sunday, October 5, 2003, at 11:27 AM, Kirk Bailey wrote: > >> The servers do not respect ssi includes. Yet the modules list code to >> handle such, although I am not up to speed enough to debug them. As >> this is defined in the modules, I have the qurious duty to repport a >> possible bug in the cgiHTTPServer.py module. > > > I don't believe anything in the Python core has ever supported > server-side includes; they're mostly an Apache thing. > > --amk > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From tony at tcapp.com Mon Oct 6 02:08:46 2003 From: tony at tcapp.com (Tony Cappellini) Date: Mon Oct 6 02:12:14 2003 Subject: [Tutor] Instantiating a derived class:Does the constructor need the same args as the parent class ? Message-ID: <5.1.0.14.0.20031005224821.01bc0e40@smtp.sbcglobal.net> Danny- One of your previous posts almost addresses my question, but ..... Re: [Tutor] Classes by Daniel Yoo Apr 4 2001 1:45AM When instantiating an instance of a derived class, should the derived class constructor have the same args as the parent class constructor, as a minimum, as well as any args specifically required by the derived class ? The derive class is specializing the class Definition, by adding a class member to the Macro class, but still needs to have access to the members in the parent class. From what I can see, The only way to instantiate the subclass, is to pass the arguments to the derived class constructor, and in turn,pass them to the parent class constructor (even though my code below doesn't explicitly do this yet). However, something feels wrong with having the same args for the derived class, as those of the parent class. ################################################ class Definition: def __init__(self,MacroFilename,Linenum,Context): self.Filename = MacroFilename self.FileLinenum = Linenum self.Context = Context ################################################ class Macro(Definition): def __init__(self,MacroName): self.MacroName = MacroName -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031005/6787c2b7/attachment.html From jim_938 at hotmail.com Mon Oct 6 04:10:15 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon Oct 6 04:10:25 2003 Subject: [Tutor] Private and Public variables Message-ID: Hello, I hope this must have been discussed already on the list. Can some one point me towards some stuff where i can know about ''Private and public variables'' in a class in python. Thanks in advance for this one and also thanks for the previous responses from the tutor. With best regards, James _________________________________________________________________ Get Married! http://www.bharatmatrimony.com/cgi-bin/bmclicks1.cgi?74 Search from 7 lakh Brides & Grooms. From james_royus at eudoramail.com Mon Oct 6 04:27:59 2003 From: james_royus at eudoramail.com (james roy) Date: Mon Oct 6 04:28:21 2003 Subject: [Tutor] conversion to a fixed_no Message-ID: Hello, I am new to python and is having some problem while writing some module in python. Actually i am writing a code in which i am needed to convert a no. into a fixed_no where the fixed_no's specification is like this: fixed_no is a 32-bit representation of a binary fraction. A fixed_no is a signed quantity, with the two's complement of the entire word used to represent negation. Of the 32 bits in a fixed_no, exactily 12 are to the left of the binary point; thus the largest fixed_no value is 2048-2^(-20), and the smallest is -2048. Can someone suggest me sthing regarding writing a module to convert a no.into a fixed_no according to the way i have written above. I'll be highly thankful for this. Thanks a lot. Regards, Jimmy roy Need a new email address that people can remember Check out the new EudoraMail at http://www.eudoramail.com From glingl at aon.at Mon Oct 6 04:36:01 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Oct 6 04:37:52 2003 Subject: [Tutor] Private and Public variables In-Reply-To: References: Message-ID: <3F812971.4020201@aon.at> Jimmy verma schrieb: > Hello, > > I hope this must have been discussed already on the list. Can some one > point me towards some stuff where i can know about ''Private and > public variables'' in a class in python. Hi Jimmy, for a first answer have a look at http://diveintopython.org/object_oriented_framework/private_functions.html including the footnote. (It's part of the "dive into python" - book: http://diveintopython.org/index.html) Does this suffice? If not, feel free to ask more questions Regards, Gregor > > From op73418 at mail.telepac.pt Mon Oct 6 10:06:33 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Oct 6 10:05:07 2003 Subject: [Tutor] Private and Public variables In-Reply-To: References: Message-ID: >Hello, > >I hope this must have been discussed already on the list. Can some one point >me towards some stuff where i can know about ''Private and public >variables'' in a class in python. > > This is not a direct answer to J. Verma (G. Lingl already did that) ut to make a general question to the Tutor's Python list: What are your experiences in using protected and private attributes? I want to frame the discussion in the context of one article by H. Nowak http://zephyrfalcon.org/labs/beginners_mistakes.html where one of the Beginner's mistakes is, and I quote: "Mistake 2: writing "language X" code in Python [text snipped] -You're really paranoid about data hiding (some would call this "encapsulation"), and/or write getters and setters for all object attributes. (Java, C++, Delphi)" I tend to make this "mistake" a lot. I started using Python when Python 2.2 came out, when, in particular, properties became available. My experience was mostly in Java where I really was paranoid about data hiding. These Java habits were carried along and made their imprint on my Python code, but what's more important, after 2 years they are still with me. I think one of the reason's why is because I tend to favor (following the gang of 4) composition to inheritance. As such, it is very important that my classes have clean and small interfaces, leaking as little as possible to the outside world. These interfaces should also be "recognizable", e.g. they follow the interfaces of the Python objects as much as possible. A simple example: whenever I have an iterable container that I want to make mutable I had methods: def append(self, elem): """Append an element.""" def remove(self, elem): """Remove an element.""" So, what do you guys think? With my best regards, G. Rodrigues From project5 at redrival.net Mon Oct 6 10:46:44 2003 From: project5 at redrival.net (Andrei) Date: Mon Oct 6 10:48:50 2003 Subject: [Tutor] Combobox - SetValue based on selection Message-ID: Hello, I have a combobox with a number of predefined items. When an item is chosen, I don't want that item itself to be set as value in the text field of the combobox, but a text *associated* with that item (using a dictionary). E.g. if item "1" is chosen, the text field should say "one". I tried EVT_COMBOBOX, but after my function is processed, the associated text is replaced by the selected item again in the text field of the combobox. How can I solve this? Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Mon Oct 6 10:48:45 2003 From: project5 at redrival.net (Andrei) Date: Mon Oct 6 11:10:38 2003 Subject: [Tutor] Re: Combobox - SetValue based on selection In-Reply-To: References: Message-ID: Oops, this one was meant to go to the wxPython list :). > Hello, > > I have a combobox with a number of predefined items. When an item is > chosen, I don't want that item itself to be set as value in the text > field of the combobox, but a text *associated* with that item (using a > dictionary). E.g. if item "1" is chosen, the text field should say > "one". I tried EVT_COMBOBOX, but after my function is processed, the > associated text is replaced by the selected item again in the text field > of the combobox. > > How can I solve this? > > Andrei > > ===== > Mail address in header catches spam. Real contact info (decode with rot13): > cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V > ernq gur yvfg, fb gurer'f ab arrq gb PP. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From irridian at canada.com Mon Oct 6 12:17:44 2003 From: irridian at canada.com (irridian@canada.com) Date: Mon Oct 6 12:17:51 2003 Subject: [Tutor] (no subject) Message-ID: <20031006091744.1973.h020.c009.wm@mail.canada.com.criticalpath.net> From irridian at canada.com Mon Oct 6 12:32:00 2003 From: irridian at canada.com (irridian@canada.com) Date: Mon Oct 6 12:32:14 2003 Subject: [Tutor] Time tuple comparison Message-ID: <20031006093200.12457.h011.c009.wm@mail.canada.com.criticalpath.net> Hi I'm a newbie to python and am trying to write a program that takes user input and compares it to a time signal which I find out is a tuple.How can you take the year,month date from the time tuple and commpair to interger values from user input?I have dived into the black hole of pythhon.org but come up empty. import time YourDate = input("Enter your date eg.(year,month,day)(2003,10,6 )") Rdate = time.localtime(time.time()) From glingl at aon.at Mon Oct 6 12:59:32 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Oct 6 13:02:38 2003 Subject: [Tutor] Time tuple comparison In-Reply-To: <20031006093200.12457.h011.c009.wm@mail.canada.com.criticalpath.net> References: <20031006093200.12457.h011.c009.wm@mail.canada.com.criticalpath.net> Message-ID: <3F819F74.9010508@aon.at> irridian@canada.com schrieb: >Hi I'm a newbie to python and am trying to write a >program that takes user input and compares it to a time >signal which I find out is a tuple.How can you take the >year,month date from the time tuple and commpair to >interger values from user input?I have dived into the >black hole of pythhon.org but come up empty. >import time >YourDate = input("Enter your date >eg.(year,month,day)(2003,10,6 )") >Rdate = time.localtime(time.time()) > In your example you have: >>> YourDate (2003, 10, 6) >>> Rdate (2003, 10, 6, 18, 52, 34, 0, 279, 1) In Python you can use slices of sequances, for instance of tuples: >>> Rdate[2:7] (6, 18, 52, 34, 0) >>> Rdate[5:] (34, 0, 279, 1) >>> Rdate[:3] (2003, 10, 6) So you can compare the slice from the last example with YourDate: >>> YourDate == Rdate[:3] True This certainly is nicer than the classical clumsy >>> YourDate[0] == Rdate[0] and YourDate[1] == Rdate[1] and YourDate[2] == Rdate[2] True HTH, Gregor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From bgailer at alum.rpi.edu Mon Oct 6 17:18:00 2003 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Oct 6 17:20:20 2003 Subject: [Tutor] conversion to a fixed_no In-Reply-To: References: Message-ID: <6.0.0.22.0.20031006151112.034f1c30@66.28.54.253> At 02:27 AM 10/6/2003, james roy wrote: >Hello, > >I am new to python and is having some problem while writing some module in >python. Actually i am writing a code in which i am needed to convert a no. >into a fixed_no where the fixed_no's specification is like this: > > >fixed_no is a 32-bit representation of a binary fraction. A fixed_no is a >signed quantity, with the two's complement of the entire word used to >represent negation. Of the 32 bits in a fixed_no, exactily 12 are to the >left of the binary point; thus the largest fixed_no value is 2048-2^(-20), >and the smallest is -2048. > >Can someone suggest me sthing regarding writing a module to convert a >no.into a fixed_no according to the way i have written above. In what form is the input to this process? For the sake of discussion I will assume you start with 2 integers (L,R), one representing the part to the left and the other the part to the right. Ignoring sign for now, the desired result is L<<12 + R. How will you express the sign? Will either L or R be negative or is there a third parameter to indicate the sign? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 -------------- next part -------------- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.521 / Virus Database: 319 - Release Date: 9/23/2003 From pythontutor at venix.com Mon Oct 6 17:33:13 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Oct 6 17:33:47 2003 Subject: [Tutor] translating some python code to perl In-Reply-To: References: Message-ID: <3F81DF99.3010501@venix.com> Thanks to Danny, the Perl folks who wanted my transformed python-to-perl code are happy. (I just got the email saying so.) However, I thought I should post a followup. I'm not sure how Danny was able to avoid typing a YIKES! when he saw my class. Overriding __repr__ to emit perl code is a very bad idea. In general, you want x = eval( repr( x)) to be true. Clearly emitting perl code breaks that expectation very badly. I've mangled Danny's code slightly (e.g.sorting the dictionary keys), but if anyone else finds the need to generate perl data from python data, this could be a useful starting point. #### def renderObject(obj): if isinstance(obj, dict): return renderDictionary(obj) elif isinstance(obj, str): return renderString(obj) raise Exception, ("I don't know how to handle %s" % obj) def renderDictionary(d): rendered_items = [] keys = d.keys() keys.sort() for key in keys: rendered_items.append("%s => %s," % (renderObject(key), renderObject(d[key]))) return "{\n%s\n}" % (indent(rendered_items)) def renderString(s): return repr(s) def indent(s): indented_lines = [' ' + l for l in s] indented_lines = [l.replace('\n','\n ') for l in indented_lines] return '\n'.join(indented_lines) # remember to add the semicolon print "$perl_dict = %s;" % (renderObject(pydict)) #### Danny Yoo wrote: > > On Thu, 28 Aug 2003, Lloyd Kvam wrote: > > >>This did not generate any responses, but I thought I'd post my solution >>anyway. >>My python code (version 2.2) follows: >>#!/usr/bin/python >># py2perl.py >>'''module to handle some python to perl transformations. >>''' >>class Py2perl_dict(dict): >> >> def __init__(self, arg): >> super(Py2perl_dict, self).__init__(arg) >> for key,val in self.items(): >> if isinstance(val, dict) and not isinstance(val, Py2perl_dict): >> self[key] = Py2perl_dict(val) >> >> def __repr__(self): >> keylist = self.keys() >> keylist.sort() >> return ''.join(['{', >> ','.join(["%s => %s" % (repr(key),repr(self[key])) for key in keylist]), >> '}']) > > This code works, but also does modifications to our original dictionary. > Seems a harsh price to pay for compatibility. *grin* -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From missive at hotmail.com Mon Oct 6 18:07:34 2003 From: missive at hotmail.com (Lee Harr) Date: Mon Oct 6 18:07:39 2003 Subject: [Tutor] Re: Instantiating a derived class Message-ID: >Does the constructor need the same args as the parent class ? > >When instantiating an instance of a derived class, should the derived class >constructor >have the same args as the parent class constructor, as a minimum, as well >as any args specifically required by the derived class ? > I would say... not necessarily, although that is certainly one way to do it. Basically, until you know that you do not need to, you should be calling the parent class's constructor in your child class. Like this: class Definition: def __init__(self, MacroFilename, Linenum, Context): self.Filename = MacroFilename self.FileLinenum = Linenum self.Context = Context class Macro(Definition): def __init__(self, MacroName): mf = 'the_macrofilename' ln = 43 ct = foo # not sure where you get this Definition.__init__(self, mf, ln, ct) self.MacroName = MacroName _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From dyoo at hkn.eecs.berkeley.edu Mon Oct 6 20:02:33 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 6 20:02:38 2003 Subject: [Tutor] pointers for python? In-Reply-To: <6b8snv8odh9ve1n9a8n9v9anff5g758o4d@4ax.com> Message-ID: > >def inc(x): > > x+=1 > > > >a=1 > >inc(a) > >print a > > > >prints "1" > > > >is there a way to get the inc() function to modify the original > >variable, even though it's not in the function's scope? Hello! Not this way. This may seem like a limitation, but it's consistant and forces Python functions to be more useful for arbitrary expressions. This isn't obvious, so let's talk about it a little more. What should happen if we do something like this? inc(42) ## what happens here? Since you're familiar with C/C++, let's use a C++ example: /// using namespace std; #include // Increments reference variable x. void inc(int &x) { x++; } int main() { int number = 42; inc(number); cout << number << endl; // inc(42); <-- this won't work! } /// The commented-out line actually doesn't work --- it's a compile-time error --- because our inc() definition above can only work with variables. If we have to think about references, we now have to make this weird distinction between expressions and variables. So the reference-passing model --- distinguishing between references and values --- is just more unnecessarily involved than the simpler pass-by-value system in Python. Hope this helps! From bvg.pythontutor at freemail.hu Mon Oct 6 20:37:12 2003 From: bvg.pythontutor at freemail.hu (Gabor Borgulya) Date: Mon Oct 6 20:36:37 2003 Subject: [Tutor] pointers for python? In-Reply-To: References: Message-ID: <1065487031.3626.120.camel@catv-d5de952e.bp04catv.broadband.hu> > > >def inc(x): > > > x+=1 > > > > > >a=1 > > >inc(a) > > >print a > > > > > >prints "1" > > > > > >is there a way to get the inc() function to modify the original > > >variable, even though it's not in the function's scope? In this solution a and x are lists, which are mutable types. You could choose any mutable types. def inc(x): x[0]+=1 a=[1] inc(a) print a[0] G?bor From dyoo at hkn.eecs.berkeley.edu Mon Oct 6 21:32:17 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 6 21:32:27 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310051118.09631.thomi@imail.net.nz> Message-ID: On Sun, 5 Oct 2003, Thomi Richards wrote: > > Can you say why? The return method is by far the best technique, > > its safe and makes the function reusable - it doesn't rely on a > > variable called x existing somewhere. Its "the right way" to do it. > > well, (for example), supposing you had a situation where a function was > passed 3 variables ("A", "B", and "C"). A is an empty pygtk Table > element, B is a list of strings. > > under C, you'd have to pass a pointer to A in order to modify it, > correct? It just seemed neater doing someting like this: > > table = gtk.Table(3,2,gtk.FALSE) > fill_table(table,["Label 1 text","label 2 text","Label 3 text"]) > > than something like this: > table = fill_table(gtk.table,["Label 1 text","label 2 text","Label 3 text"]) Hi Thomi, Ok, good, a concrete example! *grin* Question: is gtk.table mutable? If so, then good news: it's perfectly possible to write the code you'd expect to write in Python. I'm not familiar enough with PyGTK to decipher: http://www.gnome.org/~james/pygtk-docs/class-gtktable.html yet --- I'm more familiar with Tkinter. But if we pass a mutable object to Python, we're perfectly set to do changes to it: ### ## Small demonstration of sending a function a mutable object from Tkinter import * def fill_frame_with_labels(frame, label_strings): for s in label_strings: Label(frame, text=s).pack() if __name__ == '__main__': root = Tk() frame = Frame(root) fill_frame_with_labels(frame, ['label1', 'label2', 'label3']) frame.pack() mainloop() ### Is this simliar to what you're looking for? What we're talking about, then, is just a matter of "mutability" and "immutability". Maybe we should refocus the subject away from pointers and to immutability concepts. Talk to you later! From dyoo at hkn.eecs.berkeley.edu Mon Oct 6 21:34:47 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Oct 6 21:34:53 2003 Subject: [Tutor] Recursion confusion In-Reply-To: Message-ID: > Fine. > > But don't rely too much on recursion in Python. Too deep recursion will > cause Python to complain. Try factorial(999) with your code. Python > does nothing like eg. Scheme which can optimize recursive algorithms > where the recursive function call is in tail position (the last function > call in the caller). By the way, there's a nice paper by the Scheme folks from the 1970's that's actually quite fun to read: ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-443.pdf http://library.readscheme.org/page1.html It explains in good detail what a "tail call" means, and how modern compilers can optimize procedure calls into fast GOTO's. From dyoo at hkn.eecs.berkeley.edu Tue Oct 7 01:26:52 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 7 01:26:58 2003 Subject: [Tutor] ANN: BayPIGgies meeting for Thursday, October 9, 2003: GUI Programming Message-ID: When: Thursday, October 9, 2003 Where: Carnegie Institute of Washington at Stanford University; Palo Alto Agenda: GUI programming Speaker: Jimmy Retzlaff Note: our regular meeting times have been rescheduled: we are now meeting on the second Thursday of each month. The topic of this month's BayPIGgies meeting is GUI programming, with an emphasis on the use of Model-View-Controller and Model-View-Presenter architectures. There will be a short presentation, followed by an open discussion. Jimmy Retzlaff will present a simple RPN calculator application, written in wxPython, that demonstrates MVC decoupling between the GUI and other program logic. This will lead to discussion of people's experiences using MVC or MVP with Python's GUI toolkits. Bring your questions and experiences to help contribute. Discussion on other GUI concepts or toolkits are welcome. For driving directions, please see: http://baypiggies.net/ From dyoo at hkn.eecs.berkeley.edu Tue Oct 7 01:59:52 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 7 01:59:57 2003 Subject: [Tutor] Code critique? [Red-Black balanced binary trees] Message-ID: Hi everyone, I had some time today, and I wanted to understand Red-Black trees a little more. I ran into them a few times on Tutor before, especially whenever asked for a sorted Dictionary. http://mail.python.org/pipermail/tutor/2002-November/018864.html They're a neat data structure. I have to admit, though, that I didn't really quite get how red-black trees worked. So I spent this afternoon coding another red-black tree module. *grin* I also wanted to get a lot more familiar with the 'unittest' module, http://www.python.org/doc/lib/module-unittest.html so the code comes with a few unit tests. Can anyone help me by critiquing the implementation and suggesting other good things to test? The code is here at the moment: http://hkn.eecs.berkeley.edu/~dyoo/python/red_black/red_black.py and as soon as it's more stable and useful (and is better documented), I can package it up using distutils. Thanks again! From thomi at imail.net.nz Tue Oct 7 04:24:54 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Tue Oct 7 04:24:52 2003 Subject: [Tutor] pointers for python? In-Reply-To: References: Message-ID: <200310072124.54876.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > > Question: is gtk.table mutable? If so, then good news: it's perfectly > possible to write the code you'd expect to write in Python. > pass.. i guess there's only one way top find out though: >>> import gtk >>> def fill_table(table,strings): ... for i in range(len(strings)): ... table.attach(gtk.Label(strings[i]),0,1,i,i+1) ... >>> window = gtk.Window() >>> table = gtk.Table(4,2,gtk.FALSE) >>> fill_table(table,['one','two','three']) >>> window.add(table) >>> window.show_all() >>> gtk.main() >>> does indeed display a window with 3 labels in it.... > > Is this simliar to what you're looking for? > this is *exactly* what I'm looking for... It almost adds to the confusion however. > > What we're talking about, then, is just a matter of "mutability" and > "immutability". Maybe we should refocus the subject away from pointers > and to immutability concepts. > AFAIK (And I'm no expert), in C, whenever a function is called, a *copy* of the variables passed to it are made, and the function uses that copy, like this: void test(int a) { a++; printf("Integer value + 1 is: %d\n",a); } if you were to call this like so: int t = 42; test(t); this would print 43, but the variable "t" (in the main scope of the program) would remain 42, because the function test() was operating on a copy of the variable, not the variable itself. is this basically correct? However, when you use pointers in C, you are passing an address in memory, which can be used like a variable. However, because you are passing the original address, the function operates on the original varibale, not a copy (this can of course be useful when you're dealing with larger structures, as it saves the program chewing memory and CPU cycles to copy something which you were effectively going to change anyway). ...which brings us back to python. Evidently, python doesn't do this, with *some* types...which is supreemly wierd.. IMO anyway... can someone offer a sensible explination as to why this happens? - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/gnhW2tSuYV7JfuERAswEAJ41KZJG/qWN5omZp2KOQEb7LPuCzACffWX8 9SQz2AqEVFHQsEegjZTmvsE= =Oaw/ -----END PGP SIGNATURE----- From krier115 at student.liu.se Tue Oct 7 04:50:11 2003 From: krier115 at student.liu.se (Kristoffer Erlandsson) Date: Tue Oct 7 04:50:29 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310072124.54876.thomi@imail.net.nz> References: <200310072124.54876.thomi@imail.net.nz> Message-ID: <20031007085011.GA2953@n14.ryd.student.liu.se> On Tue, Oct 07, 2003 at 09:24:54PM +1300, Thomi Richards wrote: [snip] > AFAIK (And I'm no expert), in C, whenever a function is called, a *copy* of > the variables passed to it are made, and the function uses that copy, like > this: > > void test(int a) > { > a++; > printf("Integer value + 1 is: %d\n",a); > } > > if you were to call this like so: > > int t = 42; > test(t); > > this would print 43, but the variable "t" (in the main scope of the program) > would remain 42, because the function test() was operating on a copy of the > variable, not the variable itself. is this basically correct? > > However, when you use pointers in C, you are passing an address in memory, > which can be used like a variable. However, because you are passing the > original address, the function operates on the original varibale, not a copy > (this can of course be useful when you're dealing with larger structures, as > it saves the program chewing memory and CPU cycles to copy something which > you were effectively going to change anyway). > > ...which brings us back to python. Evidently, python doesn't do this, with > *some* types...which is supreemly wierd.. IMO anyway... > > > can someone offer a sensible explination as to why this happens? I think the Python reference manual says things better than if I would try to explain them :). First some things about object identity and such: http://www.python.org/doc/current/ref/objects.html. And then onto the type hierarchy which lists which types are immutable and mutable among other things: http://www.python.org/doc/current/ref/types.html. Hope this helps. Regards, -- Kristoffer Erlandsson http://errl.info From kalle at lysator.liu.se Tue Oct 7 05:57:22 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Tue Oct 7 05:57:27 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310072124.54876.thomi@imail.net.nz> References: <200310072124.54876.thomi@imail.net.nz> Message-ID: <20031007095722.GM9058@i92.ryd.student.liu.se> [Thomi Richards] > ...which brings us back to python. Evidently, python doesn't do this, with > *some* types...which is supreemly wierd.. IMO anyway... > > can someone offer a sensible explination as to why this happens? Well, Python is really quite consistent in only passing references. You might find http://216.239.59.104/search?q=cache:YeykRsylhJAJ:starship.python.net/crew/mwh/hacks/objectthink.html interesting (the starship or mwh's pages seem to be having some problems, the original page gives me a 500 error). Peace, Kalle -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. From magnus at thinkware.se Tue Oct 7 07:19:11 2003 From: magnus at thinkware.se (Magnus Lycka) Date: Tue Oct 7 07:19:25 2003 Subject: =?ISO-8859-1?B?UmU6IFtUdXRvcl0gQ29tYm9ib3ggLSBTZXRWYWx1ZSBiYXNlZCBvbiBzZWxlY3Rpb24=?= Message-ID: Andrei wrote: > I have a combobox with a number of predefined items. When an item is chosen, I > don't want that item itself to be set as value in the text field of the > combobox, but a text *associated* with that item (using a dictionary). E.g. if > item "1" is chosen, the text field should say "one". I tried EVT_COMBOBOX, but > after my function is processed, the associated text is replaced by the selected > item again in the text field of the combobox. I guess you are discussing the wxPython toolkit, even if I didn't find an explicit reference. In that case I would suggest that you use the wxCallAfter function. (See wx.py, or google, it's a Python function, and thus not in the wxWindows docs.) I assume that your code in the event handling changes the combobox too early, and the standard widget processing overwrites you change. What you have to do then, is to define a separate function or method that sets the value you want. In the event handling, you use wxCallAfter to make sure that this function is called after the event processing for the combobox event is finished. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From op73418 at mail.telepac.pt Tue Oct 7 08:51:17 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Oct 7 08:49:58 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310072124.54876.thomi@imail.net.nz> References: <200310072124.54876.thomi@imail.net.nz> Message-ID: On Tue, 7 Oct 2003 21:24:54 +1300, you wrote: >-----BEGIN PGP SIGNED MESSAGE----- >Hash: SHA1 [text snnipped] >> What we're talking about, then, is just a matter of "mutability" and >> "immutability". Maybe we should refocus the subject away from pointers >> and to immutability concepts. >> > >AFAIK (And I'm no expert), in C, whenever a function is called, a *copy* of >the variables passed to it are made, and the function uses that copy, like >this: > >void test(int a) >{ > a++; > printf("Integer value + 1 is: %d\n",a); >} > >if you were to call this like so: > >int t = 42; >test(t); > >this would print 43, but the variable "t" (in the main scope of the program) >would remain 42, because the function test() was operating on a copy of the >variable, not the variable itself. is this basically correct? > >However, when you use pointers in C, you are passing an address in memory, >which can be used like a variable. However, because you are passing the >original address, the function operates on the original varibale, not a copy >(this can of course be useful when you're dealing with larger structures, as >it saves the program chewing memory and CPU cycles to copy something which >you were effectively going to change anyway). > >...which brings us back to python. Evidently, python doesn't do this, with >*some* types...which is supreemly wierd.. IMO anyway... > Python treats *every* object in the same way. Repeat after me: Python treats every object in the same way. Whenever you do an assignment as in my_var = Python just adds an entry to the current namespace. Namespaces are essentially dictionaries, so you can view the above as, in Python syntax, current_namespace["my_var"] = reference_to_ You can think of reference_to_ as a pointer (and under the hoods it is). Take notice though, that you can never get a hold of the pointer itself, because Python automatically dereferences, so that whenever you have my_var Python substitutes my_var by (mixing Python and C syntax freely) *current_namespace["my_var"] Now, when you call a function some_function(my_var) Part of the function call is just adding entrance my_var in the *local* namespace of the function, that is some_function_namespace["my_var"] = my_var The rhs my_var evaluated according to the rule above. So in your example >t = 42; >test(t); Python does the following (once again mixing Python and C syntax): . Create the object 42 (in the heap) . Stick a reference to it in the current namespace: current_namespace["t"] = &<42> . In calling the function test add an entry to test's namespace as in test_namespace["t"] = & But this is, since Python automatically dereferences, test_namespace["t"] = &<42> So what you have in your local namespace is just another reference to 42. No copies of objects are involved - only copies of pointers if you want to think in terms of the above model. Now this mental model works for *any* Python object. So suppose we have >t = []; >test(t); So you end up, in the local namespace of test, with reference to the *same list* referenced by t in the outer namespace. But a list is a mutable object. This means that there are methods that change the object inplace in contrast to immutable objects (such as numbers and strings) where *every* method returns a *new* object -- and therefore you can't change the original object, thus the immutability. Since a list is mutable you can, within the body of test, do t.append() and since the outer t references the *same* list, the changes will be visible. That is, in the outer namespace t is []. I hope I have made myself understood. Any other question, just holler. With my best regards, G. Rodrigues From dyoo at hkn.eecs.berkeley.edu Tue Oct 7 11:47:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 7 11:47:36 2003 Subject: [Tutor] pointers for python? In-Reply-To: <200310072124.54876.thomi@imail.net.nz> Message-ID: > void test(int a) > { > a++; > printf("Integer value + 1 is: %d\n",a); > } > > if you were to call this like so: > > int t = 42; > test(t); Hi Thomi, Ok, looks like we can talk C code then. *grin* When we say something like this in Python: ### def test(a): a = a + 1 print a if __name__ == '__main__': a = 42 test(a) print a ### A really rough translation to C code might be something like this: ### int* makeIntObject(int number) { int* result = (int*)(malloc(sizeof(int))); *result = number; return result; } void test(int *a) { a = makeIntObject(*a + 1); printf("%d\n", *a); } void main() { int* a = makeIntObject(42); test(a); printf("%d\n", *a); } ### In Python, all names are actually represented as pointers to objects on the heap --- none of the Python objects are actually on the stack! What's important to see is that Python treats certain types as "immutable": the language provides no way of mutating an immutable object. For example, when we say: ### a = a + 1 ### what is actually happening is the construction of a new integer, not the overwriting of an old one. '+' is defined as an operation that constructs a new integer object, given two integer operands. To see this more clearly, we can use a builtin() function called id() that's equivalent to the 'address-of' (&) operator in C: ### >>> a = 42 >>> b = a >>> id(a) 135364256 >>> id(b) 135364256 ### The object pointed to by both 'a' and 'b' are identical: the integer "box" lives at location 135364256. But when we start doing arithmetic: ### >>> a = a + 1 >>> id(a) 135364184 >>> id(b) 135364256 ### the object that 'a' points to now is distinct from what it originally pointed to. > this would print 43, but the variable "t" (in the main scope of the > program) would remain 42, because the function test() was operating on > a copy of the variable, not the variable itself. is this basically > correct? Not exactly: what's happening is that arithmetic in Python constructs a whole new integer. You're probably thinking: a ------ | 42 | ------ But what Python is actually doing is more like: ------ a -------------->| 42 | ------ It's all uniform, which is what allows Python lists to contain all kinds of things without wackiness. When we say: ### l = [1, 'two'] ### we can model this as: l ---------------> --------- | . | . | --+---+-- | \ | \ | \ V V ----- --------- | 1 | | "two" | ----- --------- It has to be pointers, or else Python lists wouldn't be able to hold different types of objects. Integers manipulation is all "immutable" because the language provides no way of mutating a number. This idea might be clearer with tuples, which are also immutable: ### >>> t = (1, 2, 3) >>> t[0] = 42 Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment ### Same idea --- the type doesn't allow internal mutation, although it's perfectly ok to redirect 't' by constructing another tuple out of the pieces of the old one: ### >>> t = (42,) + t[1:] >>> t (42, 2, 3) ### Anyway, hope this clears some of the confusion! (Or at least, doesn't contribute to the confusion... *grin*) Please feel free to ask more questions about this; it is a slightly confusing topic if you're coming from a C background, but it should make sense very soon. Good luck! From jim_938 at hotmail.com Tue Oct 7 15:22:52 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Tue Oct 7 15:22:56 2003 Subject: [Tutor] conversion to a fixed_no Message-ID: I am intending to give the input in the form of a floating point no. So if u are considering L, R to be 12.099994020394 sthing like this. L be given the value 12 and R be given the value towards the right of decimal point. I hope i am interpreting L,R rightly. Can you please elaborate a bit more about your suggestion. Also what will this code do?? just for the sake of discussing further: def fix_num(input): # To convert a no into a fixed one. val=input*16*(1<<16) return val Thanks a lot for discussing my problem. With best regards, J+ At 02:27 AM 10/6/2003, james roy wrote: Hello, I am new to python and is having some problem while writing some module in python. Actually i am writing a code in which i am needed to convert a no. into a fixed_no where the fixed_no's specification is like this: fixed_no is a 32-bit representation of a binary fraction. A fixed_no is a signed quantity, with the two's complement of the entire word used to represent negation. Of the 32 bits in a fixed_no, exactily 12 are to the left of the binary point; thus the largest fixed_no value is 2048-2^(-20), and the smallest is -2048. Can someone suggest me sthing regarding writing a module to convert a no.into a fixed_no according to the way i have written above. In what form is the input to this process? For the sake of discussion I will assume you start with 2 integers (L,R), one representing the part to the left and the other the part to the right. Ignoring sign for now, the desired result is L<<12 + R. How will you express the sign? Will either L or R be negative or is there a third parameter to indicate the sign? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 _________________________________________________________________ Buy now! Receive a gold coin on Dhan Teras. http://server1.msn.co.in/features/general/dhanteras/index.asp Celebrate prosperity! From erikprice at mac.com Tue Oct 7 22:58:25 2003 From: erikprice at mac.com (Erik Price) Date: Tue Oct 7 22:36:57 2003 Subject: [Tutor] Private and Public variables In-Reply-To: Message-ID: <491E1DD1-F93B-11D7-824C-00039351FE6A@mac.com> On Monday, October 6, 2003, at 10:06 AM, Gon?alo Rodrigues wrote: > I tend to make this "mistake" a lot. I started using Python when > Python 2.2 came out, when, in particular, properties became available. > My experience was mostly in Java where I really was paranoid about > data hiding. These Java habits were carried along and made their > imprint on my Python code, but what's more important, after 2 years > they are still with me. I think one of the reason's why is because I > tend to favor (following the gang of 4) composition to inheritance. As > such, it is very important that my classes have clean and small > interfaces, leaking as little as possible to the outside world. These > interfaces should also be "recognizable", e.g. they follow the > interfaces of the Python objects as much as possible. A simple > example: whenever I have an iterable container that I want to make > mutable I had methods: > > def append(self, elem): > """Append an element.""" > > > def remove(self, elem): > """Remove an element.""" > > > So, what do you guys think? I am the exact same way. Also a Java programmer primarily (who covets Python and is attempting to convert his cow-orkers from Perl), I definitely use too many getters and setters in Python due to Java habits. And I also tend to use a lot of delegation and composition, so I end up masking everything behind an interface. Basically I need to learn to relax more when I'm using Python. Erik From erikprice at mac.com Wed Oct 8 06:55:55 2003 From: erikprice at mac.com (Erik Price) Date: Wed Oct 8 06:33:56 2003 Subject: [Tutor] Code critique? [Red-Black balanced binary trees] In-Reply-To: Message-ID: On Tuesday, October 7, 2003, at 01:59 AM, Danny Yoo wrote: > so the code comes with a few unit tests. Can anyone help me by > critiquing > the implementation and suggesting other good things to test? Hm. I can't speak to anything about red black trees. But I am curious why you did not make left_rotate and right_rotate methods of a Node rather than functions that accept a Node and perform a side effect upon it. You chose the same approach with the tree_* functions (rather than putting them in Tree). I can only assume you had a reason to choose this approach. Erik PS: thanks for providing an example of using unittest, I had been meaning to look at this module at some point but my scripts tended to be small enough to test using simple assert code in an "if __name__ == '__main__'" section. But the unittest module is familiar, like JUnit, so I will probably use that from now on. From del_dr at yahoo.com Wed Oct 8 12:01:15 2003 From: del_dr at yahoo.com (D P) Date: Wed Oct 8 12:01:21 2003 Subject: [Tutor] processing WSDL files Message-ID: <20031008160115.26107.qmail@web40902.mail.yahoo.com> hi all! could someone explain why do I have this traceback while trying to import an wsdl file? >>> import WebService >>> policy=WebService.ServiceProxy () Traceback (most recent call last): File "", line 1, in ? File "C:\Python22\Lib\site-packages\WebService.py", line 58, in ServiceProxy return soap.get_proxy(cached_wsdl) File "C:\Python22\Lib\site-packages\soapy\soap.py", line 245, in get_proxy return WSDLProxy(uri) File "C:\Python22\Lib\site-packages\soapy\soap.py", line 304, in __init__ self._get_methods(servicenode) File "C:\Python22\Lib\site-packages\soapy\soap.py", line 412, in _get_methods method.setRequestType(porttype[method_name]['input']) File "C:\Python22\Lib\site-packages\soapy\soap.py", line 159, in setRequestType self.addParam(key,type.members[key]) File "C:\Python22\Lib\site-packages\soapy\soap.py", line 150, in addParam if not (self.all_namespaces.has_key(type.namespace)): AttributeError: 'NoneType' object has no attribute 'namespace' >>> thanks in advance! del __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From idiot1 at netzero.net Wed Oct 8 12:20:21 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Oct 8 12:19:26 2003 Subject: [Tutor] css in web software Message-ID: <3F843945.80701@netzero.net> OK, I am adding some css to my 2 wiki programs. Alas, it works fine in Internet Exploiter, but the hover effect will not operate on the Netscape Navelgator browser, no matter what I manage to do. Here is a sample of the header which is currently output by the software (I am using imbedded css): MiniWiki - WikiNature
MiniWiki
Wiki Nature
(Click for backsearch)

Everything works in ie; the hover does not work for NS. Anyone got some clueatude to share? -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From glingl at aon.at Wed Oct 8 11:55:13 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Oct 8 12:29:46 2003 Subject: [Tutor] cross sum toying Message-ID: <3F843361.2060203@aon.at> Hi! Within one hour of cross sum toying with Python 2.3 ;-) I came up with four functions for calculating the crossum of a nonnegative integer: def cross_sum1(a): # drawback: uses conversion to string return sum([int(digit) for digit in str(a)]) from math import log10 def cross_sum2(a): #drawback: uses math return sum([a%10**(i+1)//10**i for i in range(1+int(log10(1+a)))]) def cross_sum3(a): # drawback: uses recursion if a: return a%10 + cross_sum3(a//10) return 0 def cross_sum4(a): # drawback: (almost) classical s = 0 while a: a, digit = divmod(a, 10) s += digit return s Do you have a more beautiful, a substantially different or even a more Pythonic one? Gregor From pythontutor at venix.com Wed Oct 8 13:27:04 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Oct 8 13:27:16 2003 Subject: [Tutor] cross sum toying In-Reply-To: <3F843361.2060203@aon.at> References: <3F843361.2060203@aon.at> Message-ID: <3F8448E8.2060304@venix.com> Not sure why you're unhappy with version 4. It can be split into a digit generator and a summer: >>> def digit_generator(a,base=10): ... a = abs(a) ... while a: ... a,d = divmod(a,base) ... yield d (import operator) >>> def cross_sum(a): ... return reduce(operator.add,digit_generator(a),0) Both versions 3 and 4 can be easily generalized to support other number bases. I added a 0 to initialize reduce, the other alternative I considered was to have an else with the while in the generator to always produce a (leading) zero. else: yield 0 Hope this helps. Gregor Lingl wrote: > Hi! > > Within one hour of cross sum toying with Python 2.3 ;-) > I came up with four functions for calculating the crossum > of a nonnegative integer: > > def cross_sum4(a): > # drawback: (almost) classical > s = 0 > while a: > a, digit = divmod(a, 10) > s += digit > return s > > > Do you have a more beautiful, a substantially > different or even a more Pythonic one? > > Gregor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From glingl at aon.at Wed Oct 8 14:13:44 2003 From: glingl at aon.at (Gregor Lingl) Date: Wed Oct 8 14:15:36 2003 Subject: [Tutor] cross sum toying In-Reply-To: <3F8448E8.2060304@venix.com> References: <3F843361.2060203@aon.at> <3F8448E8.2060304@venix.com> Message-ID: <3F8453D8.1070902@aon.at> Lloyd Kvam schrieb: > Not sure why you're unhappy with version 4. It can be split into a > digit generator and a summer: > > >>> def digit_generator(a,base=10): > ... a = abs(a) > ... while a: > ... a,d = divmod(a,base) > ... yield d > > (import operator) > >>> def cross_sum(a): > ... return reduce(operator.add,digit_generator(a),0) Very interesting, very nice! When working with Python 2.3, I can use the now built in sum: def cross_sum5(a): return sum([digit for digit in digit_generator(a)]) Thanks for the idea! I've added this to my collection. BTW, I was not really unhappy but interested in different ways to handle this problem. Maybe the cross sum zoo will continue growing ... ... although there should be one -- and preferably only one -- obvious way to do it? ;-) Regards, Gregor From bwalling at coastdental.com Wed Oct 8 14:58:22 2003 From: bwalling at coastdental.com (Benjamin Walling) Date: Wed Oct 8 14:58:28 2003 Subject: [Tutor] css in web software Message-ID: <61119D047A3FE84E83EF2FFDA9A156A4862300@cstntexch01.coastdental.lan> A:link, A:visited, A:active { text-decoration:none; } You are missing the opening curly bracket for the text above. Making this change causes it to work for me in Mozilla Firebird. I do not have Netscape installed, but the rendering engine is (nearly) the same. Netscape/Mozilla are not as forgiving as IE in terms of bad HTML. -----Original Message----- From: Kirk Bailey [mailto:idiot1@netzero.net] Sent: Wednesday, October 08, 2003 12:20 PM To: Tutor Subject: [Tutor] css in web software OK, I am adding some css to my 2 wiki programs. Alas, it works fine in Internet Exploiter, but the hover effect will not operate on the Netscape Navelgator browser, no matter what I manage to do. Here is a sample of the header which is currently output by the software (I am using imbedded css): MiniWiki - WikiNature
MiniWiki
Wiki Nature
(Click for backsearch)

Everything works in ie; the hover does not work for NS. Anyone got some clueatude to share? -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From pythontutor at venix.com Wed Oct 8 15:47:15 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Oct 8 15:47:22 2003 Subject: [Tutor] css in web software In-Reply-To: <61119D047A3FE84E83EF2FFDA9A156A4862300@cstntexch01.coastdental.lan> References: <61119D047A3FE84E83EF2FFDA9A156A4862300@cstntexch01.coastdental.lan> Message-ID: <3F8469C3.1040803@venix.com> http://validator.w3.org/ The W3C MarkUp Validation Service While getting your HTML to be fully compliant can be a pain, my experience is that it pretty much eliminates browser problems. Benjamin Walling wrote: > A:link, A:visited, A:active { text-decoration:none; } > > You are missing the opening curly bracket for the text above. Making > this change causes it to work for me in Mozilla Firebird. I do not have > Netscape installed, but the rendering engine is (nearly) the same. > > Netscape/Mozilla are not as forgiving as IE in terms of bad HTML. > > -----Original Message----- > From: Kirk Bailey [mailto:idiot1@netzero.net] > Sent: Wednesday, October 08, 2003 12:20 PM > To: Tutor > Subject: [Tutor] css in web software > > OK, I am adding some css to my 2 wiki programs. Alas, it works fine in > Internet Exploiter, but the hover effect will not operate on the > Netscape Navelgator browser, no matter what I manage to do. Here is a > sample of the header which is currently output by the software (I am > using imbedded css): > > MiniWiki - WikiNature text="000000" links="0000FF"> border="0" cellpadding="10">
color="FF0000">MiniWiki >
Wiki > Nature
> (Click for backsearch)

> > Everything works in ie; the hover does not work for NS. Anyone got some > clueatude to share? > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From alan.gauld at blueyonder.co.uk Wed Oct 8 16:02:34 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Oct 8 16:01:47 2003 Subject: [Tutor] Private and Public variables References: Message-ID: <001e01c38dd7$1d5153a0$6401a8c0@xp> > What are your experiences in using protected and private attributes? In C++ you choose. In Smalltalk all attributes are private. In early OO LISP and DElphi all attributes were public by default. In Python all attributes are public by default but tricks exist to make them private(ish). In practice I don't find any difference in any of the approaches because as a matter of good practice I access data via methods. That is I do not use methods like getXXX very often but manipulate data via behaviour of the object. In al;most every case where a lot of getXXX/setXXX methods are being used then the law of demeter is being broken and the basic OOD should be revisited. > My experience was mostly in Java where I really was paranoid about > data hiding. These Java habits were carried along I'm not sure why Java is so paranoid but it does produice an extremely verbose style of programming. This is one reason why Java programmers nearly always wind up writing more code that C++ programmers for the same project! (IMHO) > they are still with me. I think one of the reason's why is because I > tend to favor (following the gang of 4) composition to inheritance. What does that have to do with data hiding (the correct term for private data)? > such, it is very important that my classes have clean and small > interfaces, leaking as little as possible to the outside world. Clean an small is a good principle, but has nothing(much) to do with data hiding. It only becomes significant when you define the interface as being anything that is technically accessible rather than the published set of methods. If the class author tells you not to use methods other that X,Y or Z then those are the inteface, use anything else and you have broken it. Do you want a police state or one where you can exercise free concience? > interfaces should also be "recognizable", e.g. they follow the > interfaces of the Python objects as much as possible. Again an excellent design principle. > So, what do you guys think? I think your design ideas are correct, the need for data hiding and the implied distrust of your fellow programmers is perhaps more questionable. But if you design classes to expose a behavioural interface then the ability or lack of to directly access data will not be of any concern to your users. For example how often do you even think about accessing the internal data of a file object? Do you even know what attributes are there? Do you care? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Oct 8 16:16:23 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Oct 8 16:15:33 2003 Subject: [Tutor] Private and Public variables References: <491E1DD1-F93B-11D7-824C-00039351FE6A@mac.com> Message-ID: <005001c38dd9$0bcfc010$6401a8c0@xp> > definitely use too many getters and setters in Python due to Java > habits. And I also tend to use a lot of delegation and composition, > so I end up masking everything behind an interface. It sounds like you use too many getters and setters period! :-) You should very rarely need to get data from an object. The object is responsible for managing its own data, if you are pulling the data out and manipulating it *in any way* outside of the object then that is bad OOD. Get the object to do it to itself via a descriptively named method. If you want the data to feed to another object's method then again there's something wrong and that methjod probably should be taking an object as parameter not a primitive value. Unfortunately this is where languages like Javca/C++ become unstick because their static type system requires specific types to be passed so we wind up being forced to extract more data than should be necessary... The other broken feature of Java which encourages this getter/setter business is the fact that Java breans are defined in terms of a getter/setter inteface to allow IDEs to build data discovery/introspection mechanisms. Unfortunately these methods then get mistakenly considered to be part of the geneal class interface. It might have been better if Java had used some kind of a IDE keyword to indicate that these methods should only be used by tool builders! :-( > learn to relax more when I'm using Python. That and focussing on defining class behaviours, both in Python and in Java. Every time you write a metod called getXXX or setXXX consider why you need it. Could the class itself be doing it internally via a higher level interface function? BTW The book "The Pragmatic Programmer" by Hunt and Thomas covers this topic in more depth. As do many of the writings of Peter Coad. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From erikprice at mac.com Wed Oct 8 23:32:16 2003 From: erikprice at mac.com (Erik Price) Date: Wed Oct 8 23:10:20 2003 Subject: [Tutor] Private and Public variables In-Reply-To: <005001c38dd9$0bcfc010$6401a8c0@xp> Message-ID: <2DC744E0-FA09-11D7-AF86-00039351FE6A@mac.com> On Wednesday, October 8, 2003, at 04:16 PM, Alan Gauld wrote: > It sounds like you use too many getters and setters period! > :-) You're probably right but... > You should very rarely need to get data from an object. > The object is responsible for managing its own data, if you > are pulling the data out and manipulating it *in any way* > outside of the object then that is bad OOD. Get the object > to do it to itself via a descriptively named method. I understand this in principle and I agree. However, it seems to me that in some situations, this creates a tight coupling between the object that contains the data and the object making use of it. For instance, say you have a DatabaseRecord object that has been returned by the database API (and say it is a 3rd party API, and the support contract is invalidated if you modify the source code). If you need to get the content of the DatabaseRecord, you probably want to call getValue or something. This can be used portably in many different parts of the application, because there might be many aspects of the application that need a String from the database -- however, if you try to add a method to DatabaseRecord for every case where you need to do something with the data, then DatabaseRecord becomes clunky and tightly coupled to the client code that calls it. In many cases, I agree -- get the object itself to perform the appropriate behavior. But there are times when you simply want to get some element of the data contained by an object. > The other broken feature of Java which encourages this > getter/setter business is the fact that Java breans are > defined in terms of a getter/setter inteface to allow > IDEs to build data discovery/introspection mechanisms. Good observation. > Unfortunately these methods then get mistakenly considered > to be part of the geneal class interface. It might have been > better if Java had used some kind of a IDE keyword to indicate > that these methods should only be used by tool builders! :-( A great idea -- I never really thought of this before, btw. > >> learn to relax more when I'm using Python. > > That and focussing on defining class behaviours, both in Python > and in Java. Every time you write a metod called getXXX or setXXX > consider why you need it. Could the class itself be doing it > internally via a higher level interface function? > > BTW The book "The Pragmatic Programmer" by Hunt and Thomas > covers this topic in more depth. As do many of the writings > of Peter Coad. Your advice is good, and reminds me of another good book on writing better code that I am still reading: "Refactoring" by Fowler. I will have to check out the Pragmatic Programmer sometime, but I am not in a hurry to learn Ruby (though someday I would like to). Erik From alan.gauld at blueyonder.co.uk Thu Oct 9 03:26:46 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Oct 9 03:28:07 2003 Subject: [Tutor] Private and Public variables References: <2DC744E0-FA09-11D7-AF86-00039351FE6A@mac.com> Message-ID: <006401c38e36$b23a01b0$6401a8c0@xp> > > The object is responsible for managing its own data, > > instance, say you have a DatabaseRecord object that has been returned > by the database API OK, Good example of a special case. In these situations you should probably be hiding the database record object inside an application specific class which provides the behaviour. Thus most code will talk to the "customer" object or "order" object or whatever and only the entity objects will use the database API internally. > get the content of the DatabaseRecord, you probably want to call > getValue or something..... because there might be many aspects of the > application that need a String from the database And even here, as you have just pointed out, the getValue method is a valid description of behaviour( especially in Java) since the actual data inside the record will be a float, int or String. "getValue" is in fact not a data access method but a generic behaviour that just happens to have "get" in its name, it could have been just as validly called just "value" foo = record.value() as opposed to foo = record.getValue() > to add a method to DatabaseRecord for every case where you need to do > something with the data, then DatabaseRecord becomes clunky and tightly > coupled to the client code that calls it. Yes, the generic behaviour getValue requires that you provide a method per type (possibly via polymorphism and/or subclassing) but not one for every application level access. > appropriate behavior. But there are times when you simply want to get > some element of the data contained by an object. And your example is a good one, but only in so far as the internals of a single object go. Really using databases is a way of providing persistence to objects, if you had an OO database you wouldn't need these record objects at all you'd simply instantiate the objects directly from the database. Indeed you should still do that but in the constructor do all the database access stuff. Unfortunately with an RDBMS that often results in inefficient code... so we compromise with database APIs etc. > have to check out the Pragmatic Programmer sometime, but I am not in a > hurry to learn Ruby (though someday I would like to). PP doesn't have a lot of Ruby in it, in fact it has more C++ and Java than Ruby code. In fact from a quick flick through I couldn't see *any* Ruby... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From erikprice at mac.com Thu Oct 9 06:14:41 2003 From: erikprice at mac.com (Erik Price) Date: Thu Oct 9 05:52:42 2003 Subject: [Tutor] Private and Public variables In-Reply-To: <006401c38e36$b23a01b0$6401a8c0@xp> Message-ID: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com> On Thursday, October 9, 2003, at 03:26 AM, Alan Gauld wrote: > PP doesn't have a lot of Ruby in it, in fact it has more C++ > and Java than Ruby code. In fact from a quick flick through > I couldn't see *any* Ruby... Oh. I must be thinking of some other book -- I could have sworn they had a book like this that only used Ruby. Erik From alan.gauld at blueyonder.co.uk Thu Oct 9 06:09:58 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Oct 9 06:11:41 2003 Subject: [Tutor] Private and Public variables References: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com> Message-ID: <007d01c38e4d$7e9e37b0$6401a8c0@xp> > Oh. I must be thinking of some other book -- I could have sworn they > had a book like this that only used Ruby. The same two authors wrote the first significant English book on Ruby (now available online too*) and are huge Ruby advocates, but the Pragmatic Programmer is largely not about languages per se but about general good software practice. Alan G. (*) http://www.rubycentral.com/book/index.html From tbstep at tampabay.rr.com Thu Oct 9 06:28:50 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Thu Oct 9 06:32:52 2003 Subject: [Tutor] Private and Public variables In-Reply-To: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com> References: <654DD218-FA41-11D7-AF86-00039351FE6A@mac.com> Message-ID: <200310090628.50206.tbstep@tampabay.rr.com> On Thursday 09 October 2003 06:14 am, Erik Price wrote: > Oh. I must be thinking of some other book -- I could have sworn > they had a book like this that only used Ruby. Easily confused as the book you are thinking of is "Programming Ruby - The Pragmatic Programmer's Guide". -- Todd Stephens "Good people do not need laws to tell them to act responsibly, while bad people will find a way around the laws." - Plato From ronan at melim.com.br Thu Oct 9 07:53:23 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Thu Oct 9 07:52:40 2003 Subject: [Tutor] Web development Message-ID: <200310090853.23429.ronan@melim.com.br> Hello folks, Does someone develop web applications in Python? I'd like to know how can I manipulate users in a web application. Should I use cookies? I have read about cookies but I seems that cookies works with expiration time. So, if it's true, if a user closes its browser, isn't it be loged on automatcly, once the expiration time didn't end up? And if I set a little expiration time, will the user be loged for the next page? If some could point me to a documentation that clarify my mind, it also would be great. Thanks, Ronan From bwalling at coastdental.com Thu Oct 9 08:07:30 2003 From: bwalling at coastdental.com (Benjamin Walling) Date: Thu Oct 9 08:08:42 2003 Subject: [Tutor] Web development Message-ID: <61119D047A3FE84E83EF2FFDA9A156A4862303@cstntexch01.coastdental.lan> There are two types of cookies: session and (semi) permanent. Session cookies are good for the extent of time that a user is visiting your site. In some browsers, this includes the entire length of time the browser is open, so if they visit your site, go somewhere else and come back, the cookie is still valid. If you do not set an expiration date, what you get is a session cookie. Permanent cookies will stay on the user's machine until the expiration date that you set. This means that if they close the browser, reboot, etc, your cookie is still there. Generally, web applications are stateless, and you do not know who is really on your website, you would only know the last time each user requested a page. You could then infer who you considered to be on your site by assuming that anyone that has requested a page in the last 5 minutes is on your website. As far as logging, you can find the cookie information in your webserver's logs (IIS, Apache, etc), or you can log page requests yourself. You have little to no visibility that they have closed their browser or navigated to another site. You can attempt some magic here with JavaScript, but I don't find it to be reliable. -----Original Message----- From: Ronan Lucio [mailto:ronan@melim.com.br] Sent: Thursday, October 09, 2003 7:53 AM To: tutor@python.org Subject: [Tutor] Web development Hello folks, Does someone develop web applications in Python? I'd like to know how can I manipulate users in a web application. Should I use cookies? I have read about cookies but I seems that cookies works with expiration time. So, if it's true, if a user closes its browser, isn't it be loged on automatcly, once the expiration time didn't end up? And if I set a little expiration time, will the user be loged for the next page? If some could point me to a documentation that clarify my mind, it also would be great. Thanks, Ronan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From ronan at melim.com.br Thu Oct 9 09:12:42 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Thu Oct 9 09:11:59 2003 Subject: [Tutor] Web development In-Reply-To: <61119D047A3FE84E83EF2FFDA9A156A4862303@cstntexch01.coastdental.lan> References: <61119D047A3FE84E83EF2FFDA9A156A4862303@cstntexch01.coastdental.lan> Message-ID: <200310091012.42245.ronan@melim.com.br> Benjamin, Thank you very much by the good answer... :-) Ronan Em Qui 09 Out 2003 09:07, Benjamin Walling escreveu: > There are two types of cookies: session and (semi) permanent. Session > cookies are good for the extent of time that a user is visiting your > site. In some browsers, this includes the entire length of time the > browser is open, so if they visit your site, go somewhere else and come > back, the cookie is still valid. If you do not set an expiration date, > what you get is a session cookie. Permanent cookies will stay on the > user's machine until the expiration date that you set. This means that > if they close the browser, reboot, etc, your cookie is still there. > > Generally, web applications are stateless, and you do not know who is > really on your website, you would only know the last time each user > requested a page. You could then infer who you considered to be on your > site by assuming that anyone that has requested a page in the last 5 > minutes is on your website. > > As far as logging, you can find the cookie information in your > webserver's logs (IIS, Apache, etc), or you can log page requests > yourself. > > You have little to no visibility that they have closed their browser or > navigated to another site. You can attempt some magic here with > JavaScript, but I don't find it to be reliable. > > -----Original Message----- > From: Ronan Lucio [mailto:ronan@melim.com.br] > Sent: Thursday, October 09, 2003 7:53 AM > To: tutor@python.org > Subject: [Tutor] Web development > > Hello folks, > > Does someone develop web applications in Python? > > I'd like to know how can I manipulate users in a web application. > Should I use cookies? > I have read about cookies but I seems that cookies works with expiration > time. So, if it's true, if a user closes its browser, isn't it be loged > on automatcly, once the expiration time didn't end up? > > And if I set a little expiration time, will the user be loged for the > next page? > > If some could point me to a documentation that clarify my mind, it also > would be great. > > Thanks, > Ronan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Ronan Lucio Melim Internet Provider From python at rcn.com Thu Oct 9 09:35:41 2003 From: python at rcn.com (Raymond Hettinger) Date: Thu Oct 9 09:36:21 2003 Subject: [Tutor] cross sum toying In-Reply-To: <3F8448E8.2060304@venix.com> Message-ID: <000001c38e6a$3c2a7980$e841fea9@oemcomputer> Here is one more version to play with: >>> from itertools import imap >>> def cross_sum(n, codezero=ord('0')): s = str(n) return sum(imap(ord, s)) - len(s) * codezero >>> cross_sum(9851) 23 Raymond Hettinger ################################################################# ################################################################# ################################################################# ##### ##### ##### ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ################################################################# ##### ##### ##### ################################################################# ################################################################# ################################################################# From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 12:28:27 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 12:28:33 2003 Subject: [Tutor] Code critique? [Red-Black balanced binary trees] In-Reply-To: Message-ID: On Wed, 8 Oct 2003, Erik Price wrote: > > so the code comes with a few unit tests. Can anyone help me by > > critiquing the implementation and suggesting other good things to > > test? > > Hm. I can't speak to anything about red black trees. But I am curious > why you did not make left_rotate and right_rotate methods of a Node > rather than functions that accept a Node and perform a side effect upon > it. Hi Erik, No particular reason, actually. I agree with you: it does make sense to rearrange the code so that the node-rotation function are actual members of the Node class. > You chose the same approach with the tree_* functions (rather than > putting them in Tree). I can only assume you had a reason to choose > this approach. Nope. *grin* On the other hand, I'm thinking of wrapping the red-black trees using a higher level interface, to make them look like dictionaries. I think my original plan was to write the base using plain old functions, and show how one can write a nice OOP layer on top of it. > PS: thanks for providing an example of using unittest, I had been > meaning to look at this module at some point but my scripts tended to be > small enough to test using simple assert code in an "if __name__ == > '__main__'" section. But the unittest module is familiar, like JUnit, > so I will probably use that from now on. Unit testing is actually pretty fun, once you get into a diabolical frame of mind. *grin* It's definitely mandatory for anything serious I write now, now that I've seen how many bugs actually get stomped by good unit tests! As a concrete example, when I read the initial pseudocode for doing insertion into the Red-Black tree, I actually misread some of the indentation. The pseudocode in "Introduction to Algorithms" looked something like this: else if z = right[p[z]] then z <- p[z] left-rotate(T, z) color[p[z]] <- BLACK color[p[p[z]]] <- RED right-rotate(T, p[p[z]]) And even though the pseudocode looks remarkably like Python code, I had incorrectly transcribed this in Python as: elif x == x.p.right: x = x.p left_rotate(tree, x) x.p.color = BLACK x.p.p.color = RED right_rotate(tree, x.p.p) Silly indentation bug. *grin* Thankfully, the error in this code immediately showed up as soon as I tried inserted three elements into my structure, so I was able to pick out the offending bug in a few minutes. Talk to you later! From rafael.sousa at netcabo.pt Thu Oct 9 13:25:18 2003 From: rafael.sousa at netcabo.pt (rafael.sousa) Date: Thu Oct 9 13:28:26 2003 Subject: [Tutor] How can I convert a bin string to a hex string? Message-ID: <2305CFC39C15AA4896E06E5C91C509EF0299832F@VS2.hdi.tvcabo> Such as the binary contents of a jpeg image? I'm writing the code to dynamically create a RTF (Rich Text Format) document. In order to insert a picture, it's recommended in the specification that its contents are written in hex. I read the binary content to a regular python string, but then I would need to convert it to another string, this time in hex (which would naturally have the double of the length of the original bin string). Can anyone help? Thanks in advance! From erikprice at mac.com Thu Oct 9 13:44:22 2003 From: erikprice at mac.com (Erik Price) Date: Thu Oct 9 13:44:36 2003 Subject: [Tutor] Web development Message-ID: <668593.1065721462012.JavaMail.erikprice@mac.com> On Thursday, October 09, 2003, at 07:53AM, Ronan Lucio wrote: >Hello folks, > >Does someone develop web applications in Python? Sure, an interesting project for web app development is Webware. >I'd like to know how can I manipulate users in a web application. >Should I use cookies? Cookies can be a convenient way of letting your webapp know which user is making that particular HTTP request. Another way to do it is to embed an identification string into the URI of all hyperlinks in your webapp. I would be surprised if webware did not provide a mechanism for automatically generating these kinds of URIs. >I have read about cookies but I seems that cookies works >with expiration time. So, if it's true, if a user closes its browser, >isn't it be loged on automatcly, once the expiration time didn't >end up? You should read more about how cookies work, you can limit the lifetime of a cookie to only last as long as the current session (until the user quits the browser instance): >And if I set a little expiration time, will the user be loged for >the next page? > >If some could point me to a documentation that clarify my mind, >it also would be great. Hopefully the above will help answer some questions about cookies in web application development. Erik From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 14:02:07 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 14:02:13 2003 Subject: [Tutor] How can I convert a bin string to a hex string? In-Reply-To: <2305CFC39C15AA4896E06E5C91C509EF0299832F@VS2.hdi.tvcabo> Message-ID: On Thu, 9 Oct 2003, rafael.sousa wrote: > Such as the binary contents of a jpeg image? > I'm writing the code to dynamically create a RTF (Rich Text Format) > document. In order to insert a picture, it's recommended in the > specification that its contents are written in hex. > I read the binary content to a regular python string, but then I would > need to convert it to another string, this time in hex (which would > naturally have the double of the length of the original bin string). Hi Rafael, Ah, then the 'binascii' module should be suitable for this: http://www.python.org/doc/lib/module-binascii.html The binascii.hexlify() function should be exactly what you're looking for. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 14:13:22 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 14:13:34 2003 Subject: [Tutor] processing WSDL files In-Reply-To: <20031008160115.26107.qmail@web40902.mail.yahoo.com> Message-ID: On Wed, 8 Oct 2003, D P wrote: > hi all! > > could someone explain why do I have this traceback > while trying to import an wsdl file? > > > >>> import WebService > >>> policy=WebService.ServiceProxy() Hi D P, I'd suspect that there's a bug in the WSDL module; it looks like part of the software is sending the None object over to a method that doesn't expect it. From the traceback: > File "C:\Python22\Lib\site-packages\soapy\soap.py", > line 150, in addParam > if not > (self.all_namespaces.has_key(type.namespace)): > AttributeError: 'NoneType' object has no attribute The 'soapy' module is saying that something is not right --- 'type' here is set to None. But at the moment, I can't figure out the real cause of this without more information. In particular, you mention: ### >>> import WebService >>> policy=WebService.ServiceProxy() ### Can you tell us the link to the wsdl location? If so, that'll help enormously, since then we'll be better equipped to replicate the situation and test a solution. Still, you may really want to talk to the Python Web Services folks for your question: http://pywebsvcs.sourceforge.net/ I'm not sure how many of us are familiar with WSDL. But I'm positive the Python web services folks there know what they are doing. They have a mailing list that you can use: http://sourceforge.net/mailarchive/forum.php?forum_id=1729 Good luck to you! From camartin at snet.net Thu Oct 9 18:11:14 2003 From: camartin at snet.net (camartin@snet.net) Date: Thu Oct 9 18:08:19 2003 Subject: [Tutor] skipping lines Message-ID: <3F85DD02.4060109@snet.net> I have a piece of code that reads in a file line by line into lists. It then processes the file list by list and writes out the file processed line by processed line. This works fine unless I have a blank line. An example of the code (the actual code is more complicated but it works unless there are blank lines) is shown below, # file to open CSV files or plain delimited text. As one reads # each line convert the date to ordinal number, then write out # the line into a CSV file from datetime import date import string from string import * filename = raw_input("Enter the filename(make sure you enter the full path): ") f = open(filename,'r') g = open("c:\python23\outtest3.txt", 'w') for line in f.xreadlines(): words = line.rstrip().split() S = words[9] print >>g,S f.close() g.close() As I said above this writes what I expect but the error message I get is what one expects for a blank line namely there is no index S[9]. Traceback (most recent call last): File "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Python23\Script2.py", line 16, in ? S = words[9] IndexError: list index out of range I've tried using an if statement on not empty line(like I can do in MatLab) and I've tried a bunch of other things but I've not been successful. This seems so trivial but I'm not getting it. Thanks in advance. Cliff From brian_ashley99 at hotmail.com Fri Oct 3 01:16:03 2003 From: brian_ashley99 at hotmail.com (brian ashley) Date: Thu Oct 9 20:18:03 2003 Subject: [Tutor] Can you clarify these terms Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031003/8582e7c1/attachment.html From DLLBIA001 at mail.uct.ac.za Sun Oct 5 07:30:52 2003 From: DLLBIA001 at mail.uct.ac.za (UCT Student - DLLBIA001) Date: Thu Oct 9 20:18:09 2003 Subject: [Tutor] Random numbers Message-ID: <3F8000EC.5C49E947@mail.uct.ac.za> Hi! i was just wandring if you could not help me to generate 25 random numbers in the range of 0 to 24 without any number repeating. if i were then to put this numbers onto a grid with 25 squares how would i go about it. the grid and squares have already been made but how to place the numbers i am uncertain of. thank you Bianca From gulasachet at hotmail.com Sun Oct 5 12:26:43 2003 From: gulasachet at hotmail.com (cordillia contessa) Date: Thu Oct 9 20:18:14 2003 Subject: [Tutor] barcode creation Message-ID: I have to create barcode but have no slight idea of what is needed and how to create it. Help... Anyone... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031006/a4c5867f/attachment.html From James.McCarney at bnc.ca Mon Oct 6 14:11:57 2003 From: James.McCarney at bnc.ca (James.McCarney@bnc.ca) Date: Thu Oct 9 20:18:17 2003 Subject: [Tutor] Traceback error in os.remove Message-ID: In my script I get the following error.... Traceback (most recent call last): File "", line 1, in -toplevel- os.remove("Z:/Foo & D?ploiement/Foo/Rel?ve foo/Fooooooo/Foo de rel?ve/foo_de_rel?ve_chm.bak") OSError: [Errno 2] No such file or directory: 'Z:/Foo & D\xe9ploiement/Foo/Rel\xe8ve foo/Fooooooo/Foo de rel\xe8ve/foo_de_rel\xe8ve_chm.bak' It appears that Python is having difficulty interpreting diacritical marks.... Any way to get it to behave? Thanks all Merci et meilleures salutations. James Alexander (Alex) McCarney, conseiller CGI s/GRT & CMI, Banque Nationale du Canada mailto:james.mccarney@bnc.ca mailto:james.mccarney@cgi.com T?l. : (514) 394-5000, poste 5197 Fax : (514) 394-6888 700, rue de la Gaucheti?re ouest, 23e ?tage Montr?al (Qu?bec) H3B 4L1 Avis de confidentialit? : ce message peut contenir des renseignements confidentiels appartenant exclusivement au Groupe CGI inc. ou ? ses filiales. Si vous n'?tes pas le destinataire indiqu? ou pr?vu dans ce message (ou responsable de livrer ce message ? la personne indiqu?e ou pr?vue) ou si vous pensez que ce message vous a ?t? adress? par erreur, vous ne pouvez pas utiliser ou reproduire ce message, ni le livrer ? quelqu'un d'autre. Dans ce cas, vous devez le d?truire et vous ?tes pri? d'avertir l'exp?diteur en r?pondant au courriel. From TLLITU001 at mail.uct.ac.za Tue Oct 7 04:42:14 2003 From: TLLITU001 at mail.uct.ac.za (TLLITU001@mail.uct.ac.za) Date: Thu Oct 9 20:18:19 2003 Subject: [Tutor] Placing other widgets on a frame Message-ID: <3F827C66.CF12A95D@mail.uct.ac.za> To whom it may concern For the past two weeks i've been working on this project were I have to design a sorting puzzle game. I'm finding it very difficult to connect everything together. Yesterday I spend the whole day trying to place a button on a frame, i couldn't do it ! I need some help on whole thing , CAN YOU PLEASE HELP ME!! TUMI,UCT,SA From surfinserpent at yahoo.com Wed Oct 8 22:19:58 2003 From: surfinserpent at yahoo.com (joseph reaves) Date: Thu Oct 9 20:18:22 2003 Subject: [Tutor] help Message-ID: <20031009021958.50203.qmail@web80504.mail.yahoo.com> how do i get started? --------------------------------- Do you Yahoo!? The New Yahoo! Shopping - with improved product search -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031008/ced457db/attachment.html From anna at aleax.it Thu Oct 9 18:39:13 2003 From: anna at aleax.it (Anna Ravenscroft) Date: Thu Oct 9 20:18:24 2003 Subject: [Tutor] skipping lines In-Reply-To: <3F85DD02.4060109@snet.net> References: <3F85DD02.4060109@snet.net> Message-ID: <200310100039.13287.anna@aleax.it> On Friday 10 October 2003 12:11 am, camartin@snet.net wrote: > I have a piece of code that reads in a file line by line into lists. It > then processes the file list by list and writes out the file processed > line by processed line. This works fine unless I have a blank line. An > example of the code (the actual code is more complicated but it works > unless there are blank lines) is shown below, > > # file to open CSV files or plain delimited text. As one reads > # each line convert the date to ordinal number, then write out > # the line into a CSV file > from datetime import date > import string > from string import * > > > filename = raw_input("Enter the filename(make sure you enter the full > path): ") > f = open(filename,'r') > g = open("c:\python23\outtest3.txt", 'w') > > > for line in f.xreadlines(): > words = line.rstrip().split() > S = words[9] > print >>g,S > > > f.close() > g.close() > > > As I said above this writes what I expect but the error message I get is > what one expects for a blank line namely there is no index S[9]. > > Traceback (most recent call last): > File > "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Python23\Script2.py", line 16, in ? > S = words[9] > IndexError: list index out of range > What about this: (untested) for line in f.xreadlines(): words = line.rstrip().split() try: S = words[9]: print >>g,S except IndexError: pass The idea is to catch the exception so you can pass (ignore) it and go on to do the next line in your for loop. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 20:21:33 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 20:21:43 2003 Subject: [Tutor] Limit on number of characters in a string? In-Reply-To: Message-ID: On Sun, 21 Sep 2003, Jeffery Chin wrote: > Is there a limit on how many characters can be in a string? I'm using > pythonwin with python 2.3 and there seems to be a limit. > > I'm trying to concatenate lines from a file to make one continuous string > and it won't grow beyond a certain length. > I think it cuts it off around 3800 characters, but this was not consistent, > but looking at the screen output, it certainly would not add more to the > string. Hi Jeffery, There shouldn't be any hardcoded limit to the number of characters a string can contain -- I've often had strings that were several megabytes long. *grin* Your code snippet: > elif (record_check == ','): > interim_list.append(logline_path + entry + '.txt;') is a little confusing, though: as far as I can tell, there's no string concatentation going on! Can you show us where you actually generate the string? Good luck to you. From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 20:25:06 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 20:25:24 2003 Subject: [Tutor] I need help with Python [repeated message is dyoo's fault] In-Reply-To: <001301c381c5$07328e40$d60d7bca@angel> Message-ID: On Tue, 23 Sep 2003, Vickram wrote: > Hello there, > > Python is really an excellent programming language, in terms of > mathematical calculations. I have had a first hand experience of the > power of python while using the Mayalib source code for python to > calculate mayan dates. [text cut] Doh. The repeated message here is my fault and not Vickram's. As one of the list admins, I just verified/rejected a batch of messages that had been waiting in Python-tutor's queue, and didn't realize this one was already answered a few days ago. My apologies! From jeff at ccvcorp.com Thu Oct 9 20:29:24 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Oct 9 20:25:55 2003 Subject: [Tutor] skipping lines References: <3F85DD02.4060109@snet.net> Message-ID: <3F85FD64.8090700@ccvcorp.com> camartin@snet.net wrote: > for line in f.xreadlines(): > words = line.rstrip().split() > S = words[9] > print >>g,S > Traceback (most recent call last): > File > "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", > line 310, in RunScript > exec codeObject in __main__.__dict__ > File "C:\Python23\Script2.py", line 16, in ? > S = words[9] > IndexError: list index out of range You could always explicity catch the IndexError -- for line in f.xreadlines(): words = line.rstrip().split() try: S = words[9] print >>g, S except IndexError: pass This should have the effect of ignoring empty lines. Another possibility is to test line itself, as you said you tried. for line in f.xreadlines(): if line.strip(): words = line.rstrip().split() # ... The key here is that Python considers an empty string ("") to be equivalent to 'false'. We can't just test line directly, because it will contain at least a newline, and possibly other whitespace. line.strip() will get rid of all of that, leaving an empty string for a blank line. This could perhaps be rearranged to be a tiny bit more efficient -- for line in f.xreadlines(): line = line.strip() if line: words = line.split() # ... The difference here is that you're only strip()ing once, but this will also strip off leading whitespace. This could be an issue if leading whitespace is significant (as it is in, say, Python sourcecode files). For the purpose you seem to be describing, though, it should be fine. Jeff Shannon Technician/Programmer Credit International From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 20:29:05 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 20:29:13 2003 Subject: [Tutor] barcode creation In-Reply-To: Message-ID: On Mon, 6 Oct 2003, cordillia contessa wrote: > I have to create barcode but have no slight idea of what is needed and > how to create it. Help... Anyone... Hi Cordillia, You can find out about barcode generation from the GNU Barcode project: http://www.gnu.org/software/barcode/barcode.html According to the documentation in GNU Barcode, there is a Python program to generate ISBN bar codes: http://www.cgpp.com/bookland/ The link to bookland has a few more links that may be helpful for you. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Oct 9 20:31:55 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 9 20:32:06 2003 Subject: [Tutor] Random numbers In-Reply-To: <3F8000EC.5C49E947@mail.uct.ac.za> Message-ID: On Sun, 5 Oct 2003, UCT Student - DLLBIA001 wrote: > i was just wandring if you could not help me to generate 25 random > numbers in the range of 0 to 24 without any number repeating. Hello, Take a close look at: http://www.python.org/doc/lib/module-random.html In particular, the shuffle() function should be useful for you. If you have more questions, please feel free to ask. Because you are working on a homework assignment, we are somewhat more restricted in answering fully, but we'll try to direct you toward good resources. Good luck to you. From jeff at ccvcorp.com Thu Oct 9 20:41:07 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Oct 9 20:37:38 2003 Subject: [Tutor] Limit on number of characters in a string? References: Message-ID: <3F860023.2080400@ccvcorp.com> Jeffery Chin wrote: > Is there a limit on how many characters can be in a string? I'm using > pythonwin with python 2.3 and there seems to be a limit. > > I'm trying to concatenate lines from a file to make one continuous string > and it won't grow beyond a certain length. > I think it cuts it off around 3800 characters, but this was not consistent, > but looking at the screen output, it certainly would not add more to the > string. I've used Python to manipulate a file that uses 4K (4096 character) long lines, so that's not your problem. However, *displaying* such long lines can frequently be a significant issue. PythonWin starts to behave rather oddly when dealing with lines that are several kB long. Instead of trying to display the entire string, try just displaying its len() before and after the concatenation. This should demonstrate that the string is indeed growing. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Thu Oct 9 20:50:29 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Oct 9 20:47:42 2003 Subject: [Tutor] I need help with Python References: <001301c381c5$07328e40$d60d7bca@angel> Message-ID: <3F860255.2070802@ccvcorp.com> Vickram wrote: > I need to make calculations using very large numbers, unfortunately, i > am getting a "ZeroDivisionError: float division" error. This would be easier to determine if you had included the rest of the traceback, which would tell us exactly *where* the error is. But let's see what we can do. The error means that you're dividing by zero. Mathematics tells us that this yields an undefined result, but computers can't handle undefined numbers, so it's not allowed and is considered an error. The trick is to find out where in your program you might be dividing by zero. > import cmath > > a = 186282.397 > b = 1609.344 > c = 365.2421987817 > d = 99.9999999999999999995 > e = (d*a)/100 > beta = ((e*b)**2) / ((a*b)**2) > gamma = 1/math.sqrt(1-beta) All of this should be good. You've got a set of floating point numbers, none of which approximate zero all that closely. > ty = 100000 > td = ty*c > print > print "speed of light =",a,"mps" > print "1 mile =",b,"metres" > print "1 year =",c,"days" > print > print "% of c =",d,"%" > print "gamma =",gamma > print > print "normal time = ",ty,"years" > print " ",td,"days" > print > print "time dilation =",ty/round(gamma),"yrs" Here's where I think your problem is. You're rounding gamma to the nearest integer, and then dividing by it. You previously defined gamma as a fraction -- it's somewhere between 0 and 1. If gamma happens to be closer to 0, then round(gamma) will be equal to 0, and there you've got an illegal division by zero. I'm not sure why you'd want to round off gamma for this calculation, anyhow. Perhaps you meant to round off the results of ty/gamma, instead? Jeff Shannon Technician/Programmer Credit International From amk at amk.ca Thu Oct 9 20:48:40 2003 From: amk at amk.ca (amk@amk.ca) Date: Thu Oct 9 20:48:46 2003 Subject: [Tutor] re-directing print statements in exec In-Reply-To: <000e01c38267$fab53d90$6501a8c0@bigduck> References: <000e01c38267$fab53d90$6501a8c0@bigduck> Message-ID: <20031010004840.GA2967@rogue.amk.ca> On Tue, Sep 23, 2003 at 11:49:14PM -0700, Toby Donaldson wrote: > I am wondering if there is any easy way to make a print statement in an > exec statement get sent to a string instead of the console. For > instance, Use the StringIO/cStringIO modules. (cStringIO is written in C, theoretically making it faster, but unless you're writing lots of data it probably won't make a significant difference. Example: from StringIO import StringIO output = StringIO() print >>output, 3.14*r**2 print >>output, 'blah blah blah' str_value = output.getvalue() --amk From jeff at ccvcorp.com Thu Oct 9 21:00:31 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Oct 9 20:57:02 2003 Subject: [Tutor] re-directing print statements in exec References: <000e01c38267$fab53d90$6501a8c0@bigduck> Message-ID: <3F8604AF.2080308@ccvcorp.com> Toby Donaldson wrote: > Hi all, > > I am wondering if there is any easy way to make a print statement in an > exec statement get sent to a string instead of the console. For instance, > >>>> prog = """ > r = 5 > print 3.14 * r ** 2 > """ >>>> exec prog > 78.5 > > The result gets printed to the console. But instead, I'd like it to be > in a string. > > Any suggestions? First off, I'd suggest just using a function instead of exec. ;) def prog(): r = 5 return 3.14 * r**2 result = prog() Of course, it'd probably be better to pass r in as a parameter, and to rename the function so that it's meaningful... def circle_area(r): return 3.14 * (r**2) result = circle_area(5) There are *very* few situations in which exec is truly the most desirable tool, and many situations in which it creates programs that are actively dangerous. The use of exec and its cousin eval() should always be considered to be deep black magic -- it is not suitable (nor intended for) everyday use. Unless you're writing an interactive shell replacement or a code debugger or some such, I *strongly* recommend against using exec. Jeff Shannon Technician/Programmer Credit International From SWidney at ci.las-vegas.nv.us Thu Oct 9 21:03:05 2003 From: SWidney at ci.las-vegas.nv.us (Scott Widney) Date: Thu Oct 9 21:05:09 2003 Subject: [Tutor] I need help with Python Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8861@sovereign.ci.las-vegas.nv.us> > I need to make calculations using very large numbers, > unfortunately, i am getting a "ZeroDivisionError: float > division" error. > > Can you please help me out? > > What follows is my program. Its simple and brief, yet it is > actually calculating one of the best proven theories in > science - special relativity. > > > import cmath Should be 'import math' -- you don't use any complex math in the code that follows, but you do request the math.sqrt() function. > > a = 186282.397 > b = 1609.344 > c = 365.2421987817 > d = 99.9999999999999999995 This is where you are getting caught. If you look at the value in 'd' here, you'll see that it is stored as 100.0 -- your precision is lost. > e = (d*a)/100 So here 'e' ends up being the same value of 'a', > beta = ((e*b)**2) / ((a*b)**2) and 'beta' ends up being the equivalent of 186282.397 divided by 186282.397, namely 1.0 > gamma = 1/math.sqrt(1-beta) So the calculation for 'gamma' ends up being: 1 / math.sqrt( 1 - 1.0). This is where you are getting the exception. Do you see the problem? Best wishes! Scott From missive at hotmail.com Thu Oct 9 21:34:48 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Oct 9 21:34:55 2003 Subject: [Tutor] Re: Can you clarify these terms Message-ID: >I have a number of questions. > Please do not send HTML to the list. Send only plain text. >How do you call from the command prompt (in Python or windows) >a script file you've successfully run compiled from the editor? > Python is an interpreted language. As such we do not usually talk about compiling scripts or programs. That said, to run from the DOS prompt, you would do something like: python myscript.py or from the python prompt, you would: import myscript although that is not usually the way you would run something... That said, it really sounds to me like you have just typed or pasted your homework assignment in to your mail program. That is not what this list is about. I think you will have better luck if you: 1. do not post html to the list 2. post only one question at a time 3. include some code you have written to illustrate your question 4, search google first, especially for things that are not python-specific _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From carroll at tjc.com Thu Oct 9 23:40:55 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Oct 9 23:41:06 2003 Subject: [Tutor] Random numbers In-Reply-To: <3F8000EC.5C49E947@mail.uct.ac.za> Message-ID: On Sun, 5 Oct 2003, UCT Student - DLLBIA001 wrote: > i was just wandring if you could not help me to generate 25 random > numbers in the range of 0 to 24 without any number repeating. > if i were then to put this numbers onto a grid with 25 squares how would > i go about it. the grid and squares have already been made but how to > place the numbers i am uncertain of. For only 25 numbers, my approach would be: 1. create a list of numbers from 0 to 24. 2. set up your grid with 25 spaces. 3. get a random number between 0 and the length of the list minus 1 (24 when you start); 4. pull that entry out of the list with pop() and put it into the first open entry in the grid. pop() will remove that entry from the list, so the number of entries will be 24 after the first pass, 23 after the second, etc. 5. Repeat 3-4 until the list is empty. Things to read up on: pop() random.uniform() (to generate a random number in a particular range) len() (to get the length of the list) -- Terry Carroll Santa Clara, CA carroll@tjc.com From alan.gauld at blueyonder.co.uk Fri Oct 10 01:12:01 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Oct 10 01:13:47 2003 Subject: [Tutor] skipping lines References: <3F85DD02.4060109@snet.net> Message-ID: <00ac01c38eed$09dede20$6401a8c0@xp> > for line in f.xreadlines(): > words = line.rstrip().split() if len(words) >= 10: S = words[9] print >>g,S Should fix it. Alan g From ronan at melim.com.br Fri Oct 10 07:17:54 2003 From: ronan at melim.com.br (Ronan Lucio) Date: Fri Oct 10 07:17:18 2003 Subject: [Tutor] Web development In-Reply-To: <668593.1065721462012.JavaMail.erikprice@mac.com> References: <668593.1065721462012.JavaMail.erikprice@mac.com> Message-ID: <200310100817.54215.ronan@melim.com.br> Erick, > >Does someone develop web applications in Python? > > Sure, an interesting project for web app development is Webware. > Webware realy seems to be a great option but, unfortunatly, I didn't get to install it in a FreeBSD-4.8 box... :-/ It gave me some errors that couldn't got to solve. > You should read more about how cookies work, you can limit the lifetime of > a cookie to only last as long as the current session (until the user quits > the browser instance): > Very good!!! > Hopefully the above will help answer some questions about cookies in web > application development. Great! Thank you very much. Ronan From bwalling at coastdental.com Fri Oct 10 07:37:48 2003 From: bwalling at coastdental.com (Benjamin Walling) Date: Fri Oct 10 07:40:23 2003 Subject: [Tutor] barcode creation Message-ID: <61119D047A3FE84E83EF2FFDA9A156A4E58FB1@cstntexch01.coastdental.lan> If you are on a Windows system, it is as easy as installing a new font. Many barcodes, such as 3 of 9, are available as fonts. This may be true on other systems (Linux, etc), although I have not used barcoding on those systems. _____ From: cordillia contessa [mailto:gulasachet@hotmail.com] Sent: Sunday, October 05, 2003 12:27 PM To: tutor@python.org Subject: [Tutor] barcode creation I have to create barcode but have no slight idea of what is needed and how to create it. Help... Anyone... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031010/6cce7394/attachment.html From aschmidt at fredericksburg.com Fri Oct 10 08:10:09 2003 From: aschmidt at fredericksburg.com (Allen) Date: Fri Oct 10 08:10:46 2003 Subject: [Tutor] Deciding on using Jython In-Reply-To: <00ac01c38eed$09dede20$6401a8c0@xp> References: <3F85DD02.4060109@snet.net> <00ac01c38eed$09dede20$6401a8c0@xp> Message-ID: <3F86A1A1.2080001@fredericksburg.com> So what are the feelings on using Jython? I asked this list a while back about how to use DigestAuthentication to gain access to a URL from a company that changed how I accessed their data. I am not familiar with Python yet to dig deep enough to make it work. But, the Java classes and API are available on SourceForge. I would like to be able to build out my own tools to get at this data and would still like to do it in Python. Wondering if anyone here has used Jython and what they thought about it before I did more investigating. Thanks!! Allen From glingl at aon.at Fri Oct 10 10:14:18 2003 From: glingl at aon.at (Gregor Lingl) Date: Fri Oct 10 10:16:19 2003 Subject: [Tutor] cross sum toying In-Reply-To: <000001c38e6a$3c2a7980$e841fea9@oemcomputer> References: <000001c38e6a$3c2a7980$e841fea9@oemcomputer> Message-ID: <3F86BEBA.4000002@aon.at> Raymond Hettinger schrieb: >Here is one more version to play with: > > > >>>>from itertools import imap >>>>def cross_sum(n, codezero=ord('0')): >>>> >>>> > s = str(n) > return sum(imap(ord, s)) - len(s) * codezero > > Nice idea! I played with it, as you suggested and, interestingly, found out that it is exactly as fast as: def cross_sum7(n): s=str(n) return sum(map(ord, s)) - ord("0")*len(s) So why use itertools in this case? Regards, Gregor > > From op73418 at mail.telepac.pt Fri Oct 10 10:25:50 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Oct 10 10:24:27 2003 Subject: [Tutor] Private and Public variables In-Reply-To: <001e01c38dd7$1d5153a0$6401a8c0@xp> References: <001e01c38dd7$1d5153a0$6401a8c0@xp> Message-ID: On Wed, 8 Oct 2003 21:02:34 +0100, you wrote: >> they are still with me. I think one of the reason's why is because I >> tend to favor (following the gang of 4) composition to inheritance. > >What does that have to do with data hiding (the correct term >for private data)? Good question :-) I guess this is one of those situations where by conflating the issues in your head things just get more complicated and muddled. [text snipped] >> So, what do you guys think? > >I think your design ideas are correct, the need for data hiding >and the implied distrust of your fellow programmers is perhaps >more questionable. The implied distrust is not towards my fellow programmers, is more towards me... But I guess I do need to relax a little more... > >But if you design classes to expose a behavioural interface >then the ability or lack of to directly access data will not >be of any concern to your users. Exactly, that's what I try to do. I believe the "we're all consenting adults" philosophy is the Right Philosophy. The name-mangling feature for attributes of the form __my_attribute is also very good IMHO, since nothing is really hidden and a client can always work around bugs and/or missing features. At the same time it gives a clear signal to the client that if he mucks with this attribute he does so at his own risk. With my best regards, G. Rodrigues From python at rcn.com Fri Oct 10 13:15:06 2003 From: python at rcn.com (Raymond Hettinger) Date: Fri Oct 10 13:15:45 2003 Subject: [Tutor] cross sum toying In-Reply-To: <3F86BEBA.4000002@aon.at> Message-ID: <000f01c38f52$0d632f00$e841fea9@oemcomputer> > >>>>from itertools import imap > >>>>def cross_sum(n, codezero=ord('0')): > >>>> > >>>> > > s = str(n) > > return sum(imap(ord, s)) - len(s) * codezero > > > > > Nice idea! I played with it, as you suggested and, interestingly, found > out that it is exactly as fast as: > > def cross_sum7(n): > s=str(n) > return sum(map(ord, s)) - ord("0")*len(s) > > So why use itertools in this case? I always use an iterator version unless a full listing is essential. Likewise, I usually prefer xrange() to range(). sum() and imap() work especially well together -- the memory consumption is constant rather than linear as with map(). For small inputs, the performance difference is negligible. For bigger inputs, building a long list and throwing it away after one use is not only wasteful of memory, but it kills cache performance once the memory requirements grow beyond the cache size. IOW, the habit of using iterators results in apps that scale-up nicely. Aside from memory consumption and cache utilization, map() is also at a disadvantage when its arguments are do not have a __len__() method. In the cross_sum() example, the string "s" dutifully reports its length so that map can pre-allocate storage. However, in other apps, the inputs can be general iterables (generators for example) which only offer __iter__() but not __len__(). In that case, map's performance drops-off each time it has to do a memory reallocation as the sequence length grows. One other thought: pre-computing ord("0") into a local variable ought to produce a measurable time savings for repeated calls to cross_sum(). If you want to be an overachiever, change the function definition to: def cross_sum(n, sum=sum, imap=itertools.imap, codezero=ord("0"), len=len, str=str): s = str(n) return sum(imap(ord, s)) - len(s) * codezero Bonus question: Explain whether imap() would be preferred to map() in the following definition: def dotproduct(v1, v2): return sum(imap(operator.mul, v1, v2)) For grins, time it against the more specialized function: def integer_dot_product(v1, v2, sum=sum, imap=imap, mul=int.__mul__): return sum(imap(mul, v1, v2)) Try repeated calls with short vector tuples. Time it again with longer iterator inputs like: integer_dot_product(xrange(1,1000000,2), xrange(0,1000000,2)). Raymond Hettinger From abli at freemail.hu Fri Oct 10 15:09:43 2003 From: abli at freemail.hu (Abel Daniel) Date: Fri Oct 10 15:09:24 2003 Subject: [Tutor] Re: Random numbers In-Reply-To: <3F8000EC.5C49E947@mail.uct.ac.za> (UCT Student's message of "Sun, 05 Oct 2003 13:30:52 +0200") References: <3F8000EC.5C49E947@mail.uct.ac.za> Message-ID: UCT Student - DLLBIA001 writes: > i was just wandring if you could not help me to generate 25 random > numbers in the range of 0 to 24 without any number repeating. Just a note: in this case you aren't 'generating random numbers' but 'shuffling numbers'. Abel Daniel From ATrautman at perryjudds.com Fri Oct 10 15:21:48 2003 From: ATrautman at perryjudds.com (Alan Trautman) Date: Fri Oct 10 15:25:12 2003 Subject: [Tutor] barcode creation Message-ID: <06738462136C054B8F8872D69DA140DB01C08AA3@corp-exch-1.pjinet.com> Are you trying to print or display a barcode. Some (usually better) printers have a barcode font hard coded or programmable. This is easiest for creating labels. Alan -----Original Message----- From: Benjamin Walling [mailto:bwalling@coastdental.com] Sent: Friday, October 10, 2003 6:38 AM To: tutor@python.org Subject: RE: [Tutor] barcode creation If you are on a Windows system, it is as easy as installing a new font. Many barcodes, such as 3 of 9, are available as fonts. This may be true on other systems (Linux, etc), although I have not used barcoding on those systems. _____ From: cordillia contessa [mailto:gulasachet@hotmail.com] Sent: Sunday, October 05, 2003 12:27 PM To: tutor@python.org Subject: [Tutor] barcode creation I have to create barcode but have no slight idea of what is needed and how to create it. Help... Anyone... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031010/c67c5cff/attachment.html From anna at aleax.it Fri Oct 10 15:27:27 2003 From: anna at aleax.it (Anna Ravenscroft) Date: Fri Oct 10 15:27:33 2003 Subject: [Tutor] Re: Random numbers In-Reply-To: References: <3F8000EC.5C49E947@mail.uct.ac.za> Message-ID: <200310102127.27279.anna@aleax.it> On Friday 10 October 2003 09:09 pm, Abel Daniel wrote: > UCT Student - DLLBIA001 writes: > > i was just wandring if you could not help me to generate 25 random > > numbers in the range of 0 to 24 without any number repeating. > > Just a note: in this case you aren't 'generating random numbers' but > 'shuffling numbers'. > > Abel Daniel > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Okay - OP might want to look into the new "sample" function in module random. >>> import random >>> random.sample(range(25), 25) [20, 8, 14, 4, 13, 10, 1, 21, 19, 7, 6, 23, 22, 16, 5, 17, 15, 2, 18, 12, 24, 3, 0, 9, 11] >>> If you only want, say, 10 of the values from your range, you can do this: >>> random.sample(range(25), 10) [16, 15, 21, 24, 14, 17, 0, 7, 9, 11] >>> If you don't care about repetition in your samples, then just use randrange...: To get one random number at a time: >>> random.randrange(25) 11 Or, to get a list of them, use a list comprehension: >>> [random.randrange(25) for i in range(10)] [2, 21, 8, 3, 4, 23, 1, 21, 13, 11] >>> [random.randrange(25) for i in range(10)] [8, 6, 1, 21, 9, 24, 14, 5, 12, 3] >>> [random.randrange(25) for i in range(10)] [22, 19, 20, 20, 2, 13, 7, 3, 11, 7] >>> HTH Anna Ravenscroft -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From anna at aleax.it Fri Oct 10 15:32:59 2003 From: anna at aleax.it (Anna Ravenscroft) Date: Fri Oct 10 15:33:05 2003 Subject: [Tutor] Re: Random numbers In-Reply-To: <200310102127.27279.anna@aleax.it> References: <3F8000EC.5C49E947@mail.uct.ac.za> <200310102127.27279.anna@aleax.it> Message-ID: <200310102132.59482.anna@aleax.it> On Friday 10 October 2003 09:27 pm, Anna Ravenscroft wrote: Oops... got carried away, I guess. Didn't realize this was somebody's homework assignment... He'll still need to figure out how to get them into the squares... I'll read more carefully before answering next time... Sorry. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From erikprice at mac.com Fri Oct 10 16:39:46 2003 From: erikprice at mac.com (Erik Price) Date: Fri Oct 10 16:39:51 2003 Subject: [Tutor] __getitem__() and for loops Message-ID: <1620007.1065818386317.JavaMail.erikprice@mac.com> Quick question: Is a for loop actually calling __getitem__() behind the scenes, and passing in the current index of the range of the for loop? Thanks, Erik From rafael.sousa at netcabo.pt Fri Oct 10 16:46:13 2003 From: rafael.sousa at netcabo.pt (Rafael Sousa) Date: Fri Oct 10 16:49:42 2003 Subject: [Tutor] How can I convert a bin string to a hex string? References: Message-ID: <001b01c38f6f$8be57b40$6800a8c0@mobile> Thanks! That's exactly what I need! I wonder: Is there anything that Python doesn't have a module for? ----- Original Message ----- From: "Danny Yoo" To: "rafael.sousa" Cc: Sent: Thursday, October 09, 2003 7:02 PM Subject: Re: [Tutor] How can I convert a bin string to a hex string? > > > On Thu, 9 Oct 2003, rafael.sousa wrote: > > > Such as the binary contents of a jpeg image? > > I'm writing the code to dynamically create a RTF (Rich Text Format) > > document. In order to insert a picture, it's recommended in the > > specification that its contents are written in hex. > > I read the binary content to a regular python string, but then I would > > need to convert it to another string, this time in hex (which would > > naturally have the double of the length of the original bin string). > > > Hi Rafael, > > > Ah, then the 'binascii' module should be suitable for this: > > http://www.python.org/doc/lib/module-binascii.html > > The binascii.hexlify() function should be exactly what you're looking for. > > > > Good luck! > > From op73418 at mail.telepac.pt Fri Oct 10 16:52:12 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Oct 10 16:50:45 2003 Subject: [Tutor] __getitem__() and for loops In-Reply-To: <1620007.1065818386317.JavaMail.erikprice@mac.com> References: <1620007.1065818386317.JavaMail.erikprice@mac.com> Message-ID: On Fri, 10 Oct 2003 16:39:46 -0400, you wrote: >Quick question: > >Is a for loop actually calling __getitem__() behind the scenes, and passing in the current index of the range of the for loop? > Let us test: >>> class Test(object): ... def __init__(self, n): ... self.n = int(n) ... def __getitem__(self, i): ... if 0 <= i < self.n: ... return i ... else: ... raise IndexError ... >>> t = Test(4) >>> for i in t: ... print i ... 0 1 2 3 So it seems... Python looks first for __iter__ then tries __getitem__ -- also for backwards compatibility. Before the iterator protocol (< 2.2) coding a __getitem__ was the standard way to make classes cooperate with for-loops. With my best regards, G. Rodrigues From project5 at redrival.net Fri Oct 10 18:41:58 2003 From: project5 at redrival.net (Andrei) Date: Fri Oct 10 18:44:05 2003 Subject: [Tutor] Re: help In-Reply-To: <20031009021958.50203.qmail@web80504.mail.yahoo.com> References: <20031009021958.50203.qmail@web80504.mail.yahoo.com> Message-ID: joseph reaves wrote: > how do i get started? Beginner's guide to Python: http://python.org/topics/learn/ If you have more specific questions, you can ask them here. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Sat Oct 11 03:51:00 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 11 03:51:08 2003 Subject: [Tutor] __getitem__() and for loops In-Reply-To: Message-ID: > >Is a for loop actually calling __getitem__() behind the scenes, and > >passing in the current index of the range of the for loop? > > Python looks first for __iter__ then tries __getitem__ -- also for > backwards compatibility. Before the iterator protocol (< 2.2) coding a > __getitem__ was the standard way to make classes cooperate with > for-loops. Hello! Hmmm... Ideally, we'd be able to find out the specific details about the 'for' statement from the Language Reference: http://www.python.org/doc/current/ref/for.html Although the text does mention "iterable" objects, for the most part, the description emphasizes the idea that the for loop uses the 'sequence' interface (__getitem__()) to reach every element in the 'expression list'. So this part of the documentation may need to be freshened up a bit to better reflect the current reality. *grin* Let's dig in a little bit more. The documentation from the Iterator PEP: http://www.python.org/peps/pep-0234.html seems to have a more up-to-date description on how 'for' loops are working now: """For backwards compatibility, the PyObject_GetIter() function implements fallback semantics when its argument is a sequence that does not implement a tp_iter function: a lightweight sequence iterator object is constructed in that case which iterates over the items of the sequence in the natural order.""" There are some low-level C details in that paragraph, but it's not too bad. In general, for loops uses iter() now. But if the thing we're iterating across doesn't natively support iteration, the system generates a iterable wrapper on-the-fly around that sequence. And that wrapper is responsible for doing the right __getitem__()'s to make the iteration work. So the subtle thing to see is that it's not 'for' loops themselves that call __getitem__() anymore. Instead, it's the result of that wrapper that iter() is generating on-the-fly: ### >>> class Wrapper: ... def __init__(self, obj): ... self.obj = obj ... def __getattr__(self, attr): ... print "Debug: attribute", attr, "requested" ... return getattr(self.obj, attr) ... >>> class Foo: pass ... >>> f = Wrapper(Foo()) >>> iter(f) Debug: attribute __iter__ requested Debug: attribute __getitem__ requested Traceback (most recent call last): File "", line 1, in ? TypeError: iteration over non-sequence ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sat Oct 11 04:12:06 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 11 04:12:19 2003 Subject: [Tutor] How can I convert a bin string to a hex string? [Python Packages Index] In-Reply-To: <001b01c38f6f$8be57b40$6800a8c0@mobile> Message-ID: On Fri, 10 Oct 2003, Rafael Sousa wrote: > Thanks! That's exactly what I need! > > I wonder: Is there anything that Python doesn't have a module for? Hi Rafael, If there's some functionality that's not in the Standard Library, we might be able to find it in some third-party module. Recently, the PyPI project has kickstarted into action, collecting information on those third-party modules! http://www.python.org/pypi It's very nice and shiny. (But why is Python 2.3.2: http://www.python.org/pypi?:action=display&name=Python&version=2.3.2 classified under both "Development Status :: 3 - Alpha" and "Development Status :: 6 - Mature"? That's somewhat disconcerting. *grin*) There's also the venerable Vaults of Parnassus: http://www.vex.net/parnassus/ Good luck to you! From DataSoft2004 at netscape.net Sat Oct 11 13:37:59 2003 From: DataSoft2004 at netscape.net (Data) Date: Sat Oct 11 13:38:21 2003 Subject: [Tutor] Python Message-ID: <3F883FF7.1060501@netscape.net> I would like to learn this language but i am a complete beginner. Can someone help me with this language? Data. From david at graniteweb.com Sat Oct 11 15:43:44 2003 From: david at graniteweb.com (David Rock) Date: Sat Oct 11 15:43:49 2003 Subject: [Tutor] Python In-Reply-To: <3F883FF7.1060501@netscape.net> References: <3F883FF7.1060501@netscape.net> Message-ID: <20031011194344.GA749@wdfs.graniteweb.com> * Data [2003-10-11 19:37]: > I would like to learn this language but i am a complete beginner. > Can someone help me with this language? > Data. The best place to start is: http://www.python.org/topics/learn/ -- 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/20031011/a785366b/attachment.bin From kp8 at mac.com Sun Oct 12 03:20:15 2003 From: kp8 at mac.com (kevin parks) Date: Sun Oct 12 03:20:28 2003 Subject: [Tutor] putting a short list of integers into a (specific) compact form In-Reply-To: Message-ID: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> Hi everyone, I've got a question. It is a bit of a brain teaser for me and i am trying to figure out nice and pythonic way of going about things, but i just can't get my head round the problem so after staring and the screen for an eternity, i though that i would give a shout out and see if i can understand what comes back in response and hopefully i will have an 'a-ha' type moment. It is quite a complex process for my small brain so half the battle is understanding the steps and the other is figuring out how to code it up. As a way to help me get the problem straight in my pea-sized brain, i though that i would write out the process and now, since i am stuck, if anyone is bored, i would love some help, since this is actually being done for a purpose (in order to get some other work done). here's what i'd like to do (it is quite complex, but it have tried to present the recipe as clearly as possible): Take a short list of small integers and put it into a very specific compact form like so: 1. Initially, all duplicate elements should be eliminated and the elements should be written so that they are ascending in order (all integers are mapped mod 12). 2. Since there will be as many ways to order them as there are elements in the list, we want to choose the ordering that has the smallest interval from lowest element to highest one. 3. If there is still a tie under rule #2 we want to pick the list that is most packed to the left (by finding the intervals between the first element and the second to last element and comparing the intervals of each list in the tie, if there is still a tie, compare the intervals between first element in the lists and the third to last, etc.) 4. If this still results in a tie for each element, for example in the case of: [10,1,6] , [1,6,10] , and [6,10,1] we choose [1,6,10], since it's first element is 1. (finally, and optionally, i'll likely need to transpose the answer so that it starts on 0) So in a set with the following five possible orderings (here already sorted low to high and proceeding systematically (again %12)): [0,4,8,9,11] [4,8,9,11,0] [8,9,11,0,4] [9,11,0,4,8] [11,0,4,8,9] So the interval between the first element and the last is [0,4,8,9,11] = 0-11 = 11 [4,8,9,11,0] = 0-4 = 12-4 = 8 [8,9,11,0,4] = 4-8 = 16 - 8 = 8 [9,11,0,4,8] = 9-8 = 20-9 = 11 [11,0,4,8,9] = 9-11 = 21-11 = 10 Here end up with a tie between the second and third orderings above. So we go to rule #3: We compare the intervals btween the first and next to last elements: second ordering: 11-4 = 7 third ordering: 0-8 = 4 Since 4 is smaller than 7 we conclude the third ordering [8,9,11,0,4] is more packed to the left and what we want and there is no need for rule 4 in this case. I hope that i have stated the question clearly. I would appreciate any help folks could give on this. Frankly it is beyond what i can do at this point, but i would like to see how others approach this in the hopes that my code will work and that i might learn something. Best, kevin --^---------------------------------------- kp8 @ mac . com From kp8 at mac.com Sun Oct 12 05:46:28 2003 From: kp8 at mac.com (kevin parks) Date: Sun Oct 12 05:46:41 2003 Subject: [Tutor] Re: putting a short list of integers into a (specific) compact form In-Reply-To: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> Message-ID: > 1. Initially, all duplicate elements should be eliminated and the > elements should > be written so that they are ascending in order (all integers are > mapped mod 12). I should say that i got this part (#1) (see below) and step 4 and my optional little step 5 is probably pretty easy. It is the step 2 and 3 parts that i can't get my head round coding. I guess what i want is to generate each list (as i have done below) and compare the intervals between each list element and between the two list and i am 100000% sure there is some elegant way to do this in Python, it seems the kind of thing python was born to handle, with something sexy like bisect or list comprehension... hmm.... i'll keep thinking and hope that someone will lend a hand.... maybe once the list is made then a list of list can be built like: [0,4,8,9,11] [4,8,9,11,0] [8,9,11,0,4] [9,11,0,4,8] [11,0,4,8,9] and each interval can be taken and stored in a list? Hmmm... I just don't know. I guess that i am just reaching so that i don't look to silly on the tutor list, but i really don't know so i should just shut up and see what folks propose. -kp-- -- -- #!/usr/bin/env python import sys import random def unique(seq): try: # attempt fast algorithm d = {} for x in seq: d[x] = 0 return d.keys() except TypeError: # have an unhashable object, use slow algorithm ret = [] app = ret.append for x in seq: if x not in ret: app(x) return ret def test(): random.seed(720) x = range(0, 12, 1) print x; print random.shuffle(x) print x y= range(0, 12, 1) print y; print random.shuffle(y) print y; print x.extend(y) print x; print x.sort() print x; print z=unique(x) print z; print if __name__ == "__main__": test() > 2. Since there will be as many ways to order them as there are > elements in > the list, we want to choose the ordering that has the > smallest interval from lowest element to highest one. > > 3. If there is still a tie under rule #2 we want to pick the list that > is > most packed to the left (by finding the intervals between the first > element > and the second to last element and comparing the intervals of each > list in > the tie, if there is still a tie, compare the intervals between > first element > in the lists and the third to last, etc.) > > 4. If this still results in a tie for each element, for example in the > case of: > [10,1,6] , [1,6,10] , and [6,10,1] we choose [1,6,10], since > it's first element is 1. > > (finally, and optionally, i'll likely need to transpose the answer so > that > it starts on 0) > > So in a set with the following five possible orderings (here already > sorted low to high > and proceeding systematically (again %12)): > > [0,4,8,9,11] > [4,8,9,11,0] > [8,9,11,0,4] > [9,11,0,4,8] > [11,0,4,8,9] > > So the interval between the first element and the last is > > [0,4,8,9,11] = 0-11 = 11 > [4,8,9,11,0] = 0-4 = 12-4 = 8 > [8,9,11,0,4] = 4-8 = 16 - 8 = 8 > [9,11,0,4,8] = 9-8 = 20-9 = 11 > [11,0,4,8,9] = 9-11 = 21-11 = 10 > > Here end up with a tie between the second and third orderings above. > So we go to > rule #3: We compare the intervals btween the first and next to last > elements: > > second ordering: 11-4 = 7 > third ordering: 0-8 = 4 > > Since 4 is smaller than 7 we conclude the third ordering [8,9,11,0,4] > is more packed to the left and > what we want and there is no need for rule 4 in this case. > > I hope that i have stated the question clearly. I would appreciate any > help folks could give on this. Frankly it is beyond > what i can do at this point, but i would like to see how others > approach this in the hopes that my code will work and that > i might learn something. > > Best, > > kevin > > > --^---------------------------------------- > > kp8 @ mac . com > From bvg.pythontutor at freemail.hu Sun Oct 12 06:31:57 2003 From: bvg.pythontutor at freemail.hu (Gabor Borgulya) Date: Sun Oct 12 06:31:05 2003 Subject: [Tutor] putting a short list of integers into a (specific) compact form In-Reply-To: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> References: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> Message-ID: <1065954717.2063.9.camel@catv-d5de952e.bp04catv.broadband.hu> 2003-10-12, v keltez?ssel kevin parks ezt ?rta: > 1. Initially, all duplicate elements should be eliminated and the > elements should > be written so that they are ascending in order >>> l=[1,8,5,3,7,8,2,11,1,2,0,5] # a list with duplicate elements >>> wod=[] # this will be the new list without duplicates >>> for i in l: ... if i not in wod: # we append only if it is not already there ... wod.append(i) ... >>> wod [1, 8, 5, 3, 7, 2, 11, 0] >>> wod.sort() # sort in place >>> wod [0, 1, 2, 3, 5, 7, 8, 11] I couldn't understand the rest of your question. Hope this helps. G?bor From kalle at lysator.liu.se Sun Oct 12 07:55:28 2003 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sun Oct 12 07:55:33 2003 Subject: [Tutor] Re: putting a short list of integers into a (specific) compact form In-Reply-To: References: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> Message-ID: <20031012115528.GY9058@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [kevin parks] > >1. Initially, all duplicate elements should be eliminated and the > >elements should > > be written so that they are ascending in order (all integers are > >mapped mod 12). > > It is the step 2 and 3 parts that i can't get my head round > coding. I would try to put all the lists in a big list, and use the cmpfunc argument of the list sort method. Something like this: def dist(lst, elem): if lst[0] < lst[elem]: return lst[elem] - lst[0] return 12 - lst[0] + lst[elem] def funny_compare(l1, l2): end = -1 while abs(end) < len(l1): d1, d2 = dist(l1, end), dist(l2, end) if d1 < d2: return -1 if d2 < d1: return 1 end -= 1 return cmp(l1[0], l2[0]) It seems to work for some data: >>> x = [[0, 4, 8, 9, 11], [4, 8, 9, 11, 0], ... [8, 9, 11, 0, 4], [9, 11, 0, 4, 8], [11, 0, 4, 8, 9]] >>> x.sort(funny_compare) >>> for a in x: ... print a ... [8, 9, 11, 0, 4] [4, 8, 9, 11, 0] [11, 0, 4, 8, 9] [9, 11, 0, 4, 8] [0, 4, 8, 9, 11] The following example doesn't produce the results you wanted in your original post, but I don't understand why e.g. [10,1,6] and [1,6,10] should be equal in distances. Isn't the distance from 10 to 6 == 8, and the distance from 1 to 10 == 9? >>> y = [[10,1,6],[1,6,10],[6,10,1]] >>> y.sort(funny_compare) >>> y [[6, 10, 1], [10, 1, 6], [1, 6, 10]] I think I have misunderstood some part of the algorithm. Maybe you can start with this solution and change it to correctly implement your algorithm? As an aside, this might not be the fastest way to implement the algorithm (using cmpfunc is slow), but it is quite simple and clear in my opinion. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE/iUEodNeA1787sd0RAnNMAJ43Rke4zGGWvd61fIA8XUpDZjxuWgCfT9OV J+za0Jgdz+v1PihnJgg0NZs= =BJ62 -----END PGP SIGNATURE----- From gbrunet at sempersoft.com Sun Oct 12 07:40:16 2003 From: gbrunet at sempersoft.com (Greg Brunet) Date: Sun Oct 12 08:10:22 2003 Subject: [Tutor] Testing for punctuation in a string Message-ID: I'm trying to process a string of 'new field names' that will be comma separated, and want to make sure that there are no punctuation characters present (except for commas and underscores). Is there a pythonic way to do this. The list of characters that I DON'T want to allow are (and even this might not be very efficient): import string badchar = string.punctuation.replace('_','').replace(',','') If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure what to do next. I would probably split the string & test it a character at a time, but I am hoping for something better. Thanks, -- Greg From guillermo.fernandez at epfl.ch Sun Oct 12 08:50:38 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Sun Oct 12 08:50:53 2003 Subject: [Tutor] CVS package Message-ID: <3F894E1E.6020106@epfl.ch> Hi, Is there any CVS package in python? I'm looking for something to interact with a CVS server. I haven't find anything with google (other that CVS's of programs... :-) Thanks! Guille From godoy at metalab.unc.edu Sun Oct 12 10:05:00 2003 From: godoy at metalab.unc.edu (Jorge Godoy) Date: Sun Oct 12 10:05:50 2003 Subject: [Tutor] CVS package In-Reply-To: <3F894E1E.6020106@epfl.ch> (Guillermo Fernandez's message of "Sun, 12 Oct 2003 14:50:38 +0200") References: <3F894E1E.6020106@epfl.ch> Message-ID: Guillermo Fernandez writes: > Is there any CVS package in python? > I'm looking for something to interact with a CVS server. > I haven't find anything with google (other that CVS's of programs... :-) One like the svn (subversion) module would be very interesting. -- Godoy. From alan.gauld at blueyonder.co.uk Sun Oct 12 12:41:25 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Oct 12 12:43:09 2003 Subject: [Tutor] putting a short list of integers into a (specific) compactform References: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> Message-ID: <002401c390df$ad9ab590$6401a8c0@xp> > I've got a question. It is a bit of a brain teaser for me and i am > trying to figure out nice and pythonic way of going about things, I'm trying to think why on earth anyone would want to do such a thing! Can you assuage my curiosity? Whatever, a brute force approach follows: OK, removing duplicates can be done in a brute force style by just checking for pre-existence prior to insertion: original =[] unique = [] for item in original: if item not in unique: unique.append(item) # Now we want all the lists possible: possibles = [unique[:]] # store a copy for j in unique: previous = possibles[-1] possibles.append[previous[1:-1] + previous[0]] # we now have a list of options. # so define a function to calculate the delta def getDelta(low,high,mod=12): # an exercise for the reader... :-) # add the delta to the options as a tuple candidates = [] for option in possibles: candidates.append((option, getDelta(option[0],option[-1])) # now sort by delta def sortByDelta(t1,t2): return cmp(t1[1],t2[1]) canditates.sort(sortByDelta) lowest = candidates[0][1] candidates = [option[0] for option in candidates if option[1] == lowest] # At this point we have the list of lists with the # lowest possible deltas. At this point we can go through the candidates list applying the 4 rules until we only have 1 canditate left... I'm sure there are cleaner ways, and the code above is untested pseudo code but it should be a basis for something... HTH, Alan G. From alan.gauld at blueyonder.co.uk Sun Oct 12 12:52:36 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Oct 12 12:54:18 2003 Subject: [Tutor] Testing for punctuation in a string References: Message-ID: <002f01c390e1$3d153ff0$6401a8c0@xp> > If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure what > to do next. I would probably split the string & test it a character at > a time, but I am hoping for something better. Thanks, Ultimately you will have to test each character but you want to do it in C rather than Python. However the best I can think of is a comprehension: class Oops(Exception): pass def checkName(name): # use comprehension to maximise use of C code if len([char for char in name if char in punctuation]) == 0 raise Oops ok = [] for name in names: try: checkName(name) ok.append(name) except Oops: pass HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bwalling at coastdental.com Sun Oct 12 13:57:26 2003 From: bwalling at coastdental.com (Benjamin Walling) Date: Sun Oct 12 13:57:31 2003 Subject: [Tutor] Report Writer Message-ID: <61119D047A3FE84E83EF2FFDA9A156A486230D@cstntexch01.coastdental.lan> I've started to evaluate moving to Python from ASP.NET. One of the hurdles I have come across is Crystal Reports. We use Crystal extensively. I've found that there are a few open source projects for report writing, the best of which seems to be JasperReports. Can either Crystal or Jasper be called from Python? Linux or Windows? From glingl at aon.at Sun Oct 12 14:43:52 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Oct 12 14:45:44 2003 Subject: [Tutor] Report Writer In-Reply-To: <61119D047A3FE84E83EF2FFDA9A156A486230D@cstntexch01.coastdental.lan> References: <61119D047A3FE84E83EF2FFDA9A156A486230D@cstntexch01.coastdental.lan> Message-ID: <3F89A0E8.6030307@aon.at> Benjamin Walling schrieb: >I've started to evaluate moving to Python from ASP.NET. One of the hurdles I have come across is Crystal Reports. We use Crystal extensively. > >I've found that there are a few open source projects for report writing, the best of which seems to be JasperReports. > >Can either Crystal or Jasper be called from Python? Linux or Windows? > > Hi Benjamin, I don't konw, but I recommend to hava a look at http://www.reportlab.org. especially http://www.reportlab.org/rl_toolkit.html another open source report toolkit which uses Python itself. Regards, Gregor >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From anna at aleax.it Sun Oct 12 16:31:29 2003 From: anna at aleax.it (Anna Ravenscroft) Date: Sun Oct 12 16:31:36 2003 Subject: [Tutor] CVS package In-Reply-To: References: <3F894E1E.6020106@epfl.ch> Message-ID: <200310122231.29587.anna@aleax.it> On Sunday 12 October 2003 04:05 pm, Jorge Godoy wrote: > Guillermo Fernandez writes: > > Is there any CVS package in python? > > I'm looking for something to interact with a CVS server. > > I haven't find anything with google (other that CVS's of programs... :-) My understanding is that there isn't really any module for Python - folks manually open a shell or use os.system or os.open to run a command line. There is a project going on at cvshome.org... called libcvs, for perl and java.... but nobody yet appears to be working on a python version... > One like the svn (subversion) module would be very interesting. Many folks apparently are more happy with moving to subversion, than continuing to support CVS. The PyPy project, for example, uses subversion. Building the server is said to be a bear, according to folks who ought to know, like AMK. But installing and using it as a client is quite easy. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From anna at aleax.it Sun Oct 12 17:35:34 2003 From: anna at aleax.it (Anna Ravenscroft) Date: Sun Oct 12 17:35:40 2003 Subject: [Tutor] Testing for punctuation in a string In-Reply-To: <002f01c390e1$3d153ff0$6401a8c0@xp> References: <002f01c390e1$3d153ff0$6401a8c0@xp> Message-ID: <200310122335.34640.anna@aleax.it> On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote: > > If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure Make sure your list of fieldnames has quotes around each item, not just the beginning and end of the list... > what to do next. I would probably split the string & test it a character > at a time, but I am hoping for something better. Thanks, Ouch. Sounds long and unpleasant. I like the nifty new sets module (available in 2.3). You can use a list comprehension (as Alan suggested) but if you have more than one type of "bad" punctuation in a particular fieldname, you'll get duplicates. If you use the new sets module, you can eliminate the duplicates. >>> import sets >>> fieldnames=['fld1','fld2','fld-bad', 'fld-ba_d'] >>> bad = ['-'. '_'] >>> badfld = [f for f in fieldnames for b in bad if b in f] >>> print badfld # will print any duplicates ['fld-bad', 'fld-ba_d', 'fld-ba_d'] >>> setofbad = sets.Set(badfld) # removes the duplicates >>> print setofbad Set(['fld-ba_d', 'fld-bad']) >>> Hope this gives you some ideas... Have fun. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From python at rcn.com Sun Oct 12 19:21:06 2003 From: python at rcn.com (Raymond Hettinger) Date: Sun Oct 12 19:21:45 2003 Subject: [Tutor] putting a short list of integers into a (specific) compactform In-Reply-To: <8683ADE5-FC84-11D7-BB7D-003065555ABC@mac.com> Message-ID: <000d01c39117$83bec9e0$e841fea9@oemcomputer> [kevin parks] > here's what i'd like to do (it is quite complex, but it have tried to > present the recipe as > clearly as possible): It is not so bad if you break in down functionally and use generators. * rule1() applies the inital step * rotations() returns a generator for each ordering * orderings() prepends three values corresponding to rules 2, 3, and 4 * min() selects the best ordering based on rule2, falling back to 3 in a tie, and back to four for a final tie breaker * [3] throws away the ordering info leaving on the best sequence * optional() applies to final transpose rule def rule1(s): "Apply mod12, eliminate duplicates, and sort" set = {} for elem in s: set[elem%12] = True nodups = set.keys() nodups.sort() return nodups def rotations(s): "generate all rotations of a sequence" for i in xrange(len(s)): yield s s = s[1:] + s[0:1] def ordering(rots): "rules for deciding which rotation comes first" for s in rots: rule2 = (s[-1] - s[0]) % 12 rule3 = (s[-2] - s[0]) % 12 rule4 = s[0] yield rule2, rule3, rule4, s def optional(s): "transpose the answer so it starts with zero" return [(x - s[0])%12 for x in s] start = [4, 12, 20, 9, 11, 0, 8, 4] print optional(min(ordering(rotations(rule1(start))))[3]) Raymond Hettinger From kp8 at mac.com Sun Oct 12 22:34:21 2003 From: kp8 at mac.com (kevin parks) Date: Sun Oct 12 22:34:37 2003 Subject: [Tutor] putting a short list of integers into a (specific) compactform In-Reply-To: <002401c390df$ad9ab590$6401a8c0@xp> Message-ID: On Sunday, October 12, 2003, at 12:41 PM, Alan Gauld wrote: >> I've got a question. It is a bit of a brain teaser for me and i am >> trying to figure out nice and pythonic way of going about things, > > I'm trying to think why on earth anyone would want to do such > a thing! Can you assuage my curiosity? Hi Alan. Thanks for your reply. I am still working on this and have the first few steps taken care of. but, since you and a bunch of other folks are curious I ought to explain what this is needed for. I didn't mean for it to be so mysterious, but i noticed my post was already getting quite convoluted so i was trying to cut to the chase as best as i could. I am trying to use this to form what is called the 'normal form' of a set of musical pitches. Here the pitches are all represented as numbers 0-11. In order to compare sets and see if they are inversionally or transpositionally related, or if they will have any common tones under transposition or inversion it is helpful to put the sets in this compact form. There are lots of buggy little java applets that do this on the web. http://mail.rochester.edu/~af006m/Clock2.html http://www.jaytomlin.com/music/settheory/ http://www.webcalc.net/calc/0515.php http://gigue.peabody.jhu.edu/~pnelson/PCSets/setfinder.html http://www.cosmoedu.net/DoctorFields/TTTBLow.html but i want to do this from within python. As i said i have the unique(), sort, and rotate() thing sort of working, but then i have to figure out how work with that to get my steps 3,4 (and 5). Raymond Hettinger has replied as well an i am looking at how he has broken the problem down and it is helping me understand a bit better. -kevin From idiot1 at netzero.net Sun Oct 12 23:15:46 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Sun Oct 12 23:16:08 2003 Subject: [Tutor] Testing for punctuation in a string In-Reply-To: <200310122335.34640.anna@aleax.it> References: <002f01c390e1$3d153ff0$6401a8c0@xp> <200310122335.34640.anna@aleax.it> Message-ID: <3F8A18E2.5090805@netzero.net> May I please jump in the thread? I just wrote 2 wiki's, and had to sort things out, seperating sheep from goats just this way. And I had to do it a char at a time, and used recursion in doing it. You might not want to use recursion, but maybe you will... My task was to return a 1 or a 0 for an if statement to swallow and genuflect at. A function looked at a word and nibbled through it char by char, using other functions, which were recursive, and decided if a word was a wiki word. ( a WikiWord is 2+ words RunTogetherLikeThis, each capitalized, and no punctuation within them. So 'WikiWord' is a wikiword, but 'Wiki-Word' is not. I used a lot of string slicing, IF statements, IN, and the string module's constants (string.uppercase, string.punctuation, etc). Each function is rather simple in itself, and the total effect is a fairly powerful word chomper. And NO gang, this time I did NOT do any counting, which kept it from being a state engine in the first one I wrote. Here is the stript I wrote using these functions. Note it is optimized for operation in a windows 9x environment. BEWARE WORD WRAP! I edited this to minimize as much as possible, and inserted a '\' wher a code line wraps around, but please be careful, make your screen as wide as possible, maybe use a narrow font? ------------------------------------------------------------------------------ #!C:\Python22\pythonw.exe # tablebgcolor="FFE0C0" import os, os.path, sys, string, re, cgitb; cgitb.enable() print "Content-Type: text/html\n" # try: pagename=os.environ['QUERY_STRING'] # try to get page name requested except Exception, e: pagename="FrontPage" # but default to FrontPage # path=os.getcwd() path=path+'\\cgi-bin\\text' os.chdir(path) # make the pages dir current if os.path.exists(pagename): # if the page asked for exists, pass # do nothing here; else: # BUT if it does NOT- f1=open(pagename,'w') # CREATE it! f1.write('Please contribute to this webpage.\n') f1.close() # # header for webpage print 'MiniWiki - '+ pagename +'' print '' print '' print '
' print 'MiniWiki' print '
' print string.join(re.split('([A-Z][a-z]*)',pagename)[1:-1]) + '
' print '(Click for backsearch)

' f1=open(pagename,'r') page=f1.readlines() f1.close() # def isin( searchthis, forthis ): # return a 1 or 0 to control IF statements value = 1 + string.find(searchthis, forthis) if value > 0: return 1 else: return 0 # # # Now we try to hash out wiether or not a word is a wikiword... # a WikiWord is in CamelCaps. it has a 'hump' in it. # ThisIs a WikiWord, # but ThisISNOT, # ANDNEITHERISTHIS, # NorisTHIS. Fun? # # these functions build wikiwords. def buildwikilink(word): # turns a word into a hyperlink word = '' + word + '' # it's a hyperlink anchor, normal html. return word # def potentialword(word): # newword='' prefix='' suffix='' index=0 while 1: # loop processes the word 1 char at time if word[index] in string.ascii_letters: prefix, newword, suffix = mainbody(prefix, word[index:]) return prefix, newword, suffix else: prefix=prefix+word[index] index=index+1 # def mainbody(prefix, word,): newword='' suffix='' index=0 for char in word: if char in string.ascii_letters: newword=newword+char else: suffix=suffix+char # index=index+1 return prefix, newword, suffix # def makewikiword(word): # combines processed link prefix='' suffix='' prefix, word, suffix=potentialword(word) return prefix + buildwikilink(word) + suffix # # # these 2 words determine if a word is a wikiword. def iswikiword(word): # tests to see if is wikiword. if word: if word[0]in string.ascii_uppercase: # ALL start with capital. if (len(word)>1): # guard for 'A' word if word[1] in string.ascii_lowercase: # if (len(word)>3): # is there any more to process? if processword(word[2:]): # is there another? return 1 # YES! it's a wikiword! return 0 # it's not a wikiword. # def processword(word): if word: # it is possible to # exaust a word and not find another capital letter if word[0] in string.ascii_lowercase: # wikiwords CAN have # several lowercase letters before the next capital, after all... value=processword(word[1:]) # so keep # invoking this word until exaustion, or a capital is found return value else: # MIGHT be a capital! if word[0] in string.ascii_uppercase: if len(word)>1: if word[1] in string.ascii_lowercase: return 1 else: return 0 else: return 0 else: return 0 else: return 0 # # # # this group processes the raw page to convert it to html code- but not wikiwords or links. index=0 for line in page: # process the line for substrings line=string.rstrip(line) # kill EOL stuff line=string.replace(line,'<','<') # kills html tag opener line=string.replace(line,'>','>') # kills html tag closer line=string.replace(line,'----','
') # create standard
line=string.replace(line,'@!','
') # open centering line=string.replace(line,'!@','
') # close centering line=string.replace(line,"```","") # open BOLD line=string.replace(line,"'''","") # close BOLD line=string.replace(line,"``","") # open ITALIC line=string.replace(line,"''","") # Close Italic line=string.replace(line,"{{{","
")		# open PREFORMATTED TEXT
	line=string.replace(line,"}}}","
\n") # close PREFORMATTED line=string.replace(line,'
','') # remove any BR's. line=string.replace(line,'[=','
') # create header bar line=string.replace(line,'=]','
\n') # end # header bar line=string.replace(line,'{{{','
')	# start 
 zone
	line=string.replace(line,'}}}','
')	# END a 
 zone with 
line=string.replace(line,'#! ','
\n') # end an image tag line=string.replace(line,'-!','') # insert small tag line=string.replace(line,'!-','') # insert end small tag line=string.replace(line,'+!','') # insert tag line=string.replace(line,'!+','') # insert END of BIG state if line == "": # null line> with

line='

\n' page[index]=line # save resulting line index=index+1 # and increase pointer. # # wordscanner routine linecounter=0 # reset the linepointer we will use it again... for line in page: # see? wordcounter=0 # start the word pointer over at 0 again wordlist = string.split(line,' ') # split the line into a list of words. for word in wordlist: if ((isin(word,'http://')) or (isin(word,'mailto:'))): #if link: if isin(word,'"'): # DO NOT process a "http- it's imbedded code! pass # DO NOT process; leave the word alone! else: # otherwise, make a hyperlink for them to click. wordlist[wordcounter]=''\ + word + '' else: if iswikiword(word): wordlist[wordcounter]=makewikiword(word) else: pass wordcounter=wordcounter+1 line=string.join(wordlist,' ') page[linecounter]=line linecounter=linecounter+1 # # print out the final highly modified page. for line in page: print line # # Page footer follows print '

' print '' print '' print '' print '' print '' print '' print '
Edit this page
' print ' ' print '
LIST ALL PAGES
MiniWiki V:1.3.0
©2003 Kirk D Bailey
 FrontPage
' print '' ------------------------------------------------------------------------------ BEWARE WORD WRAP! That is the complete wiki browser engine. If you want the entire suite of several scripts I am using, I will email it to you off list- email me and ask for it. Anna Ravenscroft wrote: > On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote: > >>>If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure > > > Make sure your list of fieldnames has quotes around each item, not just the > beginning and end of the list... > > >>what to do next. I would probably split the string & test it a character >>at a time, but I am hoping for something better. Thanks, > > > Ouch. Sounds long and unpleasant. > > I like the nifty new sets module (available in 2.3). You can use a list > comprehension (as Alan suggested) but if you have more than one type of "bad" > punctuation in a particular fieldname, you'll get duplicates. If you use the > new sets module, you can eliminate the duplicates. > > >>>>import sets >>>>fieldnames=['fld1','fld2','fld-bad', 'fld-ba_d'] >>>>bad = ['-'. '_'] >>>>badfld = [f for f in fieldnames for b in bad if b in f] >>>>print badfld # will print any duplicates > > ['fld-bad', 'fld-ba_d', 'fld-ba_d'] > >>>>setofbad = sets.Set(badfld) # removes the duplicates >>>>print setofbad > > Set(['fld-ba_d', 'fld-bad']) > > > Hope this gives you some ideas... Have fun. > > Anna -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From tony at tcapp.com Sun Oct 12 23:40:05 2003 From: tony at tcapp.com (Tony Cappellini) Date: Sun Oct 12 23:43:28 2003 Subject: [Tutor] Auto login of website Message-ID: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net> Would anyone happen to have a small python program (with or without gui) that can log a user into a website, at regular intervals ? The program would have to take the following as input (can be hard-coded, or on the cmd line) 1. the URL of a website (http) 2. the user ID 3. the user pasword 4. click (simulate a keypress or mouse click) on the button to log the user in if the user could not be logged in, due to the website being overloaded, then it would do a retry at the next interval (where the interval can be supplied by the user, preferably in seconds) I've already checked the Python Cookbook, didn't find a match for the keywords I used From gbrunet at sempersoft.com Mon Oct 13 04:21:47 2003 From: gbrunet at sempersoft.com (Greg Brunet) Date: Mon Oct 13 04:33:34 2003 Subject: [Tutor] Re: Testing for punctuation in a string References: <002f01c390e1$3d153ff0$6401a8c0@xp> Message-ID: "Alan Gauld" wrote in message news:002f01c390e1$3d153ff0$6401a8c0@xp... > Ultimately you will have to test each character but you want to > do it in C rather than Python. However the best I can think of > is a comprehension: >... Hi Alan: Yes - I can see how comprehension would be slightly more efficient. OTOH, I want to kick out as soon as I see ANY error condition, so I may stay with a standard FOR loop with a sys.exit (after displaying an error message) if I find any bad characters. Thanks for the ideas, -- Greg From gbrunet at sempersoft.com Mon Oct 13 04:33:03 2003 From: gbrunet at sempersoft.com (Greg Brunet) Date: Mon Oct 13 04:40:21 2003 Subject: [Tutor] Re: Testing for punctuation in a string References: <002f01c390e1$3d153ff0$6401a8c0@xp><200310122335.34640.anna@aleax.it> <3F8A18E2.5090805@netzero.net> Message-ID: "Kirk Bailey" wrote in message news:3F8A18E2.5090805@netzero.net... > May I please jump in the thread? > > I just wrote 2 wiki's, and had to sort things out, seperating sheep from goats > just this way. And I had to do it a char at a time, and used recursion in doing > it. You might not want to use recursion, but maybe you will... Hi Kirk: I ended up using regex (the actual routine I used is in my response to Anna). Your code sample has a lot of interesting stuff though, so I'll flag it to look at later for some more good ideas. Thanks, -- Greg From gbrunet at sempersoft.com Mon Oct 13 04:30:37 2003 From: gbrunet at sempersoft.com (Greg Brunet) Date: Mon Oct 13 04:50:18 2003 Subject: [Tutor] Re: Testing for punctuation in a string References: <002f01c390e1$3d153ff0$6401a8c0@xp> <200310122335.34640.anna@aleax.it> Message-ID: Hi Anna: Thanks for your response. "Anna Ravenscroft" wrote in message news:200310122335.34640.anna@aleax.it... > On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote: > > > If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure > > Make sure your list of fieldnames has quotes around each item, not just the > beginning and end of the list... Actually, I the string is getting loaded by a call to getopt, so I wanted to show what I originally received in case there wasn't a need to split it into the actual names. If I want to look at it by names (which I eventually did), my first step was to use: fields = s.split(',') > > what to do next. I would probably split the string & test it a character > > at a time, but I am hoping for something better. Thanks, > > Ouch. Sounds long and unpleasant. Yeah, but it was a quick and easy first approach. For various reasons, I ended up using regex, thought that might be a bit heavyweight for what I needed: p=re.compile('^[a-zA-Z]\w*$') def fldNameValid(fldName): return p.match(fldName) != None > I like the nifty new sets module (available in 2.3). You can use a list > comprehension (as Alan suggested) but if you have more than one type of "bad" > punctuation in a particular fieldname, you'll get duplicates. If you use the > new sets module, you can eliminate the duplicates. > > Hope this gives you some ideas... Have fun. > > Anna I will look into sets though, so I am familiar with them for the next time. Thanks again, -- Greg From pythontutor at venix.com Mon Oct 13 09:01:12 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Oct 13 09:01:16 2003 Subject: [Tutor] Auto login of website In-Reply-To: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net> References: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net> Message-ID: <3F8AA218.1030503@venix.com> The urllib and urllib2 modules support accessing a website. The module documentation for urllib describes how to create your own class to override functions provided by urllib. In your case, you want to override the method: prompt_user_passwd to return a tuple containing your username and password. import urllib class MyURLopener(urllib.FancyURLopener): def prompt_user_passwd(host,realm): #ignore host and realm # substitue your id and password return ("mulder", "trustNo1") urllib._urlopener = MyURLopener() f = urllib.urlopen("http://www.some.com") print f.read() This omits cookie issues and other pitfalls. You may find it easier to use a program like wget to access URL's that have cookies and passwords to control access. Tony Cappellini wrote: > > > Would anyone happen to have a small python program (with or without gui) > that can > > log a user into a website, at regular intervals ? > > The program would have to take the following as input (can be > hard-coded, or on the cmd line) > > 1. the URL of a website (http) > 2. the user ID > 3. the user pasword > 4. click (simulate a keypress or mouse click) on the button to log the > user in > > if the user could not be logged in, due to the website being overloaded, > then it would do a retry at the next interval (where the interval can be > supplied by the user, preferably in seconds) > > I've already checked the Python Cookbook, didn't find a match for the > keywords I used > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From Janssen at rz.uni-frankfurt.de Mon Oct 13 11:31:02 2003 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Mon Oct 13 11:31:22 2003 Subject: [Tutor] Re: Testing for punctuation in a string In-Reply-To: References: <002f01c390e1$3d153ff0$6401a8c0@xp> <200310122335.34640.anna@aleax.it> Message-ID: On Mon, 13 Oct 2003, Greg Brunet wrote: > I ended up using regex, thought that might be a bit heavyweight for what > I needed: > > p=re.compile('^[a-zA-Z]\w*$') > def fldNameValid(fldName): > return p.match(fldName) != None Hello Greg Brunet, in case your goal is to "test for punctuation in a string" you should do that in the most direct way: [untested] _punctuation = string.punctuation.replace("_","").replace(",","") aPattern = "[%s]" % _punctuation mt = re.search(aPattern, aString) if mt: # do whatever you want, including: raise Exception, \ "fldName '%s' contains a '%s' on position %s" \ % (fldName, mg.group(), mt.start() ) regular expression is the thing to test for the presence or absence of patterns. The other way (iterating through the string and look if each element is in a sequence of punctuation chars: for s in aString: if s in _punctuation: raise ) is heavyweight in terms of performance: Python has to perform len(aString) "s in _punctuation" lookups against one single regexp-operation with the former example (OTOH, it is believed that only testing the actual runtime of both solutions truly reveals their better or worse performance). When I may take a look at your latest approach (Testing legality by definig a pattern the Field Name must match): > p=re.compile('^[a-zA-Z]\w*$') > def fldNameValid(fldName): > return p.match(fldName) != None Doing things the other way around as in ones own goal-definition (supposed I can take the thread's subject as such a thing ;-) might be a clever choice in case it becomes clear that it's better than the "former way around". Nevertheless it might introduce some unforeseen results: Now, your pattern rejects whitespace and commas; Field Names starting with numbers or an underscore will be rejected. All this might be perfectly what you needs but it doesn't do the "Testing for punctuation in a string" job any longer. Beside this (and given that the additional restrictions for valid Field Names are what you need), you're solution will do the job, and you won't feel much of a performance impact as long as you don't want to parse a serveral kB's commandline ;-) Michael From idiot1 at netzero.net Mon Oct 13 12:36:33 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Mon Oct 13 12:37:10 2003 Subject: [Tutor] Re: Testing for punctuation in a string In-Reply-To: References: <002f01c390e1$3d153ff0$6401a8c0@xp><200310122335.34640.anna@aleax.it> <3F8A18E2.5090805@netzero.net> Message-ID: <3F8AD491.4010908@netzero.net> thanks for the compliment Greg. This is the first time I ever used recursion in a significant way, and I *THINK* the series of functions which together form a state machine, check and see if I am blowing sunshine up my own kilt please. Greg Brunet wrote: > "Kirk Bailey" wrote in message > news:3F8A18E2.5090805@netzero.net... > >>May I please jump in the thread? >> >>I just wrote 2 wiki's, and had to sort things out, seperating sheep > > from goats > >>just this way. And I had to do it a char at a time, and used recursion > > in doing > >>it. You might not want to use recursion, but maybe you will... > > > Hi Kirk: > > I ended up using regex (the actual routine I used is in my response to > Anna). Your code sample has a lot of interesting stuff though, so I'll > flag it to look at later for some more good ideas. Thanks, > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From pythontutor at venix.com Mon Oct 13 13:59:35 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Oct 13 13:59:44 2003 Subject: [Tutor] Auto login of website In-Reply-To: <20031013103414.B52710-100000@yamato.yamato.com> References: <20031013103414.B52710-100000@yamato.yamato.com> Message-ID: <3F8AE807.2080408@venix.com> http://unxutils.sourceforge.net/ Native Win32 ports of some GNU utilities wget is included in the list of utilities. The python snippet I sent you should be close to working code. You need to specify the real URL, username, and password. A class website is less likely to have strange cookie requirements than commercial sites. You might find that the python code does the trick. Tony Cappellini wrote: > Thanks Lloyd > > I dont know what wget is ? > Is that available for Windows ? > I need something that works now, as opposed to having to write a program. > I'm not familair with web programming, and odnt have time to learn now, > but need to get logged into a wesbtie to work on a project for a class. > I'd liek to write a Python version of the auto login program later though > > > thanks > > Tony > > > On Mon, 13 Oct 2003, Lloyd Kvam wrote: > > >>The urllib and urllib2 modules support accessing a website. The module >>documentation for urllib describes how to create your own class to >>override functions provided by urllib. In your case, you want to >>override the method: >> prompt_user_passwd >>to return a tuple containing your username and password. >> >>import urllib >>class MyURLopener(urllib.FancyURLopener): >> def prompt_user_passwd(host,realm): >> #ignore host and realm >> # substitue your id and password >> return ("mulder", "trustNo1") >> >>urllib._urlopener = MyURLopener() >> >>f = urllib.urlopen("http://www.some.com") >>print f.read() >> >>This omits cookie issues and other pitfalls. You may find it easier to >>use a program like wget to access URL's that have cookies and passwords >>to control access. >> >>Tony Cappellini wrote: >> >>> >>>Would anyone happen to have a small python program (with or without gui) >>>that can >>> >>>log a user into a website, at regular intervals ? >>> >>>The program would have to take the following as input (can be >>>hard-coded, or on the cmd line) >>> >>>1. the URL of a website (http) >>>2. the user ID >>>3. the user pasword >>>4. click (simulate a keypress or mouse click) on the button to log the >>>user in >>> >>>if the user could not be logged in, due to the website being overloaded, >>>then it would do a retry at the next interval (where the interval can be >>>supplied by the user, preferably in seconds) >>> >>>I've already checked the Python Cookbook, didn't find a match for the >>>keywords I used >>> >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >> >>-- >>Lloyd Kvam >>Venix Corp. >>1 Court Street, Suite 378 >>Lebanon, NH 03766-1358 >> >>voice: 603-443-6155 >>fax: 801-459-9582 >> >> > > > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From scot at possum.in-berlin.de Mon Oct 13 21:35:34 2003 From: scot at possum.in-berlin.de (Scot W. Stevenson) Date: Mon Oct 13 21:45:41 2003 Subject: [Tutor] osx python editor In-Reply-To: <69372ED0-F227-11D7-84A4-000A9579AE94@csiro.au> References: <69372ED0-F227-11D7-84A4-000A9579AE94@csiro.au> Message-ID: <200310140335.34515.scot@possum.in-berlin.de> Hello Kim, > i'm making the transition from perl to python, i'm trying to convert a > lot of tools into python so they can be maintained a little better. > I'm looking at doing alot of my work under osx rather than linux. I'm sure somebody has already pointed this out or that you have already considered this solution and found it lacking, but just to be sure: You might want to try an editor that will run on just about any platform, so you don't have to care which operating system you are running. My favorite is vim (http://www.vim.org), which runs on just about anything above a 6502 and is beautiful for pythonizing. You will, however, have to invest a bit of time to become familiar with it. Various Mac versions seem to live at http://macvim.swdev.org/OSX/ The vim page has more info. Note to the list: vim has a new Python script, check http://www.vim.org/scripts/script.php?script_id=790 for details. Haven't tried it out myself yet. Y, Scot -- Scot W. Stevenson - Zepernick, Germany From j.ezequiel at spitech.com Mon Oct 13 22:45:15 2003 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Mon Oct 13 22:45:53 2003 Subject: [Tutor] unichr() question Message-ID: <29E16390A38FD7118A03000BCD0F3F6501223811@mail.spiglobe.com> PythonWin 2.2.2 Windows XP >>> long('1D4AA', 16) 119978L >>> unichr(long('1D4AA', 16)) Traceback (most recent call last): File "", line 1, in ? ValueError: unichr() arg not in range(0x10000) (narrow Python build) >>> x = eval("u'\\U000%s'" % '1D4AA') >>> x u'\U0001d4aa' >>> for c in x: ... print ord(c) ... 55349 56490 >>> unichr(55349) + unichr(56490) u'\U0001d4aa' >>> How do I convert strings such as '1D4AA' to unicode without using eval()? Alternatively, how can I break down the value 119978L into 55349 and 56490? From hall at ouhep1.nhn.ou.edu Fri Oct 10 16:25:50 2003 From: hall at ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue Oct 14 14:19:45 2003 Subject: [Tutor] Re: Random numbers In-Reply-To: Message-ID: In this case, the last number would not be random at all. Ike On Fri, 10 Oct 2003, Abel Daniel wrote: > UCT Student - DLLBIA001 writes: > > > i was just wandring if you could not help me to generate 25 random > > numbers in the range of 0 to 24 without any number repeating. > > Just a note: in this case you aren't 'generating random numbers' but > 'shuffling numbers'. > > Abel Daniel > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From m_anderson_0830 at yahoo.com Fri Oct 10 22:26:55 2003 From: m_anderson_0830 at yahoo.com (Michelle R. Anderson Anderson) Date: Tue Oct 14 14:19:51 2003 Subject: [Tutor] which way do I go? Message-ID: <20031011022655.44589.qmail@web11501.mail.yahoo.com> Hi Tutor: My name is Michelle. I am learning languages for the first time in my life and right now I'm kind of on my own with it. I have a pre-class assignment to complete, which is due by October 18, and I'm am totally lost. I need to create a function that receives two numbers as arguments. This function should add up all the integers between the two numbers, for example: If I called the function with the numbers 3 and 9, I should get: >>>sumdifference (3, 9) my result should be 30 this comes from adding the numbers 4+5+6+7+8=30 This program should give me an output of: the sum of integers between 3 and 9 is equal to 30 Now don't get me wrong, I am not looking for a step by step procedureto complete this problem. However, I have been through several tutorials and nothing has pointed me in the right direction. I've read about defining arguments and several other topics that seemed related, but I still cannot seem to get started. All that I need is a big push in the right direction and possibly some pointers on finishing it off. Please keep in mind that this is my very FIRST time attempting to program and I am doing this on my own (no instructors, no nothing). Thank you so much for your time. I cannot wait to hear your suggestions. --------------------------------- Do you Yahoo!? The New Yahoo! Shopping - with improved product search -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031010/0a8af4fb/attachment.html From tgoodear at bigpond.net.au Sat Oct 11 18:55:35 2003 From: tgoodear at bigpond.net.au (Trevor G) Date: Tue Oct 14 14:19:55 2003 Subject: [Tutor] A beginners question Message-ID: <000b01c3904a$c8920be0$4f09fea9@J23388.tfil.com> Hello guys, I am new to programming and have installed 2.3.2 onto my pc operating under Windows 98. 1. When I go to run a coded program ie Run Module F5 it takes a long time to actually 'run'. Is this a normal feature of Python or should it simply take several seconds and then 'run'. The code is very straight forward and is the type of exercises seen in any Python textbook for beginners ... chapter 1. Am I doing something stupid? Hope you can be of assistance. Thanks Trevor Goodear tgoodear@bigpond.net.au From psgopu at rediffmail.com Sun Oct 12 11:05:35 2003 From: psgopu at rediffmail.com (Perumal Sadagopan) Date: Tue Oct 14 14:19:59 2003 Subject: [Tutor] (no subject) Message-ID: <20031012150535.6815.qmail@webmail8.rediffmail.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031012/cbf5b793/attachment.html -------------- next part -------------- pl tell me how to edit a programm From druidmatt at yahoo.com Mon Oct 13 02:05:46 2003 From: druidmatt at yahoo.com (Matt Hehman) Date: Tue Oct 14 14:20:03 2003 Subject: [Tutor] Newbie - Outputting List to a File Message-ID: <20031013060546.31737.qmail@web10308.mail.yahoo.com> I have written a program that will either give you prime factors of an inputted number or inform you that it is prime. (That is pretty much my programming resume.) To do this, I begin by generating a list of prime numbers, and then I use them for mod operations. I was wondering if there was a way to save the list of primes generated to an output file so that I could just retrieve it and use it for the next number I tested. I tried the .write command and received the error message: TypeError: argument 1 must be string or read-only character buffer, not list Also, I started playing around with increasingly large numbers, is there anything I need to do to accomodate that? __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From lkvam at venix.com Mon Oct 13 09:00:28 2003 From: lkvam at venix.com (Lloyd Kvam) Date: Tue Oct 14 14:20:08 2003 Subject: [Tutor] Auto login of website In-Reply-To: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net> References: <5.1.0.14.0.20031012203457.01bda8d8@smtp.sbcglobal.net> Message-ID: <3F8AA1EC.4000407@venix.com> The urllib and urllib2 modules support accessing a website. The module documentation for urllib describes how to create your own class to override functions provided by urllib. In your case, you want to override the method: prompt_user_passwd to return a tuple containing your username and password. import urllib class MyURLopener(urllib.FancyURLopener): def prompt_user_passwd(host,realm): #ignore host and realm # substitue your id and password return ("mulder", "trustNo1") urllib._urlopener = MyURLopener() f = urllib.urlopen("http://www.some.com") print f.read() This omits cookie issues and other pitfalls. You may find it easier to use a program like wget to access URL's that have cookies and passwords to control access. Tony Cappellini wrote: > > > Would anyone happen to have a small python program (with or without gui) > that can > > log a user into a website, at regular intervals ? > > The program would have to take the following as input (can be > hard-coded, or on the cmd line) > > 1. the URL of a website (http) > 2. the user ID > 3. the user pasword > 4. click (simulate a keypress or mouse click) on the button to log the > user in > > if the user could not be logged in, due to the website being overloaded, > then it would do a retry at the next interval (where the interval can be > supplied by the user, preferably in seconds) > > I've already checked the Python Cookbook, didn't find a match for the > keywords I used > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From gventer at fish.co.uk Tue Oct 14 14:57:23 2003 From: gventer at fish.co.uk (Gerhard Venter) Date: Tue Oct 14 14:57:09 2003 Subject: [Tutor] assigning a variable Message-ID: <3F8C4713.8090704@fish.co.uk> Hi I have the following: >>> import os >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic translate') 11 >>> print K 0 What I am trying to do is a test to see if the website is running (as opposed to whether the web server is running). Curl reads the website for me and grep counts the occurences of the word translate. Later I might replace curl and grep with Python code that do the same job. My question is why does K not assume the value of 11 and what can I do to make it do so. Gerhard From project5 at redrival.net Tue Oct 14 15:27:27 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 14 15:29:38 2003 Subject: [Tutor] Re: Newbie - Outputting List to a File In-Reply-To: <20031013060546.31737.qmail@web10308.mail.yahoo.com> References: <20031013060546.31737.qmail@web10308.mail.yahoo.com> Message-ID: Matt Hehman wrote: > I was wondering if there was a way to save the list > of primes generated to an output file so that I could > just retrieve it and use it for the next number I > tested. I tried the .write command and received the > error message: It's called a method (function inside a class). > TypeError: argument 1 must be string or read-only > character buffer, not list Use the str() function to convert a list (or anything else for that matter) to a string, like this: somefile.write(str(somelist)) -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Tue Oct 14 15:28:41 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 14 15:40:48 2003 Subject: [Tutor] Re: A beginners question In-Reply-To: <000b01c3904a$c8920be0$4f09fea9@J23388.tfil.com> References: <000b01c3904a$c8920be0$4f09fea9@J23388.tfil.com> Message-ID: Trevor G wrote: > Hello guys, > I am new to programming and have installed 2.3.2 onto my pc operating under > Windows 98. > 1. When I go to run a coded program ie Run Module F5 it takes a long time to > actually 'run'. Is this a normal feature of Python or should it simply take > several seconds and then 'run'. The code is very straight forward and is the > type of exercises seen in any Python textbook for beginners ... chapter 1. > Am I doing something stupid? > Hope you can be of assistance. What IDE are you using? Is your PC very old? -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Tue Oct 14 15:43:26 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 14 15:45:40 2003 Subject: [Tutor] Re: which way do I go? In-Reply-To: <20031011022655.44589.qmail@web11501.mail.yahoo.com> References: <20031011022655.44589.qmail@web11501.mail.yahoo.com> Message-ID: Hi, > My name is Michelle. I am learning languages for the first time in > my life and right now I'm kind of on my own with it. I have a pre-class > assignment to complete, which is due by October 18, and I'm am totally Well, at least you started reasonably early on it. Have you browsed through the python tutorials, Alan Gauld's online book or Thinking Like a Computer Scientist in Python? All of these contain enough info to write your program. Here's a link: http://www.python.org/topics/learn/. > lost. I need to create a function that receives two numbers as > arguments. This function should add up all the integers between the two > numbers, for example: > > If I called the function with the numbers 3 and 9, I should get: > > >>>sumdifference (3, 9) > > my result should be 30 > this comes from adding the numbers 4+5+6+7+8=30 Assuming you don't want to dive into the exotic facilities for functional programming, here are some things you should study from one of the tutorials: - python's code structure (indentation!, variables, assignment) - mathematical operations (easy) - functions: def ...(): - the list data type: [] - the for loop: for ... in ...: - the while loop: while ...: - the range function: range() These are fairly simple things which you can probably grasp in a couple of hours. If you understand them, you know more than enough (quite literally, you don't need all of them) to write your program. But you will need to take a tutorial and follow it properly in order to understand how these things work. You can also try to write out your program on paper: pretend you have to write a step-by-step guide for solving your problem in such a way that a very stupid problem can use that step-by-step guide. Your computer is quite stupid, so that should work out just fine. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Tue Oct 14 15:46:10 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 14 15:50:33 2003 Subject: [Tutor] Re: editor (was: no subject) In-Reply-To: <20031012150535.6815.qmail@webmail8.rediffmail.com> References: <20031012150535.6815.qmail@webmail8.rediffmail.com> Message-ID: Perumal Sadagopan wrote: > pl tell me how to edit a programm My fav. editor is Spe (http://spe.pycs.net, wxPython based). SciTE (http://scintilla.org) is fast and versatile. PythonWin (included in the ActiveState python distro at http://activestate.com) is good too, but works only on Win. If all else fails, you can use Idle (included in your Python) - some people like it a lot, but I think it's ugly and slow. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From sigurd at 12move.de Tue Oct 14 16:04:30 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Oct 14 16:05:40 2003 Subject: [Tutor] which way do I go? In-Reply-To: <20031011022655.44589.qmail@web11501.mail.yahoo.com> (Michelle R. Anderson Anderson's message of "Fri, 10 Oct 2003 19:26:55 -0700 (PDT)") References: <20031011022655.44589.qmail@web11501.mail.yahoo.com> Message-ID: Michelle R. Anderson Anderson <- m_anderson_0830@yahoo.com wrote: > am totally lost. I need to create a function that receives two numbers > as arguments. This function should add up all the integers between the > two numbers, for example: > If I called the function with the numbers 3 and 9, I should get: >>>>sumdifference (3, 9) > my result should be 30 this comes from adding the numbers 4+5+6+7+8=30 > This program should give me an output of: the sum of integers between > 3 and 9 is equal to 30 There are a lot of solutions to your problem. I will show you one of them. First you should finf a way to generate a sequence of integers from your smaller input upto your bigger input. Let's call the smaller start and the bigger end. Python has a function which does nearly what you need: range(). range(3,9) generates a list from 3 upto 8. >>> range(3,9) [3, 4, 5, 6, 7, 8] >>> So start must be incremented by one before you use it with range. Let's write a toy example. >>> def ourrange(start, end): ... return range(start + 1, end) ... >>> ourrange(3,9) [4, 5, 6, 7, 8] >>> So now we know how to build out list we need a way to sum it up. I'll show you here a way how it can be done (there are plenty of others; some of them even nicer). If you want to use the elements of a list there is an easy way in Python to iterate (look up the meaning of it in an tutorial if you don't know it) over a list: for i in lst: will bind `i' successively to the values of the list elements. So: >>> for i in [1,2,3,4,5,6]: ... print i, i*2 ... 1 2 2 4 3 6 4 8 5 10 6 12 `i' got first bound to 1 then to 2, to 3 etc. That's nearly all you need. You know how to generate a list of integers, you know how to iterate over the list; so how do we sum integrs up? To assign a value in Python to a variable you simple write it with a `=' >>> num = 4 >>> print num 4 >>> num = num + 6 >>> num 10 >>> Here first we assigned 4 to num, then we assigned num the value of num + 6. Don't think like a mathematician about the way assignments are written; which it means is: num(newvalue) <- num(oldvalue) + 6 So bringing all that together gives (SPOILER) >>> def sumupintegers(start, end): ... result = 0 ... for num in range(start + 1, end): ... result = result + num ... return result ... >>> sumupintegers(3,9) 30 >>> Karl -- Please do *not* send copies of replies to me. I read the list From jeff at ccvcorp.com Tue Oct 14 16:34:31 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Oct 14 16:31:11 2003 Subject: [Tutor] assigning a variable References: <3F8C4713.8090704@fish.co.uk> Message-ID: <3F8C5DD7.1010608@ccvcorp.com> Gerhard Venter wrote: > I have the following: > > >>> import os > >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic > translate') > 11 > >>> print K > 0 > > My question is why does K not assume the value of 11 and what can I do > to make it do so. Not all output is return values. In fact, the two are completely separate. If you call a function from within the Python interpreter, and don't assign the return value to a variable, then Python will display it for you, and that's probably what's confusing you, but in this case they're two different things. The os.system() function runs a system command, and then returns the exit value of that command. Most system commands have exit values that indicate whether or not the command succeeded (and if it failed, some indication of why). In this case, '0' is the exit value of the curl command, which indicates that curl ran successfully. What you *want* to get, the 11, is the output of the command -- the shell's stdout. Just like any *nix filter or redirection, stdout can be piped to different programs or what have you. In this case, the stdout of curl is piped to grep, and the stdout from grep comes back to Python. Python simply prints the stdout of os.system() calls to the screen. If you want to be able to capture the stdout of your program, then you need to look into using os.popen() and its related functions. os.popen() will return an open file-like object that is connected to the stdout of the system command; you can then use that object's read()/readlines() method(s) to assign that output to a Python variable. Hope this helps! Jeff Shannon Technician/Programmer Credit International From sigurd at 12move.de Tue Oct 14 16:34:30 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Oct 14 16:36:27 2003 Subject: [Tutor] assigning a variable In-Reply-To: <3F8C4713.8090704@fish.co.uk> (Gerhard Venter's message of "Tue, 14 Oct 2003 19:57:23 +0100") References: <3F8C4713.8090704@fish.co.uk> Message-ID: On 14 Oct 2003, Gerhard Venter <- gventer@fish.co.uk wrote: > >>> import os > >>> K=os.system('curl -gs http://babelfish.altavista.com |grep -ic > >>> translate') > 11 > >>> print K > 0 [...] > My question is why does K not assume the value of 11 and what can I do > to make it do so. >>> help(os.system) Help on built-in function system: system(...) system(command) -> exit_status Execute the command (a string) in a subshell. >>> So the return value of os.system is the exit status of grep. If you want the 11 as return value you need one of the os.popen* functions. >>> g = os.popen('grep -c e .gnus.el') >>> g >>> g.next() '279\n' >>> Karl -- Please do *not* send copies of replies to me. I read the list From klappnase at freenet.de Tue Oct 14 19:16:12 2003 From: klappnase at freenet.de (Michael Lange) Date: Tue Oct 14 19:14:13 2003 Subject: [Tutor] (no subject) In-Reply-To: <20031012150535.6815.qmail@webmail8.rediffmail.com> References: <20031012150535.6815.qmail@webmail8.rediffmail.com> Message-ID: <20031015011612.405e2571.klappnase@freenet.de> On 12 Oct 2003 15:05:35 -0000 "Perumal Sadagopan" wrote: > pl tell me how to edit a programm Surely everyone have their own favorite editors, for linux I love Moleskine (http://www.micampe.it/moleskine.html). It is written in Python and uses Gtk, so maybe it will even run on windows if you install Gtk. Best regards Michael From tim at johnsons-web.com Tue Oct 14 23:52:00 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Oct 14 23:48:35 2003 Subject: [Tutor] Re: editor (was: no subject) In-Reply-To: References: <20031012150535.6815.qmail@webmail8.rediffmail.com> Message-ID: <20031015035200.GJ27005@johnsons-web.com> * Andrei [031014 12:00]: > Perumal Sadagopan wrote: > > >pl tell me how to edit a programm > > My fav. editor is Spe (http://spe.pycs.net, wxPython based). SciTE > (http://scintilla.org) is fast and versatile. PythonWin (included in the > ActiveState python distro at http://activestate.com) is good too, but works > only on Win. If all else fails, you can use Idle (included in your Python) > - some people like it a lot, but I think it's ugly and slow. I use vim. Some people think vim is strange because of its modal style of editing. Some people think python is strange because of the indent-sensitive control blocks. But it works and so does vim. Vim + compiled-in python binary + python plugins = one fine IDE. tim (and pythonwin rocks too!) -- Tim Johnson http://www.alaska-internet-solutions.com From fredm at smartypantsco.com Wed Oct 15 00:25:47 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Wed Oct 15 00:26:33 2003 Subject: [Tutor] Printing Chinese characters? Message-ID: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1> Hi: I wonder if anyone can help me? I have a string which I believe is made up of Chinese characters, but I cannot display it properly. The string is >>> b = '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf' This prints out as: >>> print b ??????????????????????????? which clearly is not Chinese :) Does anyone know if there is an encoding I could use to make it display correctly? Thanks in anticipation, Fred Milgrom From Jaco.Smuts at za.didata.com Wed Oct 15 03:08:17 2003 From: Jaco.Smuts at za.didata.com (Jaco Smuts (ZA)) Date: Wed Oct 15 03:08:27 2003 Subject: [Tutor] parsing search engine keywords from search referrer log Message-ID: Hello everyone I'm about to start work on a little program to assist me with analyzing my web server logs (in mysql using mod_log_sql). I want to parse out Search phrases from the referrer fields (where referrer is a search engine). Does any one have any ideas on how best to approach this, or some code that already does this ? thanks in advance Jaco This email and all contents are subject to the following disclaimer: "http://www.didata.com/disclaimer.asp" From amonroe at columbus.rr.com Wed Oct 15 09:08:46 2003 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Oct 15 09:08:53 2003 Subject: [Tutor] Forcing file modified date to arbitrary future date? In-Reply-To: References: Message-ID: <16951867171.20031015090846@columbus.rr.com> Subject says it all - I need a way to change the last modified date of a file to any arbitrary future date. I didn't see anything in os.path. It has a "getmtime" function, but not a matching "setmtime", that I could see. I don't mind using win32api if there's not a function in the standard libraries. Alan From pythontutor at venix.com Wed Oct 15 09:52:17 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Oct 15 09:52:28 2003 Subject: [Tutor] Forcing file modified date to arbitrary future date? In-Reply-To: <16951867171.20031015090846@columbus.rr.com> References: <16951867171.20031015090846@columbus.rr.com> Message-ID: <3F8D5111.2060301@venix.com> (replying to another email and changing the subject does not change the threading. It's best to create a new email to start a new thread.) os.utime should do what you want. R. Alan Monroe wrote: > Subject says it all - I need a way to change the last modified date of > a file to any arbitrary future date. I didn't see anything in os.path. > It has a "getmtime" function, but not a matching "setmtime", that I > could see. I don't mind using win32api if there's not a function in > the standard libraries. > > Alan > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Wed Oct 15 13:46:29 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 15 13:46:34 2003 Subject: [Tutor] Newbie - Outputting List to a File [using shelve / long integers] In-Reply-To: <20031013060546.31737.qmail@web10308.mail.yahoo.com> Message-ID: On Sun, 12 Oct 2003, Matt Hehman wrote: > I was wondering if there was a way to save the list of primes generated > to an output file so that I could just retrieve it and use it for the > next number I tested. I tried the .write command and received the error > message: > > TypeError: argument 1 must be string or read-only character buffer, not > list Ah! Try using the 'shelve' module: it provides persistant storage for Python objects, and handles some of the low-level details of how to do it efficiently. http://www.python.org/doc/lib/module-shelve.html In particular, it deals with the details to convert live Python objects into "character" bytes that can be written to disk. Let's show a complete interactive session as a demonstration. In the first session, I'll generate a shelved object, and in the second, I'll try retrieving that shelved object: ### bash-2.05a$ python Python 2.2 (#1, 11/12/02, 23:31:59) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> numbers = [42, 17, 3.1415926] >>> import shelve >>> d = shelve.open('storage') >>> d['numbers'] = numbers >>> d.close() ### That's the first session. Let's see if we can get back our numbers now: ### bash-2.05a$ python Python 2.2 (#1, 11/12/02, 23:31:59) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import shelve >>> d = shelve.open('storage') >>> numbers = d['numbers'] >>> numbers [42, 17, 3.1415926000000001] ### Try it out, and feel free to ask more questions about shelve; it's very nice for saving the state of Python objects. > Also, I started playing around with increasingly large numbers, is there > anything I need to do to accomodate that? If you're using large integers, you should be fine --- Python will automagically promote an integer into a "long int" if it goes beyond the range of a normal 32-bit integer. For example, it's easy to do 2 to the 40'th power: ### >>> 2**40 1099511627776L ### The trailing 'L' at the end there tells us that Python is using long-integers to represent the number, since it's too large to store using a hardware representation. Good luck! From gbrunet at sempersoft.com Wed Oct 15 15:22:09 2003 From: gbrunet at sempersoft.com (Greg Brunet) Date: Wed Oct 15 15:22:36 2003 Subject: [Tutor] Re: Re: Testing for punctuation in a string References: <002f01c390e1$3d153ff0$6401a8c0@xp><200310122335.34640.anna@aleax.it> Message-ID: Hi Michael: "Michael Janssen" wrote in message news:Pine.A41.4.56.0310131536310.1526002@hermes-22.rz.uni-frankfurt.de... > When I may take a look at your latest approach (Testing legality by > definig a pattern the Field Name must match): > > > p=re.compile('^[a-zA-Z]\w*$') > > def fldNameValid(fldName): > > return p.match(fldName) != None > > Doing things the other way around as in ones own goal-definition > (supposed I can take the thread's subject as such a thing ;-) might > be a clever choice in case it becomes clear that it's better than the > "former way around". Nevertheless it might introduce some unforeseen > results: Now, your pattern rejects whitespace and commas; Field Names > starting with numbers or an underscore will be rejected. All this might > be perfectly what you needs but it doesn't do the "Testing for > punctuation in a string" job any longer. > > Beside this (and given that the additional restrictions for valid Field > Names are what you need), you're solution will do the job, and you won't > feel much of a performance impact as long as you don't want to parse a > serveral kB's commandline ;-) Thanks for the comments. You are right that my original request (just testing for any punctuation in a string) was a simplification of my complete needs (to make sure that I had valid field names). Whereas I originally allowed commas (as field separators), once I start checking individual fields they are obviously not valid. After my original posting, I decided that I really should be checking for all invalid field names (e.g. starting with a numeral), thus the need to re-work / improve my objective. The answer to my original question is still of interest & value to me, since I am not completely up to speed on the 'correct' or most Pythonic way of doing various string operations. So thanks to all who helped out on this, -- Greg From hec.villafuerte at telgua.com.gt Wed Oct 15 18:31:06 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Wed Oct 15 16:30:46 2003 Subject: [Tutor] Interfacing MySQL and Python Message-ID: <3F8DCAAA.9020308@telgua.com.gt> Hi all, I need to start using Python in conjunction with MySQL, but in http://sourceforge.net/projects/mysql-python which leads to http://dustman.net/andy/python/MySQLdb_obsolete appears this message: MySQLdb module 0.3.5 OBSOLETE Python Interface to MySQL So, what is the easiest way to connect from Python to MySQL? and, what is the fastest way? Any link to additional info would be great. Thanks in advance. From pythontutor at venix.com Wed Oct 15 17:08:26 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Oct 15 17:08:31 2003 Subject: [Tutor] Interfacing MySQL and Python In-Reply-To: <3F8DCAAA.9020308@telgua.com.gt> References: <3F8DCAAA.9020308@telgua.com.gt> Message-ID: <3F8DB74A.1010800@venix.com> http://www.python.org/pypi?:action=display&name=MySQL-python&version=0.9.2 Python Packages Index Don't know where you hit a faulty link, but this is the current version which works well. H?ctor Villafuerte D. wrote: > Hi all, > I need to start using Python in conjunction with MySQL, > but in > http://sourceforge.net/projects/mysql-python > which leads to > http://dustman.net/andy/python/MySQLdb_obsolete > appears this message: > > MySQLdb module 0.3.5 > OBSOLETE Python Interface to MySQL > > So, what is the easiest way to connect from Python to MySQL? > and, what is the fastest way? > Any link to additional info would be great. Thanks in advance. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Wed Oct 15 17:40:41 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 15 17:41:09 2003 Subject: [Tutor] parsing search engine keywords from search referrer log In-Reply-To: Message-ID: On Wed, 15 Oct 2003, Jaco Smuts (ZA) wrote: > I'm about to start work on a little program to assist me with analyzing > my web server logs (in mysql using mod_log_sql). > > I want to parse out Search phrases from the referrer fields (where > referrer is a search engine). Does any one have any ideas on how best to > approach this, or some code that already does this ? Hi Jaco, Do you have examples of some of what these referrer fields look like? I did a quick Google search: it does look like the Python Community Server Project http://pycs.sourceforge.net/ is writing some interesting software. For example, they have a referrer-log analyzer: http://cvs.sourceforge.net/viewcvs.py/*checkout*/pycs/pycs/analyse_logs.py?content-type=text%2Fplain&rev=1.9 Their approach appears to be use regular expressions to parse the request message for their logs. I'm not sure how easy it would be to adopt their code exactly, but the idea seems right. Are you familiar with regular expressions? If not, there's an introduction to them here: http://www.amk.ca/python/howto/regex/ Please feel free to ask questions about them on Tutor; we'll be happy to help. Good luck to you! From alan.gauld at blueyonder.co.uk Wed Oct 15 17:41:53 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Oct 15 17:42:42 2003 Subject: [Tutor] which way do I go? References: <20031011022655.44589.qmail@web11501.mail.yahoo.com> Message-ID: <004101c39365$26345650$6401a8c0@xp> > >>>sumdifference (3, 9) > > my result should be 30 > this comes from adding the numbers 4+5+6+7+8=30 Look at how to define functions. You need a function called sumdifference that takes two arguments, therefore your definition has to have two parameters, lets call them x and y. You want to add all the values from x+1 to y-1. Look at the range(x,y) function in Python, it generates numbers in the range x to y-1 which is nearly what you want. Also to add the numbers together you need to repeat the addition for each numvber. Look at the for command in Python. In my tutor the relevant topics are: Simple sequences Looping Functions and Modules I hope thats enough of a starter along with the other comments. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Wed Oct 15 17:48:22 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Oct 15 17:49:10 2003 Subject: [Tutor] Re: editor (was: no subject) References: <20031012150535.6815.qmail@webmail8.rediffmail.com> <20031015035200.GJ27005@johnsons-web.com> Message-ID: <005a01c39366$0e3a39b0$6401a8c0@xp> > Perumal Sadagopan wrote: > > >pl tell me how to edit a programm Open any text editor(even notepad if you like!). Type Python commands into it. Save the file giving it a name that ends in .py Make sure it is saved as plain ASCII text not RTF or MS Word format etc. The new file is a python program that you can run by double clicking in explorer(assuming you use Windows) or by typing python file.py where file.py should be whatever you called your program. If its a short program you may find it closes too quickly to see it, in which case add the line raw_input("Hit return to quit...") as the last line. HTH, Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Oct 15 17:52:16 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 15 17:52:34 2003 Subject: [Tutor] Printing Chinese characters? In-Reply-To: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1> Message-ID: On Wed, 15 Oct 2003, Alfred Milgrom wrote: > I have a string which I believe is made up of Chinese characters, but I > cannot display it properly. > The string is > >>> b =3D > '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\x= e7\xba?\xf8\xb9\xa5\xa3\xbf' > > This prints out as: > > >>> print b > =BA=DA=CF?=AC=B3=A3=BC=FB=B5=C4=C6=E5=D0?=AC=BA=DA=C8=E7=BA?=F8=B9=A5=A3= =BF > > which clearly is not Chinese :) Hi Alfred, It all looks Greek to me. *grin* When you say "display", do you mean display in a Tkinter window? Most terminal windows don't natively support extended character sets, so you might need to use a GUI to properly see those characters. I'm guessing that you might be doing Unicode? If so, maybe use can use your web browser to help? I wrote a small post a while back: http://mail.python.org/pipermail/tutor/2002-December/019087.html that generates the Korean unicode character for the letter "Yoo". *wink* But that character string you've posted: ### s =3D ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' + '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf') ### will need to be first decoded from whatever byte encoding it is in now into Unicode before any display approach will work. Let's try something: ### >>> s =3D ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' + =2E.. '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf') >>> s.decode('utf-8') Traceback (most recent call last): File "", line 1, in ? UnicodeError: UTF-8 decoding error: unexpected code byte >>> s.decode('utf-16') Traceback (most recent call last): File "", line 1, in ? UnicodeError: UTF-16 decoding error: truncated data ### Hmmm... no luck there. The 'encodings' page: http://www.python.org/doc/lib/node126.html shows the native encodings that Python supports out of the box. I'm not quite sure if we can guess the byte encoding, although the tests above immediately discount UTF-8 and UTF-16. Do you have more information on the byte encoding is being used for your string 's'? Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Oct 15 18:04:18 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 15 18:04:23 2003 Subject: [Tutor] which way do I go? In-Reply-To: <004101c39365$26345650$6401a8c0@xp> Message-ID: On Wed, 15 Oct 2003, Alan Gauld wrote: > > >>>sumdifference (3, 9) > > > > my result should be 30 > > this comes from adding the numbers 4+5+6+7+8=30 > > Look at how to define functions. Time for more contradictory suggestions. *grin* Simplifed problem: Can you write a program that sums the numbers from 0 to 9? How about a program that sums the numbers from 0 to 3? More generally: Can you write a function that accepts an input 'n' and sums the numbers from 0 to n? This problem should be simpler for you, since the left endpoint is always at zero. (It should also remind you of a problem you really should have seen in algebra called "Gauss's sum".) If you have a function that solves the simpler zero-based problem, you can get the sum of an arbitrary interval in a very cute way. Good luck to you. From hec.villafuerte at telgua.com.gt Wed Oct 15 20:31:49 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Wed Oct 15 18:31:24 2003 Subject: [Tutor] site-packages folder Message-ID: <3F8DE6F5.3040805@telgua.com.gt> Hi, I downloaded dbfpy.tgz (for managing .DBF tables) and then I extracted it to: C:\Python23\Lib\site-packages\dbfpy but when I try to import the module, it fails: >>> from dbf import * Traceback (most recent call last): File "", line 1, in -toplevel- from dbf import * ImportError: No module named dbf >>> Obviously I need to do something to register this module (not just extract it to C:\Python23\Lib\site-packages). Thanks in advance. From Jaco.Smuts at za.didata.com Wed Oct 15 18:36:53 2003 From: Jaco.Smuts at za.didata.com (Jaco Smuts (ZA)) Date: Wed Oct 15 18:42:52 2003 Subject: [Tutor] parsing search engine keywords from search referrer log Message-ID: Hello Danny Thank you for your response. Because my logs are in MySQL I suspect regular expressions might be an overkill. This is a part time venture so my progress is a series of sporadic spurts of progress vs. none. I have played with urlparse.urlparse and cgi.parseqs~~~. All I need to do still is split the results into words (I want to analyse search phrases and keywords). And build some kind of engine that can recognize different search engines and apply specific rules for each. Any suggestions on this will also be welcome. I'm hoping to get away with a simple identification method linked to an (generic, if possible) algorithm. I will play a bit more and post my code. I'm sure I can greatly benefit from watching the guru's correct my efforts :-) thank you Jaco Smuts ~~~ It seems a bit silly that I need to use to libraries to work with url's and querstrings. ps. lastly allow me to be facetious: Some people, when confronted with a [programming] problem, think, "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Wednesday, October 15, 2003 11:41 PM To: Jaco Smuts (ZA) Cc: tutor@python.org Subject: Re: [Tutor] parsing search engine keywords from search referrer log On Wed, 15 Oct 2003, Jaco Smuts (ZA) wrote: > I'm about to start work on a little program to assist me with analyzing > my web server logs (in mysql using mod_log_sql). > > I want to parse out Search phrases from the referrer fields (where > referrer is a search engine). Does any one have any ideas on how best to > approach this, or some code that already does this ? Hi Jaco, Do you have examples of some of what these referrer fields look like? I did a quick Google search: it does look like the Python Community Server Project http://pycs.sourceforge.net/ is writing some interesting software. For example, they have a referrer-log analyzer: http://cvs.sourceforge.net/viewcvs.py/*checkout*/pycs/pycs/analyse_logs. py?content-type=text%2Fplain&rev=1.9 Their approach appears to be use regular expressions to parse the request message for their logs. I'm not sure how easy it would be to adopt their code exactly, but the idea seems right. Are you familiar with regular expressions? If not, there's an introduction to them here: http://www.amk.ca/python/howto/regex/ Please feel free to ask questions about them on Tutor; we'll be happy to help. Good luck to you! This email and all contents are subject to the following disclaimer: "http://www.didata.com/disclaimer.asp" From learning.python at dbmail.dk Wed Oct 15 21:22:35 2003 From: learning.python at dbmail.dk (Ole Jensen) Date: Wed Oct 15 21:22:53 2003 Subject: [Tutor] Databases Message-ID: <001601c39383$fae02be0$9e4c73d5@BAERBAR> Hi everybody I'm currently experimenting on creating some python generated web pages, and was wondering what databases are used for... (Sorry if it is abit to vague/general) Basically what I have been thinking of doing (without using a database) is having a few articles as text documents (with html code i.e.

's and 's) and importing them into python and displaying the text into an entire page (with tables and pics et al). Without any prior experince in web programming I was just curious, if this is something that is (normally) done with databases, or how they are used (in simple terms *grin*) in practise. Also would you recommend me to try and play around with some variant of a database or to just relax and get to understand basic CGI/web programming better before starting with it now? I realize you don't know my current level but as a general pointer, is it best saved for later? I have been trying to google for it but I didn't really find anything useful... Regards Ole Jensen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031016/abb7358f/attachment.html From fredm at smartypantsco.com Wed Oct 15 23:54:54 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Wed Oct 15 23:56:29 2003 Subject: [Tutor] Printing Chinese characters? In-Reply-To: References: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1> Message-ID: <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1> Hi Danny: Thanks for your reply. Given that this is a Chinese string, I think it might be a BIG-5 encoding, but I am unable to find the proper encoding files. In my distribution of Python, there is an encodings directory under Python22/Lib, and a file called aliases.py. As I understand it, this module is used by the encodings package search function to map encodings names to module names. There is an interesting comment under CJK encodings (Chinese, Japanese, Korean) as follows: # The codecs for these encodings are not distributed with the # Python core, but are included here for reference, since the # locale module relies on having these aliases available. Do you (or anyone else) know where I can get the Chinese encodings, including BIG-5? Thanks in advance, Fred Milgrom At 02:52 PM 15/10/03 -0700, Danny Yoo wrote: > >But that character string you've posted: > >### >s = ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' + > '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf') >### >will need to be first decoded from whatever byte encoding it is in now >into Unicode before any display approach will work. > > Do you have more information on >the byte encoding is being used for your string 's'? > >Good luck to you! From neal at bcn.boulder.co.us Thu Oct 16 00:44:28 2003 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Thu Oct 16 00:44:49 2003 Subject: [Tutor] Printing Chinese characters? In-Reply-To: <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1> References: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1> <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1> Message-ID: <20031016044428.GR1348@feynman> Well, I think the idea that it is at least similar to big5 is right. But it may have a Japanese hiragana character also. But to make that work I had to drop the '?' characters, as well as the \xc8 (trial and error....) I used linux and the free, quirky but very handy "recode" program to do the recoding. I inserted a few newlines to help keep my place.... original string: '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf' my script: $ python2 -c "print '\xba\xda\xcf\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0\xac\xba\xda\n\xe7\xba\xf8\xb9\xa5\xa3'" | recode big5..dump Output, in Unicode UCS2 form: UCS2 Mne Description 7AAA 6D09 90FD 7357 8154 3081 me hiragana letter me 8867 7AAA 000A LF line feed (lf) 8765 7E97 5974 000A LF line feed (lf) Those characters can be looked up via the Unihan.txt file at unicode.org, yielding the name of each character, and in many common cases also pronunciation and a definition: $ for i in 7AAA 6D09 90FD 7357 8154 3081 8867 7AAA 000A 8765 7E97 5974 000A; do fgrep $i Unihan.txt | grep kDefinition; done U+7AAA kDefinition hollow; pit; depression; swamp U+90FD kDefinition metropolis, capital; all, the whole; elegant, refined U+7357 kDefinition unruly, wild, violent, lawless U+8154 kDefinition chest cavity; hollow in body U+7AAA kDefinition hollow; pit; depression; swamp U+8765 kDefinition a fly which is used similarly to cantharides U+5974 kDefinition slave, servant The other characters weren't in that "dictionary". I don't know what the deal is with the characters I had to drop out, so it may be some other character set which is related to big5. But I think that for someone who knows no Chinese, using free tools and databases.... Cheers, Neal McBurnett http://bcn.boulder.co.us/~neal/ Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 On Thu, Oct 16, 2003 at 01:54:54PM +1000, Alfred Milgrom wrote: > Hi Danny: > > Thanks for your reply. > Given that this is a Chinese string, I think it might be a BIG-5 encoding, > but I am unable to find the proper encoding files. > > In my distribution of Python, there is an encodings directory under > Python22/Lib, and a file called aliases.py. As I understand it, this module > is used by the encodings package search function to map encodings names to > module names. > > There is an interesting comment under CJK encodings (Chinese, Japanese, > Korean) as follows: > # The codecs for these encodings are not distributed with the > # Python core, but are included here for reference, since the > # locale module relies on having these aliases available. > > Do you (or anyone else) know where I can get the Chinese encodings, > including BIG-5? > > Thanks in advance, > Fred Milgrom > > > At 02:52 PM 15/10/03 -0700, Danny Yoo wrote: > > > > >But that character string you've posted: > > > >### > >s = ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' + > > '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf') > >### > >will need to be first decoded from whatever byte encoding it is in now > >into Unicode before any display approach will work. > > > > Do you have more information on > >the byte encoding is being used for your string 's'? > > > >Good luck to you! > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From neal at bcn.boulder.co.us Thu Oct 16 00:54:41 2003 From: neal at bcn.boulder.co.us (Neal McBurnett) Date: Thu Oct 16 00:54:54 2003 Subject: [Tutor] Printing Chinese characters? In-Reply-To: <20031016044428.GR1348@feynman> References: <5.1.0.14.0.20031015141811.033e11a0@192.168.1.1> <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1> <20031016044428.GR1348@feynman> Message-ID: <20031016045441.GS1348@feynman> Ahh - and the final step - that would yield this utf-8 encoding (of the original string minus the troublesome characters) rendered as a python string: print '\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8\x85\x94\xe3\x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d\xa5\xe7\xba\x97\xe5\xa5\xb4\x0a' which prints fine on my utf-8-enabled xterm, as described so wonderfuly at http://www.cl.cam.ac.uk/~mgk25/unicode.html by Markus Kuhn. Though a few characters aren't in the free font I got with X11/Redhat 7.3. Of course I may be way off-base here - just playing around with it. -Neal On Wed, Oct 15, 2003 at 10:44:28PM -0600, Neal McBurnett wrote: > Well, I think the idea that it is at least similar to big5 is right. > But it may have a Japanese hiragana character also. > > But to make that work I had to drop the '?' characters, as well as the > \xc8 (trial and error....) > > I used linux and the free, quirky but very handy "recode" program to > do the recoding. I inserted a few newlines to help keep my place.... > > original string: > '\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf' > > my script: > $ python2 -c "print '\xba\xda\xcf\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6\xe5\xd0\xac\xba\xda\n\xe7\xba\xf8\xb9\xa5\xa3'" | > recode big5..dump > > Output, in Unicode UCS2 form: > > UCS2 Mne Description > > 7AAA > 6D09 > 90FD > 7357 > 8154 > 3081 me hiragana letter me > 8867 > 7AAA > 000A LF line feed (lf) > 8765 > 7E97 > 5974 > 000A LF line feed (lf) > > Those characters can be looked up via the Unihan.txt file at > unicode.org, yielding the name of each character, and in many common > cases also pronunciation and a definition: > > $ for i in 7AAA 6D09 90FD 7357 8154 3081 8867 7AAA 000A 8765 7E97 5974 000A; do > fgrep $i Unihan.txt | grep kDefinition; done > > U+7AAA kDefinition hollow; pit; depression; swamp > U+90FD kDefinition metropolis, capital; all, the whole; elegant, > refined > U+7357 kDefinition unruly, wild, violent, lawless > U+8154 kDefinition chest cavity; hollow in body > U+7AAA kDefinition hollow; pit; depression; swamp > U+8765 kDefinition a fly which is used similarly to cantharides > U+5974 kDefinition slave, servant > > The other characters weren't in that "dictionary". > > I don't know what the deal is with the characters I had to drop out, > so it may be some other character set which is related to big5. > > But I think that for someone who knows no Chinese, using > free tools and databases.... > > Cheers, > > Neal McBurnett http://bcn.boulder.co.us/~neal/ > Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 > > > On Thu, Oct 16, 2003 at 01:54:54PM +1000, Alfred Milgrom wrote: > > Hi Danny: > > > > Thanks for your reply. > > Given that this is a Chinese string, I think it might be a BIG-5 encoding, > > but I am unable to find the proper encoding files. > > > > In my distribution of Python, there is an encodings directory under > > Python22/Lib, and a file called aliases.py. As I understand it, this module > > is used by the encodings package search function to map encodings names to > > module names. > > > > There is an interesting comment under CJK encodings (Chinese, Japanese, > > Korean) as follows: > > # The codecs for these encodings are not distributed with the > > # Python core, but are included here for reference, since the > > # locale module relies on having these aliases available. > > > > Do you (or anyone else) know where I can get the Chinese encodings, > > including BIG-5? > > > > Thanks in advance, > > Fred Milgrom > > > > > > At 02:52 PM 15/10/03 -0700, Danny Yoo wrote: > > > > > > > >But that character string you've posted: > > > > > >### > > >s = ('\xba\xda\xcf?\xac\xb3\xa3\xbc\xfb\xb5\xc4\xc6' + > > > '\xe5\xd0?\xac\xba\xda\xc8\xe7\xba?\xf8\xb9\xa5\xa3\xbf') > > >### > > >will need to be first decoded from whatever byte encoding it is in now > > >into Unicode before any display approach will work. > > > > > > Do you have more information on > > >the byte encoding is being used for your string 's'? > > > > > >Good luck to you! > > > > > > > > _______________________________________________ > > 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 Thu Oct 16 02:47:31 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 16 02:47:50 2003 Subject: [Tutor] Printing Chinese characters? In-Reply-To: <20031016045441.GS1348@feynman> Message-ID: On Wed, 15 Oct 2003, Neal McBurnett wrote: > Ahh - and the final step - that would yield this utf-8 encoding (of the > original string minus the troublesome characters) rendered as a python > string: > > print > '\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8\x85\x94\xe3 > \x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d\xa5\xe7\xba\x97\xe5\xa5 > \xb4\x0a' Ah, then it is UTF-8 then? Oh, I must have introduced some weird characters when I copied and pasted. You're right! Oh, cool! ### >>> s = ('\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8' ... + '\x85\x94\xe3\x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d' ... + '\xa5\xe7\xba\x97\xe5\xa5\xb4').decode('utf8') >>> s u'\u7aaa\u6d09\u90fd\u7357\u8154\u3081\u8867\u7aaa\u8765\u7e97\u5974' ### There, now it's decoding properly. Yes, it matches what Neal decoded: > > U+7AAA kDefinition hollow; pit; depression; swamp > > U+90FD kDefinition metropolis, capital; all, the whole; elegant, > > refined > > U+7357 kDefinition unruly, wild, violent, lawless > > U+8154 kDefinition chest cavity; hollow in body > > U+7AAA kDefinition hollow; pit; depression; swamp > > U+8765 kDefinition a fly which is used similarly to cantharides > > U+5974 kDefinition slave, servant Wow, that sounds rather... um... grim. *grin* Most web browsers have native support for utf8-encoded files, so, in a pinch, you might be able to see the message this way: ### msg = ('\xe7\xaa\xaa\xe6\xb4\x89\xe9\x83\xbd\xe7\x8d\x97\xe8' + '\x85\x94\xe3\x82\x81\xe8\xa1\xa7\xe7\xaa\xaa\xe8\x9d' + '\xa5\xe7\xba\x97\xe5\xa5\xb4') print """

%s

""" % msg ### Redirect the result of this to an HTML file, and then try browsing it. If you're still having trouble seeing it, visit: http://hkn.eecs.berkeley.edu/~dyoo/weird_chinese_msg.pdf I've printed it out as a PDF as a stopgap measure if you're really desperate to see the Chinese characters. *grin* But does anyone know if ReportLab's happy with UTF-8 characters? > > > There is an interesting comment under CJK encodings (Chinese, Japanese, > > > Korean) as follows: > > > # The codecs for these encodings are not distributed with the > > > # Python core, but are included here for reference, since the > > > # locale module relies on having these aliases available. > > > > > > Do you (or anyone else) know where I can get the Chinese encodings, > > > including BIG-5? Here you go: http://cjkpython.i18n.org/ It looks like we won't need them this time, but if we run across BIG5 encoded files, we'll know what to do to transform them to utf8 now. Good luck! From sabineq at wisemail.weizmann.ac.il Thu Oct 16 08:15:11 2003 From: sabineq at wisemail.weizmann.ac.il (Sabine Ruth Quadt) Date: Thu Oct 16 08:15:20 2003 Subject: [Tutor] Configuring for Tk Message-ID: Hallo, I have a problem configuring Python for Tk. I changed the file Modules/Setup and uncommented the lines for tkinter and edited the lines for my TcL/Tk libraries and headers. I execute make Makefile. When I then run mke, I get a lot of error messages about undefined references like the folowing: /sabine/SOFTWARE/python/Python-2.3.2/Modules/tkappinit.c:74: undefined reference to `Tk_MainWindow' Can someone help me? Thanks Sabine From amk at amk.ca Thu Oct 16 10:42:18 2003 From: amk at amk.ca (amk@amk.ca) Date: Thu Oct 16 10:42:24 2003 Subject: [Tutor] site-packages folder In-Reply-To: <3F8DE6F5.3040805@telgua.com.gt> References: <3F8DE6F5.3040805@telgua.com.gt> Message-ID: <20031016144218.GB4406@rogue.amk.ca> On Wed, Oct 15, 2003 at 04:31:49PM -0800, "H?ctor Villafuerte D." wrote: > C:\Python23\Lib\site-packages\dbfpy Was what you unzipped a source or a built distribution? If it's the source distribution, you shouldn't have unpacked it in site-packages; instead you would have unpacked it somewhere else and run the included setup.py script to install the code in site-packages. The package should have had a README explaining what to do. --amk From hec.villafuerte at telgua.com.gt Thu Oct 16 12:54:17 2003 From: hec.villafuerte at telgua.com.gt (=?ISO-8859-1?Q?=22H=E9ctor_Villafuerte_D=2E=22?=) Date: Thu Oct 16 10:53:50 2003 Subject: [Tutor] Interfacing MySQL and Python In-Reply-To: <04875CB4331F0240A0AD66F970978651011375A0@paul> References: <04875CB4331F0240A0AD66F970978651011375A0@paul> Message-ID: <3F8ECD39.6080302@telgua.com.gt> Jason Tesser wrote: >What versions of Mysql and Python are you running? > > > Thank you all! I downloaded MySQLdb 0.92 and it is working just great. I got mislead with the "obsolete" message in the project page. From carroll at tjc.com Thu Oct 16 18:07:48 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Oct 16 18:07:53 2003 Subject: [Tutor] Printing Chinese characters? In-Reply-To: <5.1.0.14.0.20031016134659.03a0e6d0@192.168.1.1> Message-ID: On Thu, 16 Oct 2003, Alfred Milgrom wrote: > Do you (or anyone else) know where I can get the Chinese encodings, > including BIG-5? Alfred -- The Unicode orginazation has a file with the mappings of major Asian encodings to Unicode at http://www.unicode.org/Public/UNIDATA/Unihan.txt It's 25 meg. The Big-5 encodings are associated with the tag "kBigFive". I have a Python module, still in rough form, for looking up entries in the Unihan.txt file. I was planning on releasing in when I have it in a little bit better state, but I'd be happy to share a copy with you now, as long as you realize it's still pretty rough. -- Terry Carroll Santa Clara, CA carroll@tjc.com From missive at hotmail.com Thu Oct 16 18:36:40 2003 From: missive at hotmail.com (Lee Harr) Date: Thu Oct 16 18:36:44 2003 Subject: [Tutor] Re: Databases Message-ID: >I'm currently experimenting on creating some python generated web pages, = >and was wondering what databases are used for... (Sorry if it is abit to = >vague/general) > They are used to store data. If your site is very simple, you could just use flat files (text files) or if it gets more complex you would want to use a relational database (postgresql is a very good free one) >Basically what I have been thinking of doing (without using a database) = >is having a few articles as text documents (with html code i.e.

's = >and 's) and importing them into python and displaying the text into = >an entire page (with tables and pics et al). > >Without any prior experince in web programming I was just curious, if = >this is something that is (normally) done with databases, or how they = >are used (in simple terms *grin*) in practise. > Depends on how many articles you have, how many people will be working on them / updating them / adding new articles. Look at a site like http://slashdot.org/ for a great example of articles (and comments on those articles) stored in a database, then presented to users through a web interface. >Also would you recommend me to try and play around with some variant of = >a database or to just relax and get to understand basic CGI/web = >programming better before starting with it now? I realize you don't know = >my current level but as a general pointer, is it best saved for later? > If you like python, you may want to try Zope (the 800-pound gorilla of python web programming) or one of the lighter-weight web frameworks. Web programming is interesting. Web programming backed up by a database is even more interesting. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo at hkn.eecs.berkeley.edu Thu Oct 16 20:29:39 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Oct 16 20:29:48 2003 Subject: [Tutor] Re: Databases [Phil Greenspun's Panda book] In-Reply-To: Message-ID: On Thu, 16 Oct 2003, Lee Harr wrote: > >I'm currently experimenting on creating some python generated web > >pages, = and was wondering what databases are used for... (Sorry if it > >is abit to = vague/general) > > They are used to store data. If your site is very simple, you could > just use flat files (text files) or if it gets more complex you would > want to use a relational database (postgresql is a very good free one) [some text cut] > Look at a site like http://slashdot.org/ for a great example of articles > (and comments on those articles) stored in a database, then presented to > users through a web interface. There's another good online book by Phil Greenspun that talks about how to develop a database-backed web site: http://philip.greenspun.com/panda/ http://philip.greenspun.com/panda/databases-intro The advice he gives applies equally well to any computer language, and, more importantly, it's an entertaining read. *grin* Good luck to you! From carroll at tjc.com Thu Oct 16 22:54:05 2003 From: carroll at tjc.com (Terry Carroll) Date: Thu Oct 16 22:54:09 2003 Subject: [Tutor] unichr() question In-Reply-To: <29E16390A38FD7118A03000BCD0F3F6501223811@mail.spiglobe.com> Message-ID: On Tue, 14 Oct 2003, Ezequiel, Justin wrote: > PythonWin 2.2.2 > Windows XP > > >>> long('1D4AA', 16) > 119978L > >>> unichr(long('1D4AA', 16)) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: unichr() arg not in range(0x10000) (narrow Python build) > >>> x = eval("u'\\U000%s'" % '1D4AA') > >>> x > u'\U0001d4aa' > >>> for c in x: > ... print ord(c) > ... > 55349 > 56490 > >>> unichr(55349) + unichr(56490) > u'\U0001d4aa' > >>> > > How do I convert strings such as '1D4AA' to unicode without using eval()? Justin, I see you haven't gotten any responses on this yet. I don't know an answer, but I ran into something similar on some of the Unihan characters. Fortunately for me, I found I could just ignore any that were over x'FFFF'; it doesn't sound like you can. I looked into it for a while and determined that it depends on how your Python was built. If it was a "narrow build", it supports Unicode characters only up to x'FFFF'; if a "wide build", it supports Unicode x'10000" and higher, as well. As far as I can tell, it depends on whether the installer specified "--enable-unicode=ucs4" to get the wide build. I'm a Windows user, too, and dependent on the Activestate build, which is narrow. In the end, I decided to just avoid the higher Unicode values, which didn't matter for me. If you have a way of getting a "wide build" I suspect this would do the trick for you. There's more information in PEP 261, http://www.python.org/peps/pep-0261.html : I think this is the last word on it. Hopefully, some others more informed on Python internals and Unicode can give more information on this, but I hope this helps somewhat. -- Terry Carroll Santa Clara, CA carroll@tjc.com From rahulk at bhartitelesoft.com Fri Oct 17 01:51:17 2003 From: rahulk at bhartitelesoft.com (Rahul Kumar) Date: Fri Oct 17 01:34:25 2003 Subject: [Tutor] python_naming_conventions - newbie Message-ID: <20031017055117.GF7414@bhartitelesoft.com> As someone learning python after several years of working on Java, i am interested to know why does python follow the lower_case_with_underscores way of naming methods and variables while Java follows the MixedCaseWithoutUnderscores. After writing a couple of py progs, i find myself using the python way in Java, and i prefer it (used to write C progs this way 10 yrs ago), and i need some justification for this, since i am the guy who made the Java guidelines for my org 4 years back ! -- regards, rahul kumar From fredm at smartypantsco.com Fri Oct 17 03:43:34 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Fri Oct 17 03:46:39 2003 Subject: [Tutor] Printing Chinese characters? Message-ID: <5.1.0.14.0.20031017173840.02a41c20@mail.milgromphoto.com> Hi: Let me start by saying I just love programming in Python. I love its philosophy, its ease of use, the obvious productivity, the third-party support, the code libraries, and so on. (As an aside, I thought list comprehension was pretty great, but now that I have discovered iterators, it's even better:) But just as important as the power of the language, the support given by people on this forum is incredible. So I just want to start off by saying thanks to all of you. As far as my Chinese text string is concerned, the string is part of comments in a Go game problem from a Chinese web site (Go is an ancient oriental board game, also known as weiqi in China and baduk in Korea). My first problem was converting the string into unicode. Now that I have access to the CJK encodings (thanks Danny), I believe that the coding is mainly 'chinese' rather than 'big5'. But there could be some special Japanese Go terms in there as well :(( The first two Chinese characters might be: u'\u9ed1' Black u'\u5408' combine (Translation made using unihan.txt - thanks Neal for pointing me in that direction) This makes sense in the context of the problem and would translate as 'Black to join his groups' (or similar). I haven't figured out what to do with the '?' characters, and haven't decided if they are punctuation of some kind or an escape character or whatever. And I don't know when to check for Japanese characters, either. So I am not sure about the following characters yet. Some characters are definitely not 'chinese' encoding. But now I have enough ammunition to get me going forward. (Terry: When I get enough confidence in my decoding, I will get in touch with you concerning your unihan Python lookup module. Thanks.) As a final aside, I know that many people prefer other editors rather than IDLE, but IDLE can't be beaten in this situation. There is no need for other GUIs, web browsers, etc. Because IDLE is written in Tkinter, it automatically displays unicode characters properly! Thanks again, Fred Milgrom From project5 at redrival.net Fri Oct 17 10:17:41 2003 From: project5 at redrival.net (Andrei) Date: Fri Oct 17 10:19:58 2003 Subject: [Tutor] Re: python_naming_conventions - newbie In-Reply-To: <20031017055117.GF7414@bhartitelesoft.com> References: <20031017055117.GF7414@bhartitelesoft.com> Message-ID: Rahul Kumar wrote: > As someone learning python after several years of working on Java, i am > interested to know why does python follow the > lower_case_with_underscores way of naming methods and variables while > Java follows the MixedCaseWithoutUnderscores. Does it? It's not really true. The conventions for this kind of stuff are in the Style Guide: http://www.python.org/doc/essays/styleguide.html The recommendations for camelCase, MixedCase and under_scores are quite murky IMO, here's a quote: "CapWords style is used for functions that provide major functionality (e.g. nstools.WorldOpen()), while lowercase is used more for "utility" functions". For the one using the module, it's all pretty much guesswork whether the author considered something major or minor functionality. > After writing a couple of py progs, i find myself using the python way > in Java, and i prefer it (used to write C progs this way 10 yrs ago), and > i need some justification for this, since i am the guy who made the Java > guidelines for my org 4 years back ! I use camelCase in method names, MixedCase for classes and objects, UPPERCASE for 'constants' (well, things that are *supposed* to remain constant anyway), lowercase for most variables and normal functions, while avoiding under_scores like the plague :) - I find them very time consuming. In the end, I suppose it's all a matter of taste, as long as it's consistent. When I started programming in Pascal, we were taught to write "BEGIN". When I switched to Delphi, which uses "begin" in all generated code, I found that lowercase stuff quite annoying. Not too long ago I looked at an old Pascal program and found the all-caps impossible to read again :). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From marc_barry at hotmail.com Fri Oct 17 11:54:54 2003 From: marc_barry at hotmail.com (Marc Barry) Date: Fri Oct 17 11:55:00 2003 Subject: [Tutor] Public, private and protected member variables. Message-ID: Dear All: I have a question regarding the existence of protected members in Python. Basically, in a language like Java we have public, private and protected member variables. But in Python I only know of public and private. I would like to inherit from a class and be able to modify parent member variables, but I would not like any class that doesn't inherit from the parent to be able to modify the member variables (i.e. Protected concept in Java). Here is a simple example: #------------------------------------------------------------ class Car: def __init__(self, colour): self.__colour = colour class Ferrari(Car): def __init__(self, model, colour): Car.__init__(self, colour) self.__model = model def printColour(self): print self.__colour a_ferrari = Ferrari("Enzo", "Red") print dir(a_ferrari) a_ferrari.printColour() #------------------------------------------------------------ The output from running this script is: ['_Car__colour', '_Ferrari__model', '__doc__', '__init__', '__module__', 'printColour'] Traceback (most recent call last): File "inheritance.py", line 19, in ? a_ferrari.printColour() File "inheritance.py", line 15, in printColour self.__colour AttributeError: Ferrari instance has no attribute '_Ferrari__colour' As you can see the __colour member variable of Car is not visible in the Ferrari class since it appears that appending '__' on a variable makes it private and not protected. Is there a way to make a variable protected in Python? If I expose a variable in Car as public ,then I will allow users of the class to modify it directly. I would like to avoid this since that fixes my implementation to being always having to provide a variable named "colour" for example. Also, this is just a simplification of my problem as my class is much more complicated with a lot of gettable and settable properties in the parent object (Which I want to inherit). Regards, Marc Barry marc_barry@hotmail.com _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From dyoo at hkn.eecs.berkeley.edu Fri Oct 17 13:22:05 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 17 13:25:34 2003 Subject: [Tutor] Public, private and protected member variables. In-Reply-To: Message-ID: On Fri, 17 Oct 2003, Marc Barry wrote: > I have a question regarding the existence of protected members in > Python. Basically, in a language like Java we have public, private and > protected member variables. Hi Mark, (Tangential note: In some programming languages all member variables are private by default. Objective C is one example.) > Here is a simple example: > > #------------------------------------------------------------ > class Car: > def __init__(self, colour): > self.__colour = colour > > > class Ferrari(Car): > def __init__(self, model, colour): > > Car.__init__(self, colour) > self.__model = model > > def printColour(self): > print self.__colour > > a_ferrari = Ferrari("Enzo", "Red") > print dir(a_ferrari) > a_ferrari.printColour() > But in Python I only know of public and private. I would like to inherit > from a class and be able to modify parent member variables, but I would > not like any class that doesn't inherit from the parent to be able to > modify the member variables (i.e. Protected concept in Java). Python's variable protection is handled by convention, not law. The Python Style essay says that if we want to specify "protected"-style status, we can use a single underscore in the front of the name: http://www.python.org/doc/essays/styleguide.html So the informal way to handle this might be something like this: ### class Car: def __init__(self, colour): self._colour = colour class Ferrari(Car): def __init__(self, model, colour): Car.__init__(self, colour) self.__model = model def printColour(self): print self._colour ### I know this is a toy example, but it might be better to "pull up" the printColour() method into the parent, and avoid the visibility problems altogether: ### class Car: def __init__(self, colour): self.__colour = colour def printColour(self): print self.__colour class Ferrari(Car): def __init__(self, model, colour): Car.__init__(self, colour) self.__model = model ### > If I expose a variable in Car as public, then I will allow users of the > class to modify it directly. I would like to avoid this since that fixes > my implementation to being always having to provide a variable named > "colour" for example. Also, this is just a simplification of my problem > as my class is much more complicated with a lot of gettable and settable > properties in the parent object (Which I want to inherit). If you'd like, please feel free to talk about object design on the Tutor list. It's one of those things I'd like to learn more about myself. *grin* Perhaps it might be possible to avoid exposing so many properties by reworking the design a little? I think we had a recent discussion about this subject, and one thing that came up was Java's influence was making people overdesign their classes to use setFoo/getFoo everywhere. Folks on the list also talked a bit about the variable visibility stuff that you're interested in: http://mail.python.org/pipermail/tutor/2003-October/025599.html Good luck to you! From project5 at redrival.net Fri Oct 17 13:40:07 2003 From: project5 at redrival.net (Andrei) Date: Fri Oct 17 13:42:21 2003 Subject: [Tutor] Re: Public, private and protected member variables. In-Reply-To: References: Message-ID: Marc Barry wrote: > Dear All: > > I have a question regarding the existence of protected members in > Python. Basically, in a language like Java we have public, private and > protected member variables. But in Python I only know of public and > private. I would like to inherit from a class and be able to modify Only in Python private isn't *really* private. Come to think of it, other languages which have public/private/protected have some awkward rules too, e.g. classes declared in the same unit in Delphi don't behave quite as you'd expect them regarding these permissions. > The output from running this script is: > > ['_Car__colour', '_Ferrari__model', '__doc__', '__init__', '__module__', > 'printColour'] > Traceback (most recent call last): > File "inheritance.py", line 19, in ? > a_ferrari.printColour() > File "inheritance.py", line 15, in printColour > self.__colour > AttributeError: Ferrari instance has no attribute '_Ferrari__colour' > > As you can see the __colour member variable of Car is not visible in the > Ferrari class since it appears that appending '__' on a variable makes > it private and not protected. Is there a way to make a variable > protected in Python? Actually, it is visible. The name is mangled to "_Car__colour", that's all that "private" does: name mangling. So it should be ok if you do in printColour "print self._Car__colour" rather than "print self.__colour". Note that in Python you can access the pieces of a class using its __dict__, so you can't do a lot about a really persistent programmer trying to access your private parts - in a programming sense, that is. > If I expose a variable in Car as public ,then I will allow users of the > class to modify it directly. I would like to avoid this since that fixes > my implementation to being always having to provide a variable named > "colour" for example. Also, this is just a simplification of my problem Python doesn't enforce this kind of security. If someone *wants* to access the mangled name (_Car__colour), its name makes it clear it's "private" and they're aware of the risk that it might change. At that point they can choose to be responsible programmers and not use it, or use it anyway and live with the consequences. I like this attitude better than that in "traditional" langauges which enforce private/protected, where programmers then start looking for clever hacks to access that supposedly secret data anyway. > as my class is much more complicated with a lot of gettable and settable > properties in the parent object (Which I want to inherit). I don't know your needs, but perhaps you're trying too hard to turn Python into a language with static typing? When I first started in Python (which is not that long ago), I had a tendency to do manual typechecking along the lines of "if type(x)==type(y):". Turns out that's actually not necessary. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From tim.ronning at start.no Fri Oct 17 18:19:24 2003 From: tim.ronning at start.no (Tim) Date: Fri Oct 17 16:44:51 2003 Subject: [Tutor] Python audio help needed Message-ID: Hello list, and greetings from Norway I'm new to this list and to Python (obviously since I'm asking questions here..) In paralell with learning from books, online training, etc, I have also started my own little project. I want to build a dead simple mp3 player using pymad (libmad) library and PyQt when I get the basics to work. I started out with this little script, supplied by the author to show how to use pymad. #!/usr/bin/env python import mad, ao, sys mf = mad.MadFile(sys.argv[1]) dev = ao.AudioDevice('oss', rate=mf.samplerate()) while 1: buf = mf.read() if buf is None: break dev.play(buf, len(buf)) My first problem, I don't have module ao! Couldn't find on the net so I'm trying to acomplish the same with module ossaudiodev. After some study in the Python docs I now have this script. #!/usr/bin/env python import mad, ossaudiodev, sys mf = mad.MadFile(sys.argv[1]) dev = ossaudiodev.open('/dev/audio0', "w") rate=mf.samplerate() #print rate dev.setfmt(505) dev.channels(2) dev.speed(rate) while 1: buf = mf.read() if buf is None: break dev.write(buf) This actually plays the commandline supplied mp3 file, but! It sound's like something out of a seventees horror movie. It's extremely slow and with a lot of noise. I have a feeling that it has something to do with the setfmt() but I'm not sure. I'm running with ALSA drivers (with OSS support) so in theory it should work, but again I'm not sure. When I run getfmts() the result I'm getting back from the sound device is bitmask 505. The device is a Creative Live! 5.1 (ALSA emu10k1) Can anyone help me out here. Is there an ALSA audio module out there somewhere? Or should I set some other value to setfmt() All help is greatly appriciated. Best regards Tim -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From alan.gauld at blueyonder.co.uk Fri Oct 17 18:25:52 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Oct 17 18:25:23 2003 Subject: [Tutor] Re: python_naming_conventions - newbie References: <20031017055117.GF7414@bhartitelesoft.com> Message-ID: <001901c394fd$9fb74250$6401a8c0@xp> > When I started programming in Pascal, we were taught to write "BEGIN". When I > switched to Delphi, which uses "begin" in all generated code, I found that > lowercase stuff quite annoying. Not too long ago I looked at an old Pascal > program and found the all-caps impossible to read again :). One reason COBOL is so hard to maintain is that it uses all uppercase for everything. Uppercase is much harder for the human brain to comprehend because much of our cognitive system is based on the shape of words not the exact sequence of letters. By using uppercase the shape variation is lost - all words look square. As to the underscore_thing verses mixedCase I use a mixture depending on the name. Some things dont look right(to me) using MixedCase, others are too long using underscores. So far as I know there is no conclusive data favouring one over the other, like many stylistic issues intenal consistency is more important than which one you pick. Alan G. From alan.gauld at blueyonder.co.uk Fri Oct 17 18:45:43 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Oct 17 18:45:15 2003 Subject: [Tutor] Public, private and protected member variables. References: Message-ID: <002001c39500$657d3970$6401a8c0@xp> > I have a question regarding the existence of protected members in Python. We had a longish thread on variable scoping in Python just recently, try searching the archives. > Basically, in a language like Java we have public, private and protected > member variables. Indeed, Java copied the concept from C++ which introduced it in version 2, partly to help manage complexity in the face of multiple inheritance(also introduced in version 2). > But in Python I only know of public and private. And even private can be bypassed fairly easily (as it can in C++!) and in practice public variables are the norm. > inherit from a class and be able to modify parent member variables, > but I would not like any class that doesn't inherit from the parent > to be able to modify the member variables Why? Apart from paranoia born from exposure to languages like C++ and Java(which as I say just played copycat?) OO programmers have been using inheritance for many years without protected scopes (and originally often without private either!) and it very rarely causes problems. If you really do need to hide the variables completely then simply make them private and then provide accessor functions(yuk!) or make them properties(slightly better). The accessor can if you really want to, check the immediate parent of the calling class...if you really want to... But do you habitually find yourself breaking your own design by trying to directly access internal state? Or do you really distrust your fellow programmers that much? And what about the occasions when internal access is actually needed by a non child class? C++ provides the friend construct, should Python do likewise? Its easier to just go with the flow when using a new language. One of the reasons that C++ and Java are so verbose and difficult to use is that they introduce all manner of artificial restictions which programmers have to work around. (And I say that as someone who used C++ almost exclusively from 1988 through to 1996 - then I found Delphi, hooray! Then I found Python, double hooray! And I haven't written any serious C++ since 1999. And I studiously avoid Java as much as possible) Python tries to make the programmers life easy at the expense of expecting a little courtesy to be exercised. > If I expose a variable in Car as public ,then I will allow users of the > class to modify it directly. I would like to avoid this since that fixes my > implementation to being always having to provide a variable named "colour" > for example. If that's your concern you could override setattr and getattr to prevent access to anything that wasn't a method. That way all attributes are private. Then you have to provide accessor functions - is that really any better? Alternatively, in your documentation just tell users not to access the attributes directly. And that doing so may result in undefined behaviour! > is much more complicated with a lot of gettable and settable properties in > the parent object (Which I want to inherit). Yep, that's why lots of gettable/settable properties are a pain. See the previous thread... Sorry but the gettable/settable stuff is one of my hot buttons :-( Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From arkamir at softhome.net Fri Oct 17 20:14:56 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Fri Oct 17 20:15:13 2003 Subject: [Tutor] sorting nested tuples Message-ID: <1066436096.8346.5.camel@quercus> if I have a list x = [('hello', 2), ('goodbye', 3), ('python', 1)] how would i sort it by the 2 variable or any variable for that matter. From dyoo at hkn.eecs.berkeley.edu Fri Oct 17 20:33:15 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Oct 17 20:34:17 2003 Subject: [Tutor] sorting nested tuples [decorate-sort-undecorate] In-Reply-To: <1066436096.8346.5.camel@quercus> Message-ID: On Fri, 17 Oct 2003, Conrad Koziol wrote: > if I have a list > > > x = [('hello', 2), ('goodbye', 3), ('python', 1)] > > how would i sort it by the 2 variable or any variable for that matter. Hi Conrad, A quick way to do it is to "decorate" the list: ### >>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)] >>> for i, e in enumerate(mylist): ... mylist[i] = (e[1], e) ... >>> mylist [(2, ('hello', 2)), (3, ('goodbye', 3)), (1, ('python', 1))] ### And this is something that can now be sorted! ### >>> mylist.sort() >>> mylist [(1, ('python', 1)), (2, ('hello', 2)), (3, ('goodbye', 3))] ### So it's sorted, but it's still decorated. So we need to "undecorate" the list: ### >>> for i, e in enumerate(mylist): ... mylist[i] = e[1] ... >>> mylist [('python', 1), ('hello', 2), ('goodbye', 3)] ### This is the "decorate-sort-undecorate" pattern. We take advantage of Python's native sort() method, and augment/deaugment our structure just enough to make things work nicely. The Perl folks have popularized this technique as the "Schwartzian Transform". If you do a search on that term, you'll can find more examples of this technique. The technique is especially nice on Python because tuples are directly comparable --- and tuples can contain tuples! --- so we don't have anything really ugly to do the decoration. If you'd like to know more, Andrew Dalke Sorting mini-HOWTO tutorial is a good resource: http://www.amk.ca/python/howto/sorting/sorting.html Good luck to you! From j.ezequiel at spitech.com Fri Oct 17 21:22:51 2003 From: j.ezequiel at spitech.com (Ezequiel, Justin) Date: Fri Oct 17 21:23:19 2003 Subject: [Tutor] Re: unichr() question Message-ID: <29E16390A38FD7118A03000BCD0F3F6501316A8A@mail.spiglobe.com> >> > >>> unichr(long('1D4AA', 16)) >> > Traceback (most recent call last): >> > File "", line 1, in ? >> > ValueError: unichr() arg not in range(0x10000) (narrow Python build) >> > >>> x = eval("u'\\U000%s'" % '1D4AA') >> > >>> x >> > u'\U0001d4aa' >> > >>> for c in x: >> > ... print ord(c) >> > ... >> > 55349 >> > 56490 >> > >>> unichr(55349) + unichr(56490) >> > u'\U0001d4aa' >> > How do I convert strings such as '1D4AA' to unicode without using eval()? On Thu, 16 Oct 2003, Terry Carroll wrote: >> If you have a way of getting a "wide build" I >> suspect this would do the trick for you. >> >> There's more information in PEP 261, >> http://www.python.org/peps/pep-0261.html : I think this is the last word >> on it. >> Thanks Terry. I guess I'll just have to live with my eval() workaround. Thanks also for the link to the PEP. Will re-read it to see if I missed anything. From tim at johnsons-web.com Fri Oct 17 23:25:51 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Fri Oct 17 23:22:11 2003 Subject: [Tutor] reference instead of copy Message-ID: <20031018032551.GJ5104@johnsons-web.com> Hello All: I have been using the following function (produced by help from this list (thanks!)) which returns a subset of a list.: def extract (oldlist, spacing,ndx=-1): if ndx > -1: return [oldlist[i][ndx] for i in range (len(oldlist)) if not i%spacing] else: return [oldlist[i] for i in range (len(oldlist)) if not i%spacing] # But let's suppose I wish to operate on this subset and have it # reflected in the original list. I can't do this with the above # configuration. Example below: >>> test = [1,2,3,4,5,6,7,8,9,10] >>> t = mylib.extract(test,2) >>> print t [1, 3, 5, 7, 9] >>> t[1] = 'three' >>> print t [1, 'three', 5, 7, 9] >>> print test [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # What I need for this is and 'extract' function which retains # the original reference so that when I code: t[1] = 'three' # list 'test looks like this: [1, 2, 'three', 4, 5, 6, 7, 8, 9, 10] Any ideas? TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From good_time_bad_time_moofoshi_time_ressurected at hotmail.com Sat Oct 18 02:54:57 2003 From: good_time_bad_time_moofoshi_time_ressurected at hotmail.com (Hiroshi Ransom) Date: Sat Oct 18 02:55:02 2003 Subject: [Tutor] (no subject) Message-ID: hi, im new this is basic u prlly heard this question a MIllion times but what are all the commands usable in the snake program and what do they do? also explain any spacings that must b done between commands. _________________________________________________________________ E-mail just got a whole lot better. New ninemsn Premium. Click here http://ninemsn.com.au/premium/landing.asp From dyoo at hkn.eecs.berkeley.edu Sat Oct 18 03:32:31 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 18 03:35:52 2003 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Sat, 18 Oct 2003, Hiroshi Ransom wrote: > what are all the commands usable in the snake program and what do they > do? Hi Hiroshi, What snake program do you mean? > also explain any spacings that must b done between commands. What kind of spacings do you mean? Do you have a concrete example of commands with spaces in them that you can show us? If it sounds like these questions are a little silly, please forgive me. But I'm just trying to figure out what you are trying to figure out. *grin* > im new this is basic u prlly heard this question a MIllion times but Wwe may have heard similar questions before, but that is actually besides the point. We want to understand better why you're asking those particular ones --- the "why" is much more important to us. Are you trying to learn programming from a tutorial? If so, can you point it out to us? We want to see why you're running into problems. Just in case you're starting from scratch: there's a lot of good beginner tutorials here: http://www.python.org/topics/learn/non-prog.html There's a lot of good tutorials there, and if you go through one, we'll be happy to help answer your questions about them. Good luck! From alan.gauld at blueyonder.co.uk Sat Oct 18 03:44:44 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Oct 18 03:44:09 2003 Subject: [Tutor] (no subject) References: Message-ID: <004901c3954b$b29c9d40$6401a8c0@xp> > im new this is basic u prlly heard this question a MIllion times but what > are all the commands usable in the snake program and what do they do? OK, I'll assume that "the snake program" is Python and not the old snake game? Python is a programming language and just like any other language it has words and a set of rules abouit how to use those words. Once you understand those rules you can combine the words in many different sequences to express ideas. In a programming language instead of expressing ideas we express instructions to the computer to make it do things. The Python program is the mechanism for translating the Python statements that we write into something the computer understands. The best place to find out how to do this is to use one of the tutorials designed for complete beginners on the Python web site, and ask specific questions about them as you go on this mailing list. THe tutorials are found here: http://www.python.org/topics/learn/non-prog.html > explain any spacings that must b done between commands. The tutorials will explain all of that because spacing (or indentation as its called ) is important in Python. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From fredm at smartypantsco.com Sat Oct 18 03:45:00 2003 From: fredm at smartypantsco.com (Alfred Milgrom) Date: Sat Oct 18 03:47:20 2003 Subject: [Tutor] Re: sorting nested tuples Message-ID: <5.1.0.14.0.20031018174158.02a75310@mail.milgromphoto.com> Hi Conrad: >> if I have a list >> x = [('hello', 2), ('goodbye', 3), ('python', 1)] >> how would i sort it by the 2 variable or any variable for that matter. Danny has shown one way to sort the list using [decorate-sort-undecorate]. Here is another way to sort your list, by specifying your own compare function for sort. For example: >>> def compare(a,b): if a[1]>b[1]: return 0 else: return -1 The function 'compare' we have defined will compare tuples based on the second element, returning 0 if true. (Note you could use '>=' depending on how you want the compare to operate). This function is OK for quick and dirty programming, but if you are going to be using it in a more general environment you should also put in some error checking to make sure you have tuples, etc. >>> x = [('hello', 2), ('goodbye', 3), ('python', 1)] >>> x.sort(compare) >>> x [('python', 1), ('hello', 2), ('goodbye', 3)] Personally I prefer this way as it makes my code more readable (especially if I use a better name than 'compare' :) Hope this helps Fred Milgrom From dyoo at hkn.eecs.berkeley.edu Sat Oct 18 04:04:13 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 18 04:04:23 2003 Subject: [Tutor] reference instead of copy In-Reply-To: <20031018032551.GJ5104@johnsons-web.com> Message-ID: On Fri, 17 Oct 2003, Tim Johnson wrote: > I have been using the following function (produced by help from this > list (thanks!)) which returns a subset of a list.: > def extract (oldlist, spacing,ndx=-1): > if ndx > -1: > return [oldlist[i][ndx] for i in range (len(oldlist)) if not i%spacing] > else: > return [oldlist[i] for i in range (len(oldlist)) if not i%spacing] Hi Tim, Do you mind if we take a quick sidetrip? The complexity of the list comprehension is slightly high --- let me see what this looks like with explicit loops: ### def extract (oldlist, spacing,ndx=-1): if ndx > -1: results = [] for i in range(len(oldlist)): if not i % spacing: results.append(oldlist[i][ndx]) else: results = [] for i in range(len(oldlist)): if not i % spacing: results.append(oldlist[i]) return results ### Hmm... There's some common stuff here. Let me rework it a little more. ### def extract (oldlist, spacing,ndx=-1): results = [] for i in range(len(oldlist)): if i % spacing == 0: if ndx > -1: results.append(oldlist[i][ndx]) else: results.append(oldlist[i]) return results ### Does extract() really have to deal with grabbing specific subindices using that 'ndx' value? That's something that I think can be done outside of extract(). If it's ok, we can yank it out violently: ### def extract (oldlist, spacing): results = [] for i in range(len(oldlist)): if i % spacing == 0: results.append(oldlist[i]) return results ### Oh! There's one more simplification we can make if we know a little more about the range function() --- range can actually take in a "skip" third argument. For example: ### >>> range(0, 10, 3) [0, 3, 6, 9] ### If we take advantage of this feature, then that lets us cut out the remainder check: ### def extract (oldlist, spacing): results = [] for i in range(0, len(oldlist), spacing): results.append(oldlist[i]) return results ### We can transform this back to its list-comprehension equivalent: ### def extract(oldlist, spacing): return [oldlist[i] for i in range(0, len(oldlist), spacing)] ### > # But let's suppose I wish to operate on this subset and have it > # reflected in the original list. I can't do this with the above > # configuration. Very true. The reason for this is because of the use of the list comprehension: list comprehnsions generate fresh new lists. For example: ### >>> def makeListCopy(L): ... return [x for x in L] ... >>> pi = [3, 1, 3, 1, 5, 9, 2, 6] >>> pi_copy = makeListCopy(pi) >>> pi [3, 1, 3, 1, 5, 9, 2, 6] >>> pi_copy [3, 1, 3, 1, 5, 9, 2, 6] ### Although they look the same now, they're only clones at birth. ### >>> del pi[2:] >>> pi_copy[2] = 4 >>> >>> pi [3, 1] >>> >>> pi_copy [3, 1, 4, 1, 5, 9, 2, 6] ### > # What I need for this is and 'extract' function which retains > # the original reference so that when I code: > t[1] = 'three' > # list 'test looks like this: > [1, 2, 'three', 4, 5, 6, 7, 8, 9, 10] Trying to do this with list comprehensions probably won't work: list comprehensions are spiritually designed NOT to modify the original list. *grin* Instead, you may want do direct manipulations --- like indicing and del --- instead, and you should have better results. In your original code, though, you did something like: ### >>> test = [1,2,3,4,5,6,7,8,9,10] >>> t = mylib.extract(test,2) >>> print t ### How about reassigning to 'test'? Good luck! From dyoo at hkn.eecs.berkeley.edu Sat Oct 18 04:09:59 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Oct 18 04:10:19 2003 Subject: [Tutor] Re: sorting nested tuples In-Reply-To: <5.1.0.14.0.20031018174158.02a75310@mail.milgromphoto.com> Message-ID: On Sat, 18 Oct 2003, Alfred Milgrom wrote: > Danny has shown one way to sort the list using [decorate-sort-undecorate]. > Here is another way to sort your list, by specifying your own compare > function for sort. > > For example: > >>> def compare(a,b): > if a[1]>b[1]: return 0 > else: return -1 > > The function 'compare' we have defined will compare tuples based on the > second element, returning 0 if true. (Note you could use '>=' depending > on how you want the compare to operate). By the way, we can say this another way by taking advantage of the built-in cmp() comparison function: ### def compare(a, b): return cmp(a[1], b[1]) ### > Personally I prefer this way as it makes my code more readable > (especially if I use a better name than 'compare' :) How about compare_second_component()? *grin* Talk to you later! From yduppen at xs4all.nl Sat Oct 18 08:23:30 2003 From: yduppen at xs4all.nl (Yigal Duppen) Date: Sat Oct 18 08:29:29 2003 Subject: [Tutor] sorting nested tuples In-Reply-To: <1066436096.8346.5.camel@quercus> References: <1066436096.8346.5.camel@quercus> Message-ID: <200310181423.32558.yduppen@xs4all.nl> > x = [('hello', 2), ('goodbye', 3), ('python', 1)] > > how would i sort it by the 2 variable or any variable for that matter. Hi Conrad, Apart from the decorate-sort-undecorate pattern described by Danny, you can also pass a comparator function to the sort method of a list. First, define a comparator that compares on the second element of a tuple: >>> def cmpOnSecond(t1, t2): ... return cmp(t1[1], t2[1]) And the use that function: >>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)] >>> mylist.sort(cmpOnSecond) >>> mylist [('python', 1), ('hello', 2), ('goodbye', 3)] If you're more into anonymous functions, this works too: >>> mylist = [('hello', 2), ('goodbye', 3), ('python', 1)] >>> mylist.sort(lambda t1,t2: cmp(t1[1], t2[1])) >>> mylist [('python', 1), ('hello', 2), ('goodbye', 3)] For simple cases like this, I prefer the comparator function above the decorate-sort-undecorate approach. YDD -- http://www.xs4all.nl/~yduppen From klappnase at freenet.de Sat Oct 18 09:08:47 2003 From: klappnase at freenet.de (Michael Lange) Date: Sat Oct 18 09:14:13 2003 Subject: [Tutor] Python audio help needed In-Reply-To: References: Message-ID: <20031018150847.32470041.klappnase@freenet.de> On Sat, 18 Oct 2003 00:19:24 +0200 Tim wrote: > Hello list, and greetings from Norway > > I'm new to this list and to Python (obviously since I'm asking questions > here..) > > In paralell with learning from books, online training, etc, I have also > started my own little project. I want to build a dead simple mp3 player > using pymad (libmad) library and PyQt when I get the basics to work. > ... > > Can anyone help me out here. Is there an ALSA audio module out there > somewhere? Or should I set some other value to setfmt() All help is greatly > appriciated. > > Best regards > Tim Hi Tim, maybe you should try tkSnack : www.speech.kth.se/snack Snack supports both OSS and ALSA (however, when I tried to compile the sources with "--enable-alsa" option it did NOT work, but compiling without I have no problems using ALSA). Snack's usage is quite simple and file formats are recognized automatically by the filename extension, so it is fairly easy to play mp3 files: import tkSnack s = tkSnack.Sound(file='somefile.mp3') s.play() This way you can even play large files(bigger than system memory. I hope this helps. Cheers Michael From missive at hotmail.com Sat Oct 18 09:24:45 2003 From: missive at hotmail.com (Lee Harr) Date: Sat Oct 18 09:24:49 2003 Subject: [Tutor] Re: Python audio help needed Message-ID: >In paralell with learning from books, online training, etc, I have also >started my own little project. I want to build a dead simple mp3 player >using pymad (libmad) library and PyQt when I get the basics to work. > >I started out with this little script, supplied by the author to show how >to use pymad. > >#!/usr/bin/env python >import mad, ao, sys >mf = mad.MadFile(sys.argv[1]) >dev = ao.AudioDevice('oss', rate=mf.samplerate()) >while 1: > buf = mf.read() > if buf is None: > break > dev.play(buf, len(buf)) > >My first problem, I don't have module ao! Couldn't find on the net so I'm >trying to acomplish the same with module ossaudiodev. After some study in >the Python docs I now have this script. > http://www.google.com/search?q=python+audio+ao http://www.freshports.org/audio/py-ao/ http://www.andrewchatham.com/pyogg/ _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From raymond.hettinger at verizon.net Sat Oct 18 10:45:30 2003 From: raymond.hettinger at verizon.net (Raymond Hettinger) Date: Sat Oct 18 10:46:17 2003 Subject: [Tutor] Merge Challenge Message-ID: <000001c39586$7aecc740$e841fea9@oemcomputer> Given two sorted lists, a and b, write the fastest, code that merges a and b into a new list c. My answer has 15 characters including newlines. Raymond Hettinger -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031018/005eecb8/attachment.html From erikprice at mac.com Sat Oct 18 11:17:26 2003 From: erikprice at mac.com (Erik Price) Date: Sat Oct 18 10:55:10 2003 Subject: [Tutor] python_naming_conventions - newbie In-Reply-To: <20031017055117.GF7414@bhartitelesoft.com> Message-ID: <2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com> On Friday, October 17, 2003, at 01:51 AM, Rahul Kumar wrote: > As someone learning python after several years of working on Java, i am > interested to know why does python follow the > lower_case_with_underscores way of naming methods and variables while > Java follows the MixedCaseWithoutUnderscores. I don't know the answer why, but one of the more important suggestions made by both "Java Elements of Style" and IIRC the Python Style Guidelines is that convention is more important than aesthetics. That is to say, while aesthetics certainly play a role (even in the very choice of a name for a variable), what is more important is to make sure that your naming is consistent with what is conventional for your project. Java happens to have a well-known published style guide that strongly recommends that camelCase be used for variable names and UNDERSCORE_SEPARATORS only be used in [capitalized] constant declarations (static final String FOO). That said, my guess is that the reason why it was originally selected is probably because the extra underscores make the variable names wider. This isn't as much an issue in Python because type and access declarations aren't used, but because you need to declare the access level and type/return type in Java, it ends up making your code lines wider. Just yesterday I wrote this method signature: private Mip mipFromFile(File mipFile) whereas in Python, it could have simply been declared as: def mip_from_file(mip_file): As you can see, the Python version is still shorter even though I've used the underscores as separators. > After writing a couple of py progs, i find myself using the python way > in Java, and i prefer it (used to write C progs this way 10 yrs ago), > and > i need some justification for this, since i am the guy who made the > Java > guidelines for my org 4 years back ! In Python I don't really stick to one or the other, but try to go with what seems most logical for the situation. However, in Java my own preference is to simply stick to the official standard simply because when others read my code, that's probably what they'll expect to see. Erik From tim at johnsons-web.com Sat Oct 18 12:37:28 2003 From: tim at johnsons-web.com (Tim Johnson) Date: Sat Oct 18 12:33:49 2003 Subject: [Tutor] reference instead of copy In-Reply-To: References: <20031018032551.GJ5104@johnsons-web.com> Message-ID: <20031018163728.GM5104@johnsons-web.com> * Danny Yoo [031018 00:10]: Mornin' Danny: As usual, you are chock full of good info. Coming from a "C" background 'way' back, I would be able to copy a subset of an array of pointers, work on the data that they referenced and have it reflected in the original. Haha! But we're not supposed to talk about pointers here. Rebol's own 'extract' has the same behavior. Can you point me to some docs or discussions on the more advanced use of slicing and indexing, if you can think of any? Thanks! (and as soon as I'm done with my coffee, I'm going to start thinking of 'range' as generating object with the indices I want) there's a solution there, I can just start to see it) cheers tim > > On Fri, 17 Oct 2003, Tim Johnson wrote: > > > I have been using the following function (produced by help from this > > list (thanks!)) which returns a subset of a list.: > > > def extract (oldlist, spacing,ndx=-1): > > if ndx > -1: > > return [oldlist[i][ndx] for i in range (len(oldlist)) if not i%spacing] > > else: > > return [oldlist[i] for i in range (len(oldlist)) if not i%spacing] > > > Hi Tim, > > > Do you mind if we take a quick sidetrip? The complexity of the list > comprehension is slightly high --- let me see what this looks like with > explicit loops: > > ### > def extract (oldlist, spacing,ndx=-1): > if ndx > -1: > results = [] > for i in range(len(oldlist)): > if not i % spacing: > results.append(oldlist[i][ndx]) > else: > results = [] > for i in range(len(oldlist)): > if not i % spacing: > results.append(oldlist[i]) > return results > ### > > > > Hmm... There's some common stuff here. Let me rework it a little more. > > ### > def extract (oldlist, spacing,ndx=-1): > results = [] > for i in range(len(oldlist)): > if i % spacing == 0: > if ndx > -1: > results.append(oldlist[i][ndx]) > else: > results.append(oldlist[i]) > return results > ### > > > Does extract() really have to deal with grabbing specific subindices using > that 'ndx' value? That's something that I think can be done outside of > extract(). If it's ok, we can yank it out violently: > > ### > def extract (oldlist, spacing): > results = [] > for i in range(len(oldlist)): > if i % spacing == 0: > results.append(oldlist[i]) > return results > ### > > > Oh! There's one more simplification we can make if we know a little more > about the range function() --- range can actually take in a "skip" third > argument. For example: > > ### > >>> range(0, 10, 3) > [0, 3, 6, 9] > ### > > > If we take advantage of this feature, then that lets us cut out the > remainder check: > > ### > def extract (oldlist, spacing): > results = [] > for i in range(0, len(oldlist), spacing): > results.append(oldlist[i]) > return results > ### > > > We can transform this back to its list-comprehension equivalent: > > ### > def extract(oldlist, spacing): > return [oldlist[i] for i in range(0, len(oldlist), spacing)] > ### > > > > # But let's suppose I wish to operate on this subset and have it > > # reflected in the original list. I can't do this with the above > > # configuration. > > > Very true. The reason for this is because of the use of the list > comprehension: list comprehnsions generate fresh new lists. For example: > > ### > >>> def makeListCopy(L): > ... return [x for x in L] > ... > >>> pi = [3, 1, 3, 1, 5, 9, 2, 6] > >>> pi_copy = makeListCopy(pi) > >>> pi > [3, 1, 3, 1, 5, 9, 2, 6] > >>> pi_copy > [3, 1, 3, 1, 5, 9, 2, 6] > ### > > > Although they look the same now, they're only clones at birth. > > ### > >>> del pi[2:] > >>> pi_copy[2] = 4 > >>> > >>> pi > [3, 1] > >>> > >>> pi_copy > [3, 1, 4, 1, 5, 9, 2, 6] > ### > > > > > # What I need for this is and 'extract' function which retains > > # the original reference so that when I code: > > t[1] = 'three' > > # list 'test looks like this: > > [1, 2, 'three', 4, 5, 6, 7, 8, 9, 10] > > Trying to do this with list comprehensions probably won't work: list > comprehensions are spiritually designed NOT to modify the original list. > *grin* > > Instead, you may want do direct manipulations --- like indicing and del > --- instead, and you should have better results. In your original code, > though, you did something like: > > ### > >>> test = [1,2,3,4,5,6,7,8,9,10] > >>> t = mylib.extract(test,2) > >>> print t > ### > > How about reassigning to 'test'? > > > > Good luck! -- Tim Johnson http://www.alaska-internet-solutions.com From glingl at aon.at Sat Oct 18 13:54:44 2003 From: glingl at aon.at (Gregor Lingl) Date: Sat Oct 18 13:56:39 2003 Subject: [Tutor] Merge Challenge In-Reply-To: <000001c39586$7aecc740$e841fea9@oemcomputer> References: <000001c39586$7aecc740$e841fea9@oemcomputer> Message-ID: <3F917E64.2060807@aon.at> Hello Raymond! I'm very courious about your solution. I tried c=a+b c.sort() and that is indeed very fast. (Trying for half an hour I couldn't find *any* faster one). Will be hard to surpass. Regards, Gregor Raymond Hettinger schrieb: > Given two sorted lists, a and b, write the fastest, > > code that merges a and b into a new list c. > > > > My answer has 15 characters including newlines. > > > > > > Raymond Hettinger > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From jim_938 at hotmail.com Sat Oct 18 14:58:47 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Sat Oct 18 14:58:51 2003 Subject: [Tutor] long-to-string Message-ID: Hello, First of all thanks to tutor for providing their support. People on this list are really helpful. Now I would like to discuss something about my problem:: i have written a module to covert a 4 byte string into a long like this: >>>def makelong(chaine): ... # Make a long form a 4-byte string ... return ((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+ord(chaine[3]) ... >>># Now call the function we just defined: ... makelong('oMAP') 1867333968 I packs this data with struct module using '>L' format I am able to unpack this and get the no from my file Now i want is to convert the no back into the string like 'oXYZ' for which this no was meant. I would welcome your suggestions on how should i move ahead. Thanks in advance. With best regards, J+ _________________________________________________________________ MSN Hotmail now on your Mobile phone. http://server1.msn.co.in/sp03/mobilesms/ Click here. From python at rcn.com Sat Oct 18 15:06:47 2003 From: python at rcn.com (Raymond Hettinger) Date: Sat Oct 18 15:07:33 2003 Subject: [Tutor] Merge Challenge In-Reply-To: <3F917E64.2060807@aon.at> Message-ID: <003301c395aa$fad8d880$e841fea9@oemcomputer> [Gregor] > I'm very courious about your solution. > I tried > > c=a+b > c.sort() > > and that is indeed very fast. (Trying for half an > hour I couldn't find *any* faster one). > Will be hard to surpass. That's the winning solution. Tim Peter's amazing new sort routine discovers the two sorted subsequences and merges them in a tight C coded loop at O(n) runtime. For almost any other implementation of sort, the above solution would run at a much slower O(n log n) speed and would be beat by even badly coded pure python solutions running at O(n). In case you can't tell, I'm very impressed with Tim's sort code. Raymond Hettinger From jk_ksu at budweiser.com Sat Oct 18 16:17:39 2003 From: jk_ksu at budweiser.com (jeremy kearns) Date: Sat Oct 18 16:17:42 2003 Subject: [Tutor] Regarding loops Message-ID: <20031018201739.7231.qmail@machiavelli.synacor.com> import random # create a sequence WORDS = ("python","jumble",) # pick a random word word = random.choice(WORDS) # create variable to use later to see if guess is correct correct = word # jumble creation part # ------------------------------- # create an empty jumble word # while the chosen word has letters in it # extract a random letter from the chosen word # add the random letter to the jumble word # jumbled version of the word jumble = " " while word: position = random.randrange(len(word)) jumble += word[position] word = word[:position] + word[(position + 1):] # start print \ """ Welcome to the word jumble! Unscramble the letters to make a word. (press the enter key at prompt to exit) """ # PROBLEM AREA print "The jumble is:", jumble guess = raw_input("\nYour guess: ") guess = guess.lower() while (guess != correct) and (guess != ""): if guess != correct and correct == "python": print "Do you want a hint?" userHint1 = int(raw_input("1 for True or 0 for False: ")) if userHint1 == True: print "What program is associated with python.org? " else: print "You guessed wrong, maybe take a hint next time." if guess != correct and correct == "jumble": print "Do you want a hint?" userHint1 = int(raw_input("1 for True or 0 for False: ")) if userHint1 == True: print " " else: print "You guessed wrong, maybe take a hint next time." # I can't get the loops to function properly here. # The loops override each other. # Can you please point out what is wrong with this? if guess == correct: print "That's it! You guessed it!\n" print "Thanks for playing." raw_input("\nPress enter to exit the program.") -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20031018/4d73cef9/attachment.html From intatia at paradise.net.nz Sat Oct 18 21:33:04 2003 From: intatia at paradise.net.nz (Intatia) Date: Sat Oct 18 21:33:30 2003 Subject: [Tutor] Merge Challenge In-Reply-To: <003301c395aa$fad8d880$e841fea9@oemcomputer> References: <003301c395aa$fad8d880$e841fea9@oemcomputer> Message-ID: <3F91E9D0.1070609@paradise.net.nz> Raymond Hettinger wrote: > [Gregor] > >>I'm very courious about your solution. >>I tried >> >>c=a+b >>c.sort() >> >>and that is indeed very fast. (Trying for half an >>hour I couldn't find *any* faster one). >>Will be hard to surpass. > > > That's the winning solution. So that's the best way to do it... *bangs head on desk* > Tim Peter's amazing new sort routine discovers > the two sorted subsequences and merges them in > a tight C coded loop at O(n) runtime. > > For almost any other implementation of sort, the > above solution would run at a much slower O(n log n) > speed and would be beat by even badly coded pure > python solutions running at O(n). > > In case you can't tell, I'm very impressed with > Tim's sort code. > > > > Raymond Hettinger > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From glingl at aon.at Sun Oct 19 05:31:42 2003 From: glingl at aon.at (Gregor Lingl) Date: Sun Oct 19 05:33:34 2003 Subject: [Tutor] Regarding loops In-Reply-To: <20031018201739.7231.qmail@machiavelli.synacor.com> References: <20031018201739.7231.qmail@machiavelli.synacor.com> Message-ID: <3F9259FE.8030206@aon.at> jeremy kearns schrieb: ... > Welcome to the word jumble! > ... > # PROBLEM AREA > > print "The jumble is:", jumble > > guess = raw_input("\nYour guess: ") > guess = guess.lower() > while (guess != correct) and (guess != ""): > if guess != correct and correct == "python": > print "Do you want a hint?" > userHint1 = int(raw_input("1 for True or 0 for False: ")) > if userHint1 == True: > print "What program is associated with python.org? " > else: > print "You guessed wrong, maybe take a hint next time." > > if guess != correct and correct == "jumble": > print "Do you want a hint?" > userHint1 = int(raw_input("1 for True or 0 for False: ")) > if userHint1 == True: > print " " > else: > print "You guessed wrong, maybe take a hint next time." > > # I can't get the loops to function properly here. > # The loops override each other. > # Can you please point out what is wrong with this? Hi Jeremy! I think you expect this loop to terminate, if the user guessed right. But in your code the user has only one possibility to give an input for the guess. That is before entering the loop. In the body of the loop there is no assignment of a new value to guess. To give the user the opportunity to input a new guess, you should add an appropriate raw_input() call to the body of the loop. moeover I observed that yuo loop consist of two parts, that are almost equal. There is only one line which is different: that printing the hint. Perhaps you could find a way to make your code more compact by putting only this line, depending on the value of correct in (one or two) appropriate if statement(s)? Hope this helps? Gregor > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From karld at ugcs.caltech.edu Sun Oct 19 15:16:37 2003 From: karld at ugcs.caltech.edu (karl d'adamo) Date: Sun Oct 19 15:16:43 2003 Subject: [Tutor] Introduction and ? re: searching the list's archives In-Reply-To: <001801c385d8$39570420$797ba8c0@rclilly.com> References: <001801c385d8$39570420$797ba8c0@rclilly.com> Message-ID: <20031019191637.GA6578@ugcs.caltech.edu> On Sun, Sep 28, 2003 at 08:50:21AM -0700, Robert Lilly wrote: > Hello everyone, > I know that many of the questions I will want to ask have probably already > been discussed. So I've downloaded the mbox archive so that I may search > through it before asking a question. However, I'm not sure what an efficient > means for searching it may be. Does anyone have any recommendations on how > to go about searching an mbox archive? I am working primarily under Windows > 2000, but I have Cygwin installed, so a *nix solution may be viable as well. > post is off-topic. how about mutt. it should come with a full distribution of cygwin. it will likely take a few minutes to load a very large mbox, but you get powerful searches like: show me all posts with a subject containing "dictionary", a body containing "hashable", that have been replied to and are PGP signed from 10/1/01 to 11/1/01 ~s dictionary ~b hashable ~Q ~g ~d 1/10/01-1/11/01 see here for a full description of mutt patterns: http://mutt.org/doc/manual/manual-4.html#ss4.2 to run it on your file, just type: mutt -f for messages it finds, you will see them in a nice threaded format. if you have multiple mboxes to search there is a nice program that can search gzipped, bzip2ed mboxes, maildirs by date and regexes within headers and/or body. it also includes a wrapper for mutt or pine called grepmail: http://grepmail.sourceforge.net/ wow, i am replying almost a month too late. From rahulk at bhartitelesoft.com Mon Oct 20 01:32:04 2003 From: rahulk at bhartitelesoft.com (Rahul Kumar) Date: Mon Oct 20 01:14:25 2003 Subject: [Tutor] python_naming_conventions - newbie In-Reply-To: <2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com> References: <20031017055117.GF7414@bhartitelesoft.com> <2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com> Message-ID: <20031020053204.GA7016@bhartitelesoft.com> Interestingly, while going through the code of TwistedMatrix I find that they use the camelCase. I wonder what Bruce Eckel uses (the Thinking in Java guy who has moved to Python). I completely agree about consistency over ethics, but just wanted to know how the decision was made in the first place. Thanks for your answers. On Sat, Oct 18, 2003 at 11:17:26AM -0400, Erik Price wrote: > Date: Sat, 18 Oct 2003 11:17:26 -0400 > Subject: Re: [Tutor] python_naming_conventions - newbie > Cc: tutor@python.org > To: Rahul Kumar > From: Erik Price > X-Mailer: Apple Mail (2.552) > > > On Friday, October 17, 2003, at 01:51 AM, Rahul Kumar wrote: > > >As someone learning python after several years of working on Java, i am > >interested to know why does python follow the > >lower_case_with_underscores way of naming methods and variables while > >Java follows the MixedCaseWithoutUnderscores. > > I don't know the answer why, but one of the more important suggestions > made by both "Java Elements of Style" and IIRC the Python Style > Guidelines is that convention is more important than aesthetics. That > is to say, while aesthetics certainly play a role (even in the very > choice of a name for a variable), what is more important is to make > sure that your naming is consistent with what is conventional for your > project. Java happens to have a well-known published style guide that > strongly recommends that camelCase be used for variable names and > UNDERSCORE_SEPARATORS only be used in [capitalized] constant > declarations (static final String FOO). > > That said, my guess is that the reason why it was originally selected > is probably because the extra underscores make the variable names > wider. This isn't as much an issue in Python because type and access > declarations aren't used, but because you need to declare the access > level and type/return type in Java, it ends up making your code lines > wider. Just yesterday I wrote this method signature: > > private Mip mipFromFile(File mipFile) > > whereas in Python, it could have simply been declared as: > > def mip_from_file(mip_file): > > As you can see, the Python version is still shorter even though I've > used the underscores as separators. > > >After writing a couple of py progs, i find myself using the python way > >in Java, and i prefer it (used to write C progs this way 10 yrs ago), > >and > >i need some justification for this, since i am the guy who made the > >Java > >guidelines for my org 4 years back ! > > In Python I don't really stick to one or the other, but try to go with > what seems most logical for the situation. However, in Java my own > preference is to simply stick to the official standard simply because > when others read my code, that's probably what they'll expect to see. > > > Erik > -- Regards, Rahul Kumar | Fax: 6817557, 5770 Bharti Telesoft Intl Pvt Ltd | Tel: 6819330,31,32,34,36 X:231 F-89/6 Okhla Indl Area Phase 1, New Delhi | 8611508-14,16,17 Java everywhere! From idiot1 at netzero.net Mon Oct 20 01:21:07 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Mon Oct 20 01:21:05 2003 Subject: [Tutor] python_naming_conventions - newbie In-Reply-To: <20031020053204.GA7016@bhartitelesoft.com> References: <20031017055117.GF7414@bhartitelesoft.com> <2E8D0FAA-017E-11D8-81B0-00039351FE6A@mac.com> <20031020053204.GA7016@bhartitelesoft.com> Message-ID: <3F9370C3.7070106@netzero.net> Intresting. I wonder if the Matrix is a wikiwiki? Rahul Kumar wrote: > Interestingly, while going through the code of TwistedMatrix I find that > they use the camelCase. I wonder what Bruce Eckel uses (the Thinking in > Java guy who has moved to Python). > I completely agree about consistency over ethics, but just wanted to > know how the decision was made in the first place. > Thanks for your answers. > > On Sat, Oct 18, 2003 at 11:17:26AM -0400, Erik Price wrote: > >>Date: Sat, 18 Oct 2003 11:17:26 -0400 >>Subject: Re: [Tutor] python_naming_conventions - newbie >>Cc: tutor@python.org >>To: Rahul Kumar >>From: Erik Price >>X-Mailer: Apple Mail (2.552) >> >> >>On Friday, October 17, 2003, at 01:51 AM, Rahul Kumar wrote: >> >> >>>As someone learning python after several years of working on Java, i am >>>interested to know why does python follow the >>>lower_case_with_underscores way of naming methods and variables while >>>Java follows the MixedCaseWithoutUnderscores. >> >>I don't know the answer why, but one of the more important suggestions >>made by both "Java Elements of Style" and IIRC the Python Style >>Guidelines is that convention is more important than aesthetics. That >>is to say, while aesthetics certainly play a role (even in the very >>choice of a name for a variable), what is more important is to make >>sure that your naming is consistent with what is conventional for your >>project. Java happens to have a well-known published style guide that >>strongly recommends that camelCase be used for variable names and >>UNDERSCORE_SEPARATORS only be used in [capitalized] constant >>declarations (static final String FOO). >> >>That said, my guess is that the reason why it was originally selected >>is probably because the extra underscores make the variable names >>wider. This isn't as much an issue in Python because type and access >>declarations aren't used, but because you need to declare the access >>level and type/return type in Java, it ends up making your code lines >>wider. Just yesterday I wrote this method signature: >> >> private Mip mipFromFile(File mipFile) >> >>whereas in Python, it could have simply been declared as: >> >> def mip_from_file(mip_file): >> >>As you can see, the Python version is still shorter even though I've >>used the underscores as separators. >> >> >>>After writing a couple of py progs, i find myself using the python way >>>in Java, and i prefer it (used to write C progs this way 10 yrs ago), >>>and >>>i need some justification for this, since i am the guy who made the >>>Java >>>guidelines for my org 4 years back ! >> >>In Python I don't really stick to one or the other, but try to go with >>what seems most logical for the situation. However, in Java my own >>preference is to simply stick to the official standard simply because >>when others read my code, that's probably what they'll expect to see. >> >> >>Erik >> > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From xenacat3 at hotmail.com Mon Oct 20 10:14:29 2003 From: xenacat3 at hotmail.com (Lisa Sullivan) Date: Mon Oct 20 10:14:38 2003 Subject: [Tutor] Help understanding code Message-ID: I am new to programming and I'm trying to teach myself Python via online tutorials. I am struggling with functions. I wonder if someone could help me. Here is the URL for the program I am trying to understand: http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 I have worked through the program and I understand all but one line. Below is an edited version of my notes while I was working through understanding the program. Let me know if I should post the program as well. if get_questions(questions[index]): I don't understand this line. It seems to move through the list stored in (questions) and determine whether or not to increase right by 1. Right should only be increased if the question was answered right, so: That must be what the return statements in the check_question function are for. It replaces the words get_questions with the value returned from running get_questions. We set the variable true to equal 1 and the variable false to = 0. if get_questions(questions[index]): now could say if 1(questions[index]): or if 0(questions)[index]: (questions) refers to the get_questions info sent to the run_test function that we are now inside of. and [index] refers to an entry in this list. But which one? Is index used to get the index variable we set above? If so, then right will only be increased: if 0 or 1(questions[current question] In other words if the current question is answered correctly or incorrectly. This doesn't make sense to me. I don't understand how the program is progressing through the questions. I don't see how it knows to skip the answers. I know it has something to do with the fact that the questions and answers are stored in lists that are inside of the main list. I hope I'm not too far off here. Thanks for your help. Lisa _________________________________________________________________ Add MSN 8 Internet Software to your current Internet access and enjoy patented spam control and more. Get two months FREE! http://join.msn.com/?page=dept/byoa From zach at zcsmith.com Mon Oct 20 11:07:34 2003 From: zach at zcsmith.com (Zach Smith (Linux)) Date: Mon Oct 20 11:07:52 2003 Subject: [Tutor] Help understanding code In-Reply-To: References: Message-ID: <3F93FA36.2030804@zcsmith.com> Lisa Sullivan wrote: > I am new to programming and I'm trying to teach myself Python via > online tutorials. I am > > struggling with functions. I wonder if someone could help me. > Here is the URL for the program I am trying to understand: > http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 > > I have worked through the program and I understand all but one line. > Below is an edited version > > of my notes while I was working through understanding the program. > Let me know if I should post the program as well. > > if get_questions(questions[index]): > I don't understand this line. > It seems to move through the list stored in (questions) and determine > whether or not to increase > If I'm understanding you right, you don't know why this performs what it does. Any "if" statement reverts to true (asks if it is true). In other words, it automatically implies true unless specifically stated otherwise. Think of the line looking like this: if get_questions(questions[index])=true then: run these statements/instructions Like I said, there is an automatic implementation of true unless written otherwise, such as: if get_questions(questions[index])=false then: run these statements/instructions Hope this helps. Zach From project5 at redrival.net Mon Oct 20 11:11:43 2003 From: project5 at redrival.net (Andrei) Date: Mon Oct 20 11:14:04 2003 Subject: [Tutor] Re: Help understanding code In-Reply-To: References: Message-ID: Lisa Sullivan wrote: > I am new to programming and I'm trying to teach myself Python via online > tutorials. I am > struggling with functions. I wonder if someone could help me. Functions are just chunks of code which have a name and may return a result. > Here is the URL for the program I am trying to understand: > http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 > if get_questions(questions[index]): > I don't understand this line. > It seems to move through the list stored in (questions) and determine > whether or not to increase > right by 1. check_question asks the question, records the answer and compares the given answer to the correct one: if answer==given_answer. If the answer is correct, the function returns True (that snippet is old, in recent Python versions you should just use True and False, there's no need to define your own true/false). If the answer is incorrect it returns a False. In run_test, "if check_question(question[index])" is then basically evaluated as "if the value returned by check_question is True, do the thing below". In other words, if check_question returns a value which is evaluated as True in a boolean sense (most things are True except for 0, "", and other empty things), "right" is increased. If check_question returns a false, it does nothing. > Right should only be increased if the question was answered right, so: > That must be what the return statements in the check_question function > are for. return statements stop the execution of the function and return whatever comes after them on the same line. check_question returns true (1) if the given answer is the same as the correct answer and false (0) otherwise. > It replaces the words get_questions with the value returned from running > get_questions. Yep. > Is index used to get the index variable we set above? index *is* the index variable set above. > If so, then right will only be increased: > if 0 or 1(questions[current question] I don't understand this notation. It must be wrong, there is no "or" in its interpretation. > In other words if the current question is answered correctly or > incorrectly. Nope, see my explanation above. > This doesn't make sense to me. > I don't understand how the program is progressing through the questions. > I don't see how it knows to skip the answers. It doesn't skip the answers. It passes to check_question a list which looks like this: ["somequestion", "correctanswer"] ^-- index 0 ^-- index 1 In check_question, this is split into a question part and an answer part: question = question_and_answer[0] # becomes "somequestion" answer = question_and_answer[1] # becomes "correctanswer" > I know it has something to do with the fact that the questions and > answers are stored in lists > that are inside of the main list. Yep. The main list contains 3 question-answer lists. The while loop in run_test accesses these items one by one, by increasing the index it's looking at the end of each loop. During each loop the question-answer list at the current index is passed to check_question and evaluated. Yours, Andrei From idiot1 at netzero.net Mon Oct 20 11:33:07 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Mon Oct 20 11:33:02 2003 Subject: [Tutor] Help understanding code In-Reply-To: References: Message-ID: <3F940033.7070406@netzero.net> OK, how about this? def square(x): # define the square function return x * x # return the value of multiplying x by itself now in the definition X is an arguement passed to the function when you invoke it. For instance: side=input('What is the sidelength of your square?') area=square(side) print 'The surface area of your square courtyard is ', x, 'units.' notice that I passed a variable called 'side', NOT 'x'. However, in it's operation it used a variable named x, and that variable was local- noplace else in the program could access it. Any help as a beginning? Lisa Sullivan wrote: > I am new to programming and I'm trying to teach myself Python via online > tutorials. I am > > struggling with functions. I wonder if someone could help me. > Here is the URL for the program I am trying to understand: > http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html#SECTION001030000000000000000 > > I have worked through the program and I understand all but one line. > Below is an edited version > > of my notes while I was working through understanding the program. > Let me know if I should post the program as well. > > if get_questions(questions[index]): > I don't understand this line. > It seems to move through the list stored in (questions) and determine > whether or not to increase > > right by 1. > > Right should only be increased if the question was answered right, so: > That must be what the return statements in the check_question function > are for. > It replaces the words get_questions with the value returned from running > get_questions. > We set the variable true to equal 1 and the variable false to = 0. > if get_questions(questions[index]): > now could say > if 1(questions[index]): > or > if 0(questions)[index]: > > (questions) refers to the get_questions info sent to the run_test > function that we are now inside > > of. > and [index] refers to an entry in this list. But which one? > Is index used to get the index variable we set above? > If so, then right will only be increased: > if 0 or 1(questions[current question] > In other words if the current question is answered correctly or > incorrectly. > This doesn't make sense to me. > I don't understand how the program is progressing through the questions. > I don't see how it knows to skip the answers. > I know it has something to do with the fact that the questions and > answers are stored in lists > > that are inside of the main list. > > I hope I'm not too far off here. > Thanks for your help. > Lisa > > _________________________________________________________________ > Add MSN 8 Internet Software to your current Internet access and enjoy > patented spam control and more. Get two months FREE! > http://join.msn.com/?page=dept/byoa > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From jim_938 at hotmail.com Mon Oct 20 14:41:16 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon Oct 20 14:41:22 2003 Subject: [Tutor] long-to-string Message-ID: I hope my message reached properly as i have not recieved any response!!! >Hello, > >First of all thanks to tutor for providing their support. People on this >list are really helpful. > >Now I would like to discuss something about my problem:: > > >i have written a module to covert a 4 byte string into a long like this: > >>>>def makelong(chaine): >... # Make a long form a 4-byte string >... return >((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+ord(chaine[3]) >... >>>># Now call the function we just defined: >... makelong('oMAP') >1867333968 > > >I packs this data with struct module > >using '>L' format > >I am able to unpack this and get the no from my file > >Now i want is to convert the no back into the string like 'oMAP' for which >this no was meant. > >I would welcome your suggestions on how should i move ahead. > >Thanks in advance. > >With best regards, > >J+ > >_________________________________________________________________ >MSN Hotmail now on your Mobile phone. >http://server1.msn.co.in/sp03/mobilesms/ Click here. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Celebrate Shakti. Send money to loved ones in India. http://server1.msn.co.in/sp03/navaratri/ Have a joyous Navratri. From bwinton at latte.ca Mon Oct 20 15:13:41 2003 From: bwinton at latte.ca (Blake Winton) Date: Mon Oct 20 15:11:45 2003 Subject: [Tutor] long-to-string In-Reply-To: Message-ID: <007401c3973e$483eaf20$6401a8c0@phantomfiber.com> I was going to reply, but frankly I just started eating my lunch, and didn't read email over the weekend. You might consider being a little more patient if you send out your messages on a Saturday or Sunday. So, you want to convert a long to and from a 4-char string. The conversion to a long (which you already did) can also be written as: >>> struct.unpack( ">l", 'oMAP' ) (1867333968,) and since we only want the first thing, we write: >>> struct.unpack( ">l", 'oMAP' )[0] 1867333968 Which leads me to think that the conversion from a long to the string could be expressed as: >>> struct.pack( ">l", 1867333968 ) 'oMAP' And we see from the result that it indeed can. My one final warning is: If this is intended to help in writing a Palm program (where 4-character longs are used all over the place), then you really want the little-endian version of "l" (or "l"). If not, then feel free to ignore this whole paragraph. Later, Blake. > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Jimmy verma > Sent: Monday, October 20, 2003 2:41 PM > To: tutor@python.org > Subject: Re: [Tutor] long-to-string > > > I hope my message reached properly as i have not recieved any > response!!! > > > > >Hello, > > > >First of all thanks to tutor for providing their support. > People on this > >list are really helpful. > > > >Now I would like to discuss something about my problem:: > > > > > >i have written a module to covert a 4 byte string into a > long like this: > > > >>>>def makelong(chaine): > >... # Make a long form a 4-byte string > >... return > >((ord(chaine[0])*256+ord(chaine[1]))*256+ord(chaine[2]))*256+ > ord(chaine[3]) > >... > >>>># Now call the function we just defined: > >... makelong('oMAP') > >1867333968 > > > > > >I packs this data with struct module > > > >using '>L' format > > > >I am able to unpack this and get the no from my file > > > >Now i want is to convert the no back into the string like > >'oMAP' for which this no was meant. > > > >I would welcome your suggestions on how should i move ahead. From jim_938 at hotmail.com Mon Oct 20 15:32:39 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Mon Oct 20 15:32:44 2003 Subject: [Tutor] long-to-string Message-ID: Thanks a lot for responding. I am able to get what i was looking for. I have packed the long no again in order to get the required string. Can you please explain a bit more on this. Though I got the result but have not understood properly why it happened. I converted my string to a long with the function i wrote. and same thing can be done with unpack. >The conversion to a long (which you already did) can also be >written as: > >>> struct.unpack( ">l", 'oMAP' ) >(1867333968,) > >and since we only want the first thing, we write: > >>> struct.unpack( ">l", 'oMAP' )[0] >1867333968 > >Which leads me to think that the conversion from a long to the >string could be expressed as: > >>> struct.pack( ">l", 1867333968 ) >'oMAP' What happened here???? Not fully clear!!! Waiting for your expert suggestions. Thanks again for your kind support. With best regards, James PS: Sorry for a bit of hurry in sending my mail again. _________________________________________________________________ Buy now! Receive a gold coin on Dhan Teras. http://server1.msn.co.in/features/general/dhanteras/index.asp Celebrate prosperity! From john at duartedailey.org Mon Oct 20 18:37:09 2003 From: john at duartedailey.org (John Duarte) Date: Mon Oct 20 18:37:16 2003 Subject: [Tutor] 2nd Python Book Message-ID: <200310201537.09775.john@duartedailey.org> I have seen recommendations for a first Python book, ie Alan Guald's Learn to Program Using Python, and Lutz & Asher's Learning Python. (Which are both terrific books!) I was wondering if anyone could recommend a '2nd book'. I was glancing through Deitel & Deitel's How to Program Python, and it looks very thorough. Are their any opinions about this book specifically. Thank you. John From pythontutor at venix.com Mon Oct 20 19:32:17 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Mon Oct 20 19:32:27 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <200310201537.09775.john@duartedailey.org> References: <200310201537.09775.john@duartedailey.org> Message-ID: <3F947081.8010408@venix.com> You need to know what you're trying to accomplish to make a good choice. Python in a Nutshell provides a terrific reference for the language with short examples and sage advice. Text Processing in Python has a much narrower focus, but provides some in depth coverage of problem domains where Python is a great tool for writing solutions. Python Programming on Win32 is essential if you need to cater to the world of windows. Programming Python has lots of sample code with detailed discussion. Python in a Nutshell sits by my keyboard. I find it invaluable. John Duarte wrote: > I have seen recommendations for a first Python book, ie Alan Guald's Learn to > Program Using Python, and Lutz & Asher's Learning Python. (Which are both > terrific books!) > > I was wondering if anyone could recommend a '2nd book'. > > I was glancing through Deitel & Deitel's How to Program Python, and it looks > very thorough. Are their any opinions about this book specifically. > > Thank you. > John > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From glingl at aon.at Mon Oct 20 19:37:36 2003 From: glingl at aon.at (Gregor Lingl) Date: Mon Oct 20 19:39:28 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <3F947081.8010408@venix.com> References: <200310201537.09775.john@duartedailey.org> <3F947081.8010408@venix.com> Message-ID: <3F9471C0.3040204@aon.at> Lloyd Kvam schrieb: > You need to know what you're trying to accomplish to make a good choice. > > Python in a Nutshell provides a terrific reference for the language with > short examples and sage advice. > > Text Processing in Python has a much narrower focus, but provides some > in depth coverage of problem domains where Python is a great tool for > writing solutions. > > Python Programming on Win32 is essential if you need to cater to the > world of windows. > > Programming Python has lots of sample code with detailed discussion. > > > Python in a Nutshell sits by my keyboard. I find it invaluable. May I additionally sugest, that the Python Cookbook is an invaluable source of true Python philosophy. Lots of small, very interesting *and* useful recipes ("mind size bites"). And (most of it and more of it) also available online: http://aspn.activestate.com/ASPN/Python/Cookbook/ Regards, Gregor P.S. Editor was Alex Martelli, author of ython in a nutshell > > John Duarte wrote: > >> I have seen recommendations for a first Python book, ie Alan Guald's >> Learn to Program Using Python, and Lutz & Asher's Learning Python. >> (Which are both terrific books!) >> >> I was wondering if anyone could recommend a '2nd book'. >> >> I was glancing through Deitel & Deitel's How to Program Python, and >> it looks very thorough. Are their any opinions about this book >> specifically. >> >> Thank you. >> John >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From carroll at tjc.com Mon Oct 20 21:30:40 2003 From: carroll at tjc.com (Terry Carroll) Date: Mon Oct 20 21:30:54 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <200310201537.09775.john@duartedailey.org> Message-ID: On Mon, 20 Oct 2003, John Duarte wrote: > I have seen recommendations for a first Python book, ie Alan Guald's Learn to > Program Using Python, and Lutz & Asher's Learning Python. (Which are both > terrific books!) > > I was wondering if anyone could recommend a '2nd book'. I like Martelli's "Python in a Nutshell" as a second book. It bridges the gap between typical instruction and reference quite well. Some like Lutz's "Programming Python," but I found it completely frustrating; but that might just be me. As I said, others do like it. For a third book, I like the Python Cookbook. -- Terry Carroll Santa Clara, CA carroll@tjc.com From tbstep at tampabay.rr.com Mon Oct 20 22:01:50 2003 From: tbstep at tampabay.rr.com (Todd Stephens) Date: Mon Oct 20 22:06:01 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <200310201537.09775.john@duartedailey.org> References: <200310201537.09775.john@duartedailey.org> Message-ID: <200310202201.50907.tbstep@tampabay.rr.com> On Monday 20 October 2003 06:37 pm, John Duarte wrote: > I was wondering if anyone could recommend a '2nd book'. > > I was glancing through Deitel & Deitel's How to Program Python, and > it looks very thorough. Are their any opinions about this book > specifically. I tried a few books to start with. Most were pretty good for getting started, but the best I have found so far is "Practical Python" by Magnus Lie Hetland. This is a good first *and* second book. If you use the sample projects from the book as learning tools, it is also a good third book, IMO. -- Todd Stephens "Good people do not need laws to tell them to act responsibly, while bad people will find a way around the laws." - Plato From idiot1 at netzero.net Tue Oct 21 00:38:40 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Tue Oct 21 00:38:42 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <200310201537.09775.john@duartedailey.org> References: <200310201537.09775.john@duartedailey.org> Message-ID: <3F94B850.4020502@netzero.net> Learning Python. John Duarte wrote: > I have seen recommendations for a first Python book, ie Alan Guald's Learn to > Program Using Python, and Lutz & Asher's Learning Python. (Which are both > terrific books!) > > I was wondering if anyone could recommend a '2nd book'. > > I was glancing through Deitel & Deitel's How to Program Python, and it looks > very thorough. Are their any opinions about this book specifically. > > Thank you. > John > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From david at graniteweb.com Tue Oct 21 00:48:49 2003 From: david at graniteweb.com (David Rock) Date: Tue Oct 21 00:48:53 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <200310201537.09775.john@duartedailey.org> References: <200310201537.09775.john@duartedailey.org> Message-ID: <20031021044848.GA15903@wdfs.graniteweb.com> * John Duarte [2003-10-20 15:37]: > I have seen recommendations for a first Python book, ie Alan Guald's Learn to > Program Using Python, and Lutz & Asher's Learning Python. (Which are both > terrific books!) > > I was wondering if anyone could recommend a '2nd book'. > > I was glancing through Deitel & Deitel's How to Program Python, and it looks > very thorough. Are their any opinions about this book specifically. The Deitel & Deitel book is a good starting point. I would consider it another '1st book'. Once you get past the basics, I find that I spend most of my time on the python.org website, personally. The Python Cookbook is good for insights into how to "think python", but the best reference is still the current docs on the website. -- 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/20031020/c275c4e1/attachment.bin From gventer at fish.co.uk Tue Oct 21 02:09:19 2003 From: gventer at fish.co.uk (Gerhard) Date: Tue Oct 21 02:09:12 2003 Subject: [Tutor] this is ugly Message-ID: <3F94CD8F.3070105@fish.co.uk> Dear list Can line 3 of the following be improved (especially since I might want to search for even more strings within each line): myfile=open(r'F:\logs\myfile.txt', 'r') for line in myfile.readlines(): if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: #code if found Thanks Gerhard From glingl at aon.at Tue Oct 21 02:36:30 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Oct 21 02:38:21 2003 Subject: [Tutor] this is ugly In-Reply-To: <3F94CD8F.3070105@fish.co.uk> References: <3F94CD8F.3070105@fish.co.uk> Message-ID: <3F94D3EE.6090202@aon.at> Gerhard schrieb: > Dear list > > Can line 3 of the following be improved (especially since I might want > to search for even more strings within each line): > > myfile=open(r'F:\logs\myfile.txt', 'r') > for line in myfile.readlines(): > if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > #code if found > A quick suggestion: if -1 not in [line.find(x) for x in ["KeC 923","ZEF 156","pBX 88347","FZX 17255"]]: # etc. (untested, of course) Gregor > > Thanks > Gerhard > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From glingl at aon.at Tue Oct 21 02:48:13 2003 From: glingl at aon.at (Gregor Lingl) Date: Tue Oct 21 02:50:37 2003 Subject: OOPS - Re: [Tutor] this is ugly Message-ID: <3F94D6AD.6040601@aon.at> > if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > #code if found > A quick suggestion: if -1 not in : # etc. THIS SUGGESTIION WAS WRONG (error in boolean logic - what a shame!) perhaps you like the the less nice if [line.find(x) for x in ["KeC 923","ZEF 156","pBX 88347","FZX 17255"]] != [-1]*4 ? things = ["KeC 923","ZEF 156","pBX 88347","FZX 17255"] if sum([line.find(thing) for thing in things]) != -len(things) sum is a built-in function since Python 2.3 Sorry for the inconvenience, I'm in a hurry Gregor > > Thanks > Gerhard > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From jjhegde at ncst.ernet.in Tue Oct 21 04:05:21 2003 From: jjhegde at ncst.ernet.in (Jayprasad J. Hegde) Date: Tue Oct 21 04:04:48 2003 Subject: [Tutor] Yet another question on Python and XML In-Reply-To: <3F94D6AD.6040601@aon.at> References: <3F94D6AD.6040601@aon.at> Message-ID: <20031021080521.GA4947@sarathi.ncst.ernet.in> Hello folks, You must have seen this question many times: Could you give me pointers to some *good* source for studying XML processing--DOM, especially--using Python? I am sure that one of the answers would be the "PyXML HowTo". But IMO, it is good as an overview article and I have struggled with getting an in-depth understanding of the details. So, an additional criteria would most definitely be this: something which is a bit more elaborate. Pointers to websites rather than books would be appreciated. Regards and thanks, - JJH -- Comedy, like Medicine, was never meant to be practiced by the general public. From ms_barry2000 at yahoo.com Tue Oct 21 05:40:42 2003 From: ms_barry2000 at yahoo.com (Marc Barry) Date: Tue Oct 21 05:40:46 2003 Subject: [Tutor] Public, private and protected member variables. Message-ID: <20031021094042.58659.qmail@web11702.mail.yahoo.com> Danny, thanks for the help. Please see my comments below. Note that my email address has changed. >From: Danny Yoo >To: Marc Barry >CC: tutor@python.org >Subject: Re: [Tutor] Public, private and protected member variables. >Date: Fri, 17 Oct 2003 10:22:05 -0700 (PDT) > > > >On Fri, 17 Oct 2003, Marc Barry wrote: > > > I have a question regarding the existence of protected members in > > Python. Basically, in a language like Java we have public, private and > > protected member variables. > >Hi Mark, > >(Tangential note: In some programming languages all member variables are >private by default. Objective C is one example.) > > > > Here is a simple example: > > > > #------------------------------------------------------------ > > class Car: > > def __init__(self, colour): > > self.__colour = colour > > > > > > class Ferrari(Car): > > def __init__(self, model, colour): > > > > Car.__init__(self, colour) > > self.__model = model > > > > def printColour(self): > > print self.__colour > > > > a_ferrari = Ferrari("Enzo", "Red") > > print dir(a_ferrari) > > a_ferrari.printColour() > > > > But in Python I only know of public and private. I would like to inherit > > from a class and be able to modify parent member variables, but I would > > not like any class that doesn't inherit from the parent to be able to > > modify the member variables (i.e. Protected concept in Java). > >Python's variable protection is handled by convention, not law. The >Python Style essay says that if we want to specify "protected"-style >status, we can use a single underscore in the front of the name: > Thanks for the the style essay. I am now following its recommendations. > http://www.python.org/doc/essays/styleguide.html > >So the informal way to handle this might be something like this: > >### >class Car: > def __init__(self, colour): > self._colour = colour > >class Ferrari(Car): > def __init__(self, model, colour): > Car.__init__(self, colour) > self.__model = model > > def printColour(self): > print self._colour >### > > >I know this is a toy example, but it might be better to "pull up" the >printColour() method into the parent, and avoid the visibility problems >altogether: Yes, this was a bad example on my part. I should have just spent the time and gave more detail on the class I needed the help with. > >### >class Car: > def __init__(self, colour): > self.__colour = colour > > def printColour(self): > print self.__colour > > >class Ferrari(Car): > def __init__(self, model, colour): > Car.__init__(self, colour) > self.__model = model >### > > > > > If I expose a variable in Car as public, then I will allow users of the > > class to modify it directly. I would like to avoid this since that fixes > > my implementation to being always having to provide a variable named > > "colour" for example. Also, this is just a simplification of my problem > > as my class is much more complicated with a lot of gettable and settable > > properties in the parent object (Which I want to inherit). > > >If you'd like, please feel free to talk about object design on the Tutor >list. It's one of those things I'd like to learn more about myself. >*grin* Perhaps it might be possible to avoid exposing so many properties >by reworking the design a little? > >I think we had a recent discussion about this subject, and one thing that >came up was Java's influence was making people overdesign their classes to >use setFoo/getFoo everywhere. Folks on the list also talked a bit about >the variable visibility stuff that you're interested in: > > http://mail.python.org/pipermail/tutor/2003-October/025599.html > I do find myself using a lot of setFoo and getFoo. I too would like to better understand how to design classes to get around this problem. Right now, I have a class that I reuse in many different situations and depending on the situation the class requires different properties. Basically, what I have done is I use a dictionary inside the class that uses a string as the key and any object as a value. Therefore, I have methods of the form: setProperty(key, value) getProperty(key) I cannot come up with a better way to design the class to avoid using these types of accessor functions. I hear many comments that this type of design is ugly and lots of people hate getFoo/setFoo, but I guess I can't seem to find a better way to handle the type of situation where you have an object that has different properties depending on the situation it is used. > >Good luck to you! > Once again, thanks for your help. __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From ms_barry2000 at yahoo.com Tue Oct 21 08:34:49 2003 From: ms_barry2000 at yahoo.com (Marc Barry) Date: Tue Oct 21 08:34:55 2003 Subject: [Tutor] Public, private and protected member variables. Message-ID: <20031021123449.99844.qmail@web11708.mail.yahoo.com> Thanks for your feedback Alan. I guess my reasoning for most of my statements comes from all of those Java design principles that I have become so accustomed too. I am now beginning to understand the Python handles these types of things. I remember being very confused in the beginning with iterators under Python. I searched through the documentation and all that was stated was an iterator protocol. I was looking for some sort of interface. Now the concept makes complete sense to me. I guess like the iterator protocol, I will just state in the documentation which objects and variables should not be modified and which methods control internal state and leave it up to the programmer to abide by the "protocol". I think that I too am becoming accustomed to the Pythonic ways. Alan, thanks for the comments. I come from the background of Java, which is very strict and it has made Python feel somewhat unnatural to me. Although, the more often I use Python the more it grows on me. Regards, Marc >From: "Alan Gauld" >To: "Marc Barry" , >Subject: Re: [Tutor] Public, private and protected member variables. >Date: Fri, 17 Oct 2003 23:45:43 +0100 > > > I have a question regarding the existence of protected members in >Python. > >We had a longish thread on variable scoping in Python just recently, >try searching the archives. > > > Basically, in a language like Java we have public, private and >protected > > member variables. > >Indeed, Java copied the concept from C++ which introduced it >in version 2, partly to help manage complexity in the face of >multiple inheritance(also introduced in version 2). > > > But in Python I only know of public and private. > >And even private can be bypassed fairly easily (as it can >in C++!) and in practice public variables are the norm. > > > inherit from a class and be able to modify parent member variables, > > but I would not like any class that doesn't inherit from the parent > > to be able to modify the member variables > >Why? Apart from paranoia born from exposure to languages >like C++ and Java(which as I say just played copycat?) > >OO programmers have been using inheritance for many years >without protected scopes (and originally often without >private either!) and it very rarely causes problems. >If you really do need to hide the variables completely >then simply make them private and then provide accessor >functions(yuk!) or make them properties(slightly better). >The accessor can if you really want to, check the immediate >parent of the calling class...if you really want to... > >But do you habitually find yourself breaking your own design >by trying to directly access internal state? Or do you really >distrust your fellow programmers that much? And what about >the occasions when internal access is actually needed by >a non child class? C++ provides the friend construct, >should Python do likewise? > >Its easier to just go with the flow when using a new language. >One of the reasons that C++ and Java are so verbose and >difficult to use is that they introduce all manner of >artificial restictions which programmers have to work around. >(And I say that as someone who used C++ almost exclusively >from 1988 through to 1996 - then I found Delphi, hooray! >Then I found Python, double hooray! And I haven't written >any serious C++ since 1999. And I studiously avoid Java as >much as possible) Python tries to make the programmers life >easy at the expense of expecting a little courtesy to be >exercised. > > > If I expose a variable in Car as public ,then I will allow users of >the > > class to modify it directly. I would like to avoid this since that >fixes my > > implementation to being always having to provide a variable named >"colour" > > for example. > >If that's your concern you could override setattr and getattr >to prevent access to anything that wasn't a method. That >way all attributes are private. Then you have to provide >accessor functions - is that really any better? > >Alternatively, in your documentation just tell users not >to access the attributes directly. And that doing so may result >in undefined behaviour! > > > is much more complicated with a lot of gettable and settable >properties in > > the parent object (Which I want to inherit). > >Yep, that's why lots of gettable/settable properties are a pain. >See the previous thread... Sorry but the gettable/settable stuff >is one of my hot buttons :-( > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > __________________________________ Do you Yahoo!? The New Yahoo! Shopping - with improved product search http://shopping.yahoo.com From pythontutor at venix.com Tue Oct 21 10:36:32 2003 From: pythontutor at venix.com (Lloyd Kvam) Date: Tue Oct 21 10:36:43 2003 Subject: [Tutor] Public, private and protected member variables. In-Reply-To: <20031021094042.58659.qmail@web11702.mail.yahoo.com> References: <20031021094042.58659.qmail@web11702.mail.yahoo.com> Message-ID: <3F954470.20703@venix.com> Marc Barry wrote: > I do find myself using a lot of setFoo and getFoo. I > too would like to better understand how to design > classes to get around this problem. Right now, I have > a class that I reuse in many different situations and > depending on the situation the class requires > different properties. Basically, what I have done is I > use a dictionary inside the class that uses a string > as the key and any object as a value. Therefore, I > have methods of the form: > > setProperty(key, value) > getProperty(key) > > I cannot come up with a better way to design the class > to avoid using these types of accessor functions. I > hear many comments that this type of design is ugly > and lots of people hate getFoo/setFoo, but I guess I > can't seem to find a better way to handle the type of > situation where you have an object that has different > properties depending on the situation it is used. > Python has built in functions getattr(obj, key) and setattr(obj,key,value) that are generic equivalents to the get/setProperty methods except that you must supply the object. If the property names are known when you are writing your code, you can simply create attributes in a class by assigning to the attribute name: some_obj.foo = "some value" The object: some_obj now has a new attribute: foo. I have a "generic" class for dealing with database tables. When connected to a specific database table, the list of fieldnames are determined and stored with the class. The __setattr__ method verifies attribute names are valid for this table and keeps a list of changed attributes for INSERTs and UPDATEs. The __getattr__ method will catch references to database fields that are not yet assigned/defined and return None. For other attribute names it raises an AttributeError. If it is necessary to enforce some consistancy between fields, e.g. startdate < enddate, this can be done in the __setattr__ method. (Most of these ideas were borrowed from examples in Python Programming on Win32) The good side of this approach: easy to read object references (obj.attribute) reasonable enforcement of object requirements fewer methods to write The bad side: __setattr__ can become complex to maintain encourages habit of direct manipulation of attributes Once I start grabbing attributes, I can go overboard. A simple example: build a formatted string for a customer record by writing code that grabs cust.firstname and cust.lastname and so on. The better approach is to have a customer method that returns the formatted string. Then the logic is written once and placed where you would expect to find it. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From sigurd at 12move.de Tue Oct 21 10:46:48 2003 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Oct 21 10:50:45 2003 Subject: [Tutor] this is ugly In-Reply-To: <3F94CD8F.3070105@fish.co.uk> (Gerhard's message of "Tue, 21 Oct 2003 07:09:19 +0100") References: <3F94CD8F.3070105@fish.co.uk> Message-ID: On 21 Oct 2003, Gerhard <- gventer@fish.co.uk wrote: > Can line 3 of the following be improved (especially since I might want > to search for even more strings within each line): > myfile=open(r'F:\logs\myfile.txt', 'r') > for line in myfile.readlines(): > if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > #code if found You could write a simple function which calls the find method. def myfind(s, *args): sf = s.find for x in args: if sf(x) != -1: return True return False myfile=open(r'F:\logs\myfile.txt', 'r') for line in myfile.readlines(): if myfind(line, "KeC 923", "ZEF 156", "pBX 88347", "FZX 17255") #code if found Karl -- Please do *not* send copies of replies to me. I read the list From guillermo.fernandez at epfl.ch Tue Oct 21 12:05:29 2003 From: guillermo.fernandez at epfl.ch (Guillermo Fernandez) Date: Tue Oct 21 12:06:47 2003 Subject: [Tutor] Unimporting modules Message-ID: <3F955949.50603@epfl.ch> Hi, I'm trying to unimport modules. I try into the python interactive command line import os del os and it works just fine. But when I enter it into a function, it creates me problems. import os def run(): try: global os del os finally: import os and it makes me errors... Could someone point me where and why I'm wrong? Thanks, Guille From amk at amk.ca Tue Oct 21 12:33:37 2003 From: amk at amk.ca (amk@amk.ca) Date: Tue Oct 21 12:33:43 2003 Subject: [Tutor] Unimporting modules In-Reply-To: <3F955949.50603@epfl.ch> References: <3F955949.50603@epfl.ch> Message-ID: <20031021163337.GB29550@rogue.amk.ca> On Tue, Oct 21, 2003 at 06:05:29PM +0200, Guillermo Fernandez wrote: > I'm trying to unimport modules. This isn't possible, in general. A statement such as "del os" deletes the binding for the name 'os' in the current namespace, but it doesn't remove the module from sys.modules or free up the space used by its code. --amk From jeff at ccvcorp.com Tue Oct 21 12:58:05 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Oct 21 12:54:06 2003 Subject: [Tutor] Unimporting modules In-Reply-To: <3F955949.50603@epfl.ch> References: <3F955949.50603@epfl.ch> Message-ID: <3F95659D.80304@ccvcorp.com> Guillermo Fernandez wrote: > Hi, > > I'm trying to unimport modules. > [...] As Andrew Kuchling already said, that's not generally possible. My question for you is, *why* do you want to do this? Is there something that you're trying to accomplish by it? If so, there may be some other way to do that. For instance, if you're trying to "unimport" a module so that you can then reimport it and make changes to the module show up, you can do that by calling reload(module). If you have some other goal, there's likely another way to accomplish that, too. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Tue Oct 21 13:24:31 2003 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Oct 21 13:20:22 2003 Subject: [Tutor] Unimporting modules In-Reply-To: <3F9568AA.7050909@epfl.ch> References: <3F955949.50603@epfl.ch> <3F95659D.80304@ccvcorp.com> <3F9568AA.7050909@epfl.ch> Message-ID: <3F956BCF.8080708@ccvcorp.com> Hi Guillermo, I don't know anything about how pdb works (PythonWin's integrated debugger is pretty much the only one I've used), so I can't really offer specific advice. (If breakpoints are being retained even after Python is exited and restarted, then I doubt that reload()ing modules will help much -- maybe there's some data file that pdb is using?) I'm forwarding this back to the list, in hopes that someone else there will have some ideas... Guillermo Fernandez wrote: > Hi, > > Thanks for the answer. > > I'm trying to integrate the pdb into the editor spe > (http://projects.blender.org/projects/spe/) > > The problem is I start the python (and it works well) but when I start > it again, he keeps in memory all the breakpoints that I setted in the > previous session. I thought that to clear those, I could delete the > module and import it again... > > Here is the Shell output: > >>> # I start the debugger with Crt-P > Running 'C:\Python23\Lib\site-packages\sm\pdbtest.py' ... > > (1)?() > Breakpoint 1 at c:\python23\lib\site-packages\sm\pdbtest.py:5 > (Pdb) q > Script 'pdbtest.py' returned exit code 0 > >>> # I start again the debugger with Crt-P > Running 'C:\Python23\Lib\site-packages\sm\pdbtest.py' ... > > (1)?() > Breakpoint 2 at c:\python23\lib\site-packages\sm\pdbtest.py:5 > (Pdb) break > Num Type Disp Enb Where > 1 breakpoint keep yes at c:\python23\lib\site-packages\sm\pdbtest.py:5 > 2 breakpoint keep yes at c:\python23\lib\site-packages\sm\pdbtest.py:5 > (Pdb) q > Script 'pdbtest.py' returned exit code 0 > >>> > > As you can see, when I start again the debugger, the breakpoint added > has number 1 still there (I do a break and the 2 are listed...). I would > like to have a brand new instance of the debugger at each start :-) > > I tried to reload pdb with: > try: > global pdb > del pdb > finally: > import pdb > and I did the same with spedb (I extended pdb in the class spedb to > include breaks automatically at the start of the debugger). > > Thanks in advance! > > Guille > > Jeff Shannon wrote: > >> Guillermo Fernandez wrote: >> >>> Hi, >>> >>> I'm trying to unimport modules. >>> [...] >> >> >> >> As Andrew Kuchling already said, that's not generally possible. My >> question for you is, *why* do you want to do this? Is there something >> that you're trying to accomplish by it? If so, there may be some >> other way to do that. >> >> For instance, if you're trying to "unimport" a module so that you can >> then reimport it and make changes to the module show up, you can do >> that by calling reload(module). If you have some other goal, there's >> likely another way to accomplish that, too. >> >> Jeff Shannon >> Technician/Programmer >> Credit International >> > From dyoo at hkn.eecs.berkeley.edu Tue Oct 21 13:54:15 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 21 13:54:20 2003 Subject: [Tutor] this is ugly In-Reply-To: <3F94CD8F.3070105@fish.co.uk> Message-ID: On Tue, 21 Oct 2003, Gerhard wrote: > Can line 3 of the following be improved (especially since I might want > to search for even more strings within each line): > > myfile=open(r'F:\logs\myfile.txt', 'r') > for line in myfile.readlines(): > if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > #code if found Hi Gerhard, If the number of strings is a bit longer, perhaps a regular expression might be applicable? Also, it might be useful to write some function that takes a bunch of keywords, as well as the text, and does the mass-searching for us. That may help the readability of the code. Here's an example of one keyword-finding function: ### >>> import re >>> def find_keywords(keywords, text): ... """Returns true if any of the keywords exist in the text.""" ... pattern = "|".join(map(re.escape, keywords)) ... return re.search(pattern, text) ... >>> find_keywords(['alpha', 'beta', 'gamma', 'delta', 'epsilon'], ... "this is an alpha test") <_sre.SRE_Match object at 0x16e860> >>> find_keywords(['alpha', 'beta', 'gamma', 'delta', 'epsilon'], ... "this is a test") >>> ### Karl's approach is similar to this. So even if you don't use regular expressions, at least use functions. *grin* Good luck to you! From charlie at begeistert.org Tue Oct 21 15:27:49 2003 From: charlie at begeistert.org (Charlie Clark) Date: Tue Oct 21 15:27:12 2003 Subject: [Tutor] this is ugly In-Reply-To: References: Message-ID: <20031021212749.3006.11@bepc.gormenghast> > > > Can line 3 of the following be improved (especially since I might want > > to search for even more strings within each line): > > > myfile=open(r'F:\logs\myfile.txt', 'r') > > for line in myfile.readlines(): > > if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > > line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > > #code if found These methods are fine but regular expressions are much better for this task. Danny Yoo gave me some help on using re.compile() earlier this year so if you check the archives you should find what you need. Charlie From alan.gauld at blueyonder.co.uk Tue Oct 21 17:27:05 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Oct 21 17:26:29 2003 Subject: [Tutor] 2nd Python Book References: <200310201537.09775.john@duartedailey.org> Message-ID: <002901c3981a$139947d0$6401a8c0@xp> > I have seen recommendations for a first Python book, > ie Alan Guald's Learn to Program Using Python, Thanks for the plug :-) > I was glancing through Deitel & Deitel's How to Program Python, and it looks > very thorough. Are their any opinions about this book specifically. HTPP is a good "advanced intro". It covers a huge amount of ground but, in my opinion, stops just short of being useful in any of them. It gives a taster in loys of things but if you venture out on your own you'll find yourself struggling I suspect. Lutz's Programming Python 2nd ed is less broad but much more detailed in the areas it covers and would be my choice for a general book. However really I'd suggest picking a subject area and buying a book for that - Win32 programming, Tkinter, Web/XML, Database(MySQL say), Text processing etc. There are specialist books on each of these areas. Plus of course one of the must have references: Either "Python in a Nutshell" or "Python Essential reference". The Nutshell is the most recent but both are good, I have both! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Tue Oct 21 17:31:01 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Oct 21 17:30:25 2003 Subject: [Tutor] this is ugly References: <3F94CD8F.3070105@fish.co.uk> Message-ID: <004301c3981a$9ff151f0$6401a8c0@xp> > Can line 3 of the following be improved (especially since I might want > to search for even more strings within each line): > > myfile=open(r'F:\logs\myfile.txt', 'r') > for line in myfile.readlines(): > if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > #code if found Yes use a regular expression. You can combine conditions in one expression and it will only search the string once instead of once per condition. I'll leave it to someone else to explain how to combine the regexs! I'm going to bed and my brain is tired.... :-) Alan G. From alan.gauld at blueyonder.co.uk Tue Oct 21 17:32:12 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Oct 21 17:31:37 2003 Subject: [Tutor] this is ugly References: <3F94CD8F.3070105@fish.co.uk> <3F94D3EE.6090202@aon.at> Message-ID: <004801c3981a$ca9463c0$6401a8c0@xp> > A quick suggestion: > > if -1 not in [line.find(x) for x in ["KeC 923","ZEF 156","pBX > 88347","FZX 17255"]]: > # etc. Still searches three times but at least its more maintainable. A regex in this case will almost certainly be faster than repeated searching. Alan G. From alan.gauld at blueyonder.co.uk Tue Oct 21 17:46:09 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Oct 21 17:45:45 2003 Subject: [Tutor] Public, private and protected member variables. References: <20031021094042.58659.qmail@web11702.mail.yahoo.com> Message-ID: <005901c3981c$bd499c10$6401a8c0@xp> > classes to get around this problem. Right now, I have > a class that I reuse in many different situations and > depending on the situation the class requires > different properties. In that case they are different classes. Although Python allows you to add properties (aka attributes) at run time this probably is the wrong way to tackle it here. Is the interface constant between the classes - in other words are the multitude of classes polymorphic? If so then use inheritance to define the classes you need. (and if not then they are definitely different classes!) If you don't know which class you need until runtime build a factory method(or class!) that will look at the context and return an instance of the right variation. > use a dictionary inside the class that uses a string > as the key and any object as a value. Thats how Python builds a class internally, you are duplicating Python's work... > setProperty(key, value) > getProperty(key) Which is what the getattr and setattr methods do internally in Python... > I cannot come up with a better way to design the class > to avoid using these types of accessor functions. What is the class doing? What data does it manage and what needs to be done to that data? And whatever it is a method of the class should do it. > can't seem to find a better way to handle the type of > situation where you have an object that has different > properties depending on the situation it is used. By definition those are different classes. An class is defined by its identity, state values and behaviour. By having different sets of state variables you are effectively changing the class! You are just doing it at run time! Without more details on what the design looks like and what you are trying to achieve its impossible to be more specific. However generally this situation is handled by creating a class heirarchy(eg a UI event heirarchy) or by creating a generic data carrier collection class (a bit like your dictionary) that is itself an attribute of the dynamic object. This latter solution can be messy and is only normally done when the multi class approach leads to an explosion in the number of classes (over a dozen say). But if you are currently managing it by adding attributes in code then I'd guess creating a class tree is not going to be unreasonable. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Tue Oct 21 17:51:15 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Oct 21 17:50:39 2003 Subject: [Tutor] Public, private and protected member variables. References: <20031021123449.99844.qmail@web11708.mail.yahoo.com> Message-ID: <005e01c3981d$73a5dff0$6401a8c0@xp> > I guess my reasoning for most of my statements comes from all of those Java > design principles that I have become so accustomed too. I had similar problems when I moved to Delphi from C++ because the original Delphi had no protected and only a loose form of Private. Then when I moved to Smalltalk(much like Python, except all variables are private) I was forced to rethink my approach to objects and access etc. > Alan, thanks for the comments. I come from the background of > Java, which is very strict and it has made Python feel > somewhat unnatural to me. Yep, it's part of learning a new language. The good news is the more languages you learn you become more pliable in your approach. I'm currently learning Objective C (using Cocoa on Mac OS X) and it takes a really strange (to me!) approach to memory management. I'm slowly getting there but my initial reaction was to feel very uncomfortable. Its all part of the fun of learning a new language. And each lessonlearnt will be useful in the other languages too! Alan G. From alan.gauld at blueyonder.co.uk Tue Oct 21 17:54:48 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Oct 21 17:54:14 2003 Subject: [Tutor] Public, private and protected member variables. References: <20031021094042.58659.qmail@web11702.mail.yahoo.com> <3F954470.20703@venix.com> Message-ID: <006301c3981d$f2a551a0$6401a8c0@xp> > Once I start grabbing attributes, I can go overboard. > A simple example: build a formatted string for a > customer record by writing code that grabs cust.firstname > and cust.lastname and so on. The better approach is > to have a customer method that returns the formatted string. A good example, Lloyd, of getting the object to do it to itself so that there is no need for the get/set methods or direct access to the fields. > Then the logic is written once and placed where you would > expect to find it. Exactly so - inside the class with the data it manipulates. Thanks for posting, Alan G. From project5 at redrival.net Tue Oct 21 18:05:26 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 21 18:08:27 2003 Subject: [Tutor] Re: this is ugly In-Reply-To: <004301c3981a$9ff151f0$6401a8c0@xp> References: <3F94CD8F.3070105@fish.co.uk> <004301c3981a$9ff151f0$6401a8c0@xp> Message-ID: Alan Gauld wrote: >>Can line 3 of the following be improved (especially since I might > > want > >>to search for even more strings within each line): >> >>myfile=open(r'F:\logs\myfile.txt', 'r') >>for line in myfile.readlines(): >> if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or >>line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: >> #code if found > > > Yes use a regular expression. You can combine conditions in one > expression and it will only search the string once instead of > once per condition. > > I'll leave it to someone else to explain how to combine the > regexs! I'm going to bed and my brain is tired.... :-) Well, here's a RE which would match any of those things: KeC 923|ZEF 156|pBX 88347|FZX 17255 I don't know if evaling that regex would be faster/easier than using the find methods, especially not with one of the shortcut notations mentioned earlier in this thread. Perhaps a more generic RE would be in order, e.g.: \S{3}\s\d{3,5} which (if compiled with the IGNORECASE flag) matches any sequence of 3 letters followed by a space and 3 to 5 digits. Of course I don't know the type of input, perhaps this would match more than desired. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From druidmatt at yahoo.com Tue Oct 21 18:10:23 2003 From: druidmatt at yahoo.com (Matt Hehman) Date: Tue Oct 21 18:10:27 2003 Subject: [Tutor] Request for code critique Message-ID: <20031021221023.98586.qmail@web10309.mail.yahoo.com> I've written a program of about 40 lines including comments. I am teaching myself to program in my spare time, working through the various online tutorials. I started with "Instant Hacking" by Hetland and built on the example to calculate prime numbers. Basically, I looked for better ways to do it, then expanded its functionality by throwing code at it and seeing what stuck. Before I try to refine it any further, I think it would be good to get some feedback before I develop any bad habits. Rather than clog your inboxes by way of asking for a big favor, any volunteers, please e-mail me directly. Thanks, Matt Hehman __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From clay at shirky.com Tue Oct 21 18:19:24 2003 From: clay at shirky.com (Clay Shirky) Date: Tue Oct 21 18:19:02 2003 Subject: [Tutor] Request for code critique In-Reply-To: <20031021221023.98586.qmail@web10309.mail.yahoo.com> Message-ID: > I've written a program of about 40 lines including > comments. I am teaching myself to program in my spare > time, working through the various online tutorials. I > started with "Instant Hacking" by Hetland and built on > the example to calculate prime numbers. Basically, I > looked for better ways to do it, then expanded its > functionality by throwing code at it and seeing what > stuck. Before I try to refine it any further, I think > it would be good to get some feedback before I develop > any bad habits. Rather than clog your inboxes by way > of asking for a big favor, any volunteers, please > e-mail me directly. As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to post it here than to do it via CC. That sort of thing is what tutor is good for. -clay From project5 at redrival.net Tue Oct 21 18:21:21 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 21 18:23:35 2003 Subject: [Tutor] Re: Request for code critique In-Reply-To: References: <20031021221023.98586.qmail@web10309.mail.yahoo.com> Message-ID: Clay Shirky wrote: >>I've written a program of about 40 lines including >>comments. I am teaching myself to program in my spare >>time, working through the various online tutorials. I >>started with "Instant Hacking" by Hetland and built on >>the example to calculate prime numbers. Basically, I >>looked for better ways to do it, then expanded its >>functionality by throwing code at it and seeing what >>stuck. Before I try to refine it any further, I think >>it would be good to get some feedback before I develop >>any bad habits. Rather than clog your inboxes by way >>of asking for a big favor, any volunteers, please >>e-mail me directly. > > > As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to > post it here than to do it via CC. That sort of thing is what tutor is good > for. I agree, I can fit more than 50 lines of code on my screen so 40 doesn't seem like such a big problem. Make sure your mail interface doesn't break the code though. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From arkamir at softhome.net Tue Oct 21 18:42:42 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Oct 21 18:43:52 2003 Subject: [Tutor] can someone explain to me how this works Message-ID: <1066776162.5035.4.camel@quercus> Hey thanks for the tips !!! def compare(a,b): if a[1]>b[1]: return 0 else: return -1 i tried this out and it works, but i dont understand the logic behind it :( can someone help me out i also dont get how it compares all the tuples in a list. Dont you need to enter in two values not just one list????? From dyoo at hkn.eecs.berkeley.edu Tue Oct 21 19:13:22 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 21 19:18:42 2003 Subject: [Tutor] can someone explain to me how this works [comparsion functions and sort()] In-Reply-To: <1066776162.5035.4.camel@quercus> Message-ID: On Tue, 21 Oct 2003, Conrad Koziol wrote: > Hey thanks for the tips !!! > > def compare(a,b): > if a[1]>b[1]: return 0 > else: return -1 > > i tried this out and it works, but i dont understand the logic behind it > :( can someone help me out Hi Conrad, A "comparison function" is something that takes two things, and checks to see if one is smaller than another. In math notation: compare(a,b) = { -1 if a < b 0 if a == b 1 if a > b } The important thing to see is that a comparison function is not meant to be a "boolean" true-false thing: it's meant to return either a positive, zero, or negative value. Is this what's confusing, or is it something else? Please feel free to ask more questions about this, as it is definitely a confusing topic when we first see it. > i also dont get how it compares all the tuples in a list. Dont you need > to enter in two values not just one list????? Yes, this would be true if we were directly calling compare() on the list itself. However, that's not what's happening: instead, we're calling sort, and sort() itself is calling compare() on pairs of elements on our list. Here's a concrete toy example of a similar situation: ### >>> def applyOnList(function, L): ... """Destructivly applies a 'function' on the list 'L'.""" ... for index, element in enumerate(L): ... L[index] = function(element) ... >>> def square(x): return x * x ... >>> numbers = range(10) >>> applyOnList(square, numbers) >>> numbers [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ### In this case, we've written a function called applyOnList() that takes in a function, as well as a list of things. Notice that the function we pass in isn't being called on the whole list, but only on single elements of that list. sort() does something somewhat similar when it takes in that comparison function. sort() uses it as a helper toward some greater goal --- sorting things --- but doesn't need to try applying it to the whole list at once. Hope that made some sort of sense. *grin* Please feel free to ask more questions: if you'd like, we can talk about how comparsion functions actually help sort() figure out how to sort. From arkamir at softhome.net Tue Oct 21 18:42:42 2003 From: arkamir at softhome.net (Conrad Koziol) Date: Tue Oct 21 19:19:07 2003 Subject: [Tutor] can someone explain to me how this works Message-ID: <1066776162.5035.4.camel@quercus> Hey thanks for the tips !!! def compare(a,b): if a[1]>b[1]: return 0 else: return -1 i tried this out and it works, but i dont understand the logic behind it :( can someone help me out i also dont get how it compares all the tuples in a list. Dont you need to enter in two values not just one list????? From erikprice at mac.com Tue Oct 21 20:43:41 2003 From: erikprice at mac.com (Erik Price) Date: Tue Oct 21 20:21:20 2003 Subject: [Tutor] 2nd Python Book In-Reply-To: <200310201537.09775.john@duartedailey.org> Message-ID: On Monday, October 20, 2003, at 06:37 PM, John Duarte wrote: > I have seen recommendations for a first Python book, ie Alan Guald's > Learn to > Program Using Python, and Lutz & Asher's Learning Python. (Which are > both > terrific books!) > > I was wondering if anyone could recommend a '2nd book'. The Python Cookbook. You already know Python, this book teaches you how to do specific tasks or sophisticated programming idioms specific to Python. It's one of my favorite Python books. > I was glancing through Deitel & Deitel's How to Program Python, and it > looks > very thorough. Are their any opinions about this book specifically. I didn't even know these guys had a Python book. Neat. Erik From Harm_Kirchhoff at mail.digital.co.jp Tue Oct 21 20:07:57 2003 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Tue Oct 21 20:21:56 2003 Subject: [Tutor] Nested Lists / Array Module Message-ID: Python supports nested lists, which is very nice and can be used for very simple databases. However, I could not find a way to write nested lists to files & retrieve them easily. The .writelines() method expects a string as an argument. Is there a method to dump any list on disk & read it back, or is it necessary to code this task ? The array module seems to have such method, however, I could not find sufficient code examples to understand how the array module works. The Python Library Reference mentions the .fromfile() and .tofile() methods, does anyone have experience with the array module, especially whether it allows to write & retrieve nested arrays without problems ? Could you pass me some sample code ? Harm From project5 at redrival.net Tue Oct 21 20:33:27 2003 From: project5 at redrival.net (Andrei) Date: Tue Oct 21 20:35:42 2003 Subject: [Tutor] Re: Nested Lists / Array Module In-Reply-To: References: Message-ID: Harm_Kirchhoff@mail.digital.co.jp wrote: > Python supports nested lists, which is very nice and can be used for very > simple databases. > > However, I could not find a way to write nested lists to files & retrieve > them easily. > The .writelines() method expects a string as an argument. > > Is there a method to dump any list on disk & read it back, or is it > necessary to code this task ? Not too long ago a similar question (or was it the same?) was on the list I believe. You can either pickle or convert your list to a string using str(), e.g. str(MyList). It doesn't matter how deep that list is. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Tue Oct 21 20:54:28 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Oct 21 20:54:34 2003 Subject: [Tutor] Nested Lists / Array Module In-Reply-To: Message-ID: On Wed, 22 Oct 2003 Harm_Kirchhoff@mail.digital.co.jp wrote: > Python supports nested lists, which is very nice and can be used for very > simple databases. > > However, I could not find a way to write nested lists to files & > retrieve them easily. The .writelines() method expects a string as an > argument. > > Is there a method to dump any list on disk & read it back, or is it > necessary to code this task ? Hi Harm, Yes. For simple cases, the 'shelve' module can help to "serialize" these nested structures to and from disk. "Serialization" is a term we use to transform arbitrary Python objects to byte strings, and it's pretty easy to do in Python. In fact, we talked about this about a week ago: http://mail.python.org/pipermail/tutor/2003-October/025741.html The example at that link uses only a flat list, but 'shelve' should work with lists in lists too. If you have more questions, please feel free to ask. Good luck! From clay at shirky.com Tue Oct 21 21:42:46 2003 From: clay at shirky.com (Clay Shirky) Date: Tue Oct 21 21:42:29 2003 Subject: [Tutor] General construction of alpha lists? Message-ID: So I have this bit of code: class_groups = [ 'A', 'B', 'C', 'D', 'E' ] while class_groups: next = random.choice( range( len(class_groups) )) print class_groups[next] class_groups[next:next+1] = [] which will give me some random permutation of the items in the list class_groups. Next stop, making it possible to generate an alphabetical list, based on the array number. I'd like to do something like class_groups = range(12) and then have it print from A through L. Is there an easy way to specify a list that is simply letters in order, or do I have to write out alpha = [ 'A', 'B', ... 'Z', 'a', 'b', ... 'z' ] Thanks -clay From contrasutra at myrealbox.com Tue Oct 21 23:08:05 2003 From: contrasutra at myrealbox.com (Ben Mazer) Date: Tue Oct 21 23:34:54 2003 Subject: [Tutor] Timing a loop Message-ID: <3F95F495.4050102@myrealbox.com> I have written a small script that creates a bunch of small text files. I'm doing this because I want to benchmark file creation/deletion times on different file systems. Im looking right now about how to time how long it takes to create the files. I looked at the Timeit() module, and that doesn't seem to work, its for small algorithms. I also looked at time.clock(), but I can't get that to display an accurate readout, so I dont think that works (or Im not using it right). I know I could use the UNIX "time" command, but it would be nice if Python had a built in function. They probably do, but I can't find it. :P Any help you could provide on timing a loop would be really helpful. OT: How many files can reiserfs hold? I keep hitting "file system full" limits when I get into large amounts of files (hundreds of thousands). Thanks. -- /"\ Ben Mazer \ / X ASCII RIBBON CAMPAIGN AGAINST HTML MAIL / \ From karl.fast at pobox.com Tue Oct 21 23:42:06 2003 From: karl.fast at pobox.com (Karl Fast) Date: Tue Oct 21 23:42:16 2003 Subject: [Tutor] General construction of alpha lists? In-Reply-To: ; from clay@shirky.com on Tue, Oct 21, 2003 at 09:42:46PM -0400 References: Message-ID: <20031021214206.E8821@signal.lights.com> > Is there an easy way to specify a list that is simply letters in > order, or do I have to write out > > alpha = [ 'A', 'B', ... 'Z', 'a', 'b', ... 'z' ] The string module defines various constants that have the characters you want. If you do this in the shell you can see what's in these constants. >>> import string >>> print string.uppercase ABCDEFGHIJKLMNOPQRSTUVWXYZ?????????????????????????????????? >>> print string.lowercase abcdefghijklmnopqrstuvwxyz???????????????????????????????????? >>> print string.printable 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_{|}~ There are other constants too. Details in the string module docs. I'm new to python myself, but this should do what you want. --karl From tbrauch at mindless.com Wed Oct 22 00:07:36 2003 From: tbrauch at mindless.com (Timothy M. Brauch) Date: Wed Oct 22 00:07:39 2003 Subject: [Tutor] Bit Strings Message-ID: <005801c39852$07468c30$6600a8c0@winxp> There has to be an easy way to do this that I am just not seeing. I am trying to create all bit strings of length n. Right now my code is as follows: bitStrings = [] for a0 in [0,1]: for a1 in [0,1]: for a2 in [0,1]: oneString = str(a0)+str(a1)+str(a2) bitStrings.append(oneString) print bitStrings I know this is ugly and when I need longer strings, say n = 10, the code gets way too repetitive with 10 nested for loops. Surely there is an easier way to do this, but I just can't figure it out. I have a function that will generate the above functions, but it is uglier and probably way not the correct way to go about this. def generator(n): tb = " " stringMaker = "" print "bitStrings = []" for i in xrange(0,n+1): print i*tb + "for a"+str(i)+" in [0,1]:" stringMaker = stringMaker + "str"+chr(40)+"a"+str(i)+chr(41)+chr(43) stringMaker = stringMaker[:-1] #strip the last chr(43) print (i+1)*tb + "oneString = "+stringMaker print (i+1)*tb + "bitStrings.append(oneString)" print "print bitStrings" Any suggestions? - Tim --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003 From idiot1 at netzero.net Wed Oct 22 00:41:29 2003 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Oct 22 00:42:12 2003 Subject: [Tutor] can someone explain to me how this works In-Reply-To: <1066776162.5035.4.camel@quercus> References: <1066776162.5035.4.camel@quercus> Message-ID: <3F960A79.3030501@netzero.net> I will give it a shot. Try not to laugh too hard if I mung it into kruftyness. Conrad Koziol wrote: > Hey thanks for the tips !!! > > def compare(a,b): > if a[1]>b[1]: return 0 > else: return -1 > ok. a[1] returns a char from a string, or a number in a list or tuple of numbers. So does b[1]. I am ASSUMING they are numbers in a list or tuple. Look at the values they would return. if a[1]=12, and b[1]=4, well, 12>4 is true, so it would return a 1, which is a logical TRUE. so the condition after the test would happen, which is 'return 0', so your function ends, returning the value 0. now a -1 would be returned if the test was NOT true, by executing the other leg in the if/else structure. First, it's neater to put the conditional after a if statement indented on the next line, and I cannot gurantee that placing it on the SAME line as the test will work in future versions of python. so let's do this: def compare(a,b): if a[1]>b[1]: return 0 else: return -1 This is your function, nice nad neat and quite properly pythonesque. But we can make it easier. def compare(a,b): return not a[1]>b[1] Not inverts the logical vallue of a returned logical value. Again, a[1]=12 and b[1]=4. with this test, and those values, the return is 0. Were the values reversed, this would be a 1 return, which is true, as is a -1 return value. IF the value HAS to be 0 or -1, we need to define the function with customized values. And a simple way to do it is: def compare(a,b): return (a[1]>b[1])-1 Dig; if true, the returned value of a test is 1. If false, it is 0. These are plain old fashioned interger values, and you can do basic math on them just fine. Subtract 1 from that result, and you get 0 and -1 respectively. Python treats 0 as false, and any non 0 value as true, therefore the logic holds and you get your desired result faster and simpler. Any discussion gang? > i tried this out and it works, but i dont understand the logic behind it > :( > can someone help me out > > i also dont get how it compares all the tuples in a list. Dont you need to enter > in two values not just one list????? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Prometheus + kniht + Fnord. From thomi at imail.net.nz Wed Oct 22 00:53:11 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Wed Oct 22 01:03:56 2003 Subject: [Tutor] Bit Strings In-Reply-To: <005801c39852$07468c30$6600a8c0@winxp> References: <005801c39852$07468c30$6600a8c0@winxp> Message-ID: <200310221753.11830.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, > > Any suggestions? > I may have an idea ;) essentially, what your code does is a binary count from 0 to 2^n (where n is the number of iterations / bits). right? here's a sampel run of your code: (using 3 bits / iterations): >>> bitStrings = [] >>> for a0 in [0,1]: ... for a1 in [0,1]: ... for a2 in [0,1]: ... oneString = str(a0)+str(a1)+str(a2) ... bitStrings.append(oneString) ... >>> bitStrings ['000', '001', '010', '011', '100', '101', '110', '111'] Unless I'm mistaken, couldn't you do something like this: >>> def bitStrings(iterations=3): ... binary_strlist = [] ... for num in range(2**iterations): ... binary_strlist.append(binary(num)) ... return binary_strlist ... which leaves us with the task of coding a decimal to binary converter. This is actually quite simple...One way to do it is to use a dictionary to convert from a hex value to a binary one (AFAIK, python doesn't have a binary converter. It does however have a hex converter). However, there are a couple of complications in this function: 1.- we could/should? pad the binary values with zero's.. so binary 1 becomes 001, or 00000001 (for an 8 bit number) 2.- we can't do a direct map from decimal->hex-> binary, because we might be given a decimal larger than 15, which will result in a two digit hex number... So, something like this: >>> def binary(decimal): ... bin_string = '' ... map_dict = { ... '0' : '0000', ... '1' : '0001', ... '2' : '0010', ... '3' : '0011', ... '4' : '0100', ... '5' : '0101', ... '6' : '0110', ... '7' : '0111', ... '8' : '1000', ... '9' : '1001', ... 'a' : '1010', ... 'b' : '1011', ... 'c' : '1100', ... 'd' : '1101', ... 'e' : '1110', ... 'f' : '1111' } ... for hexdigit in hex(decimal)[2:]: #ignore the leading '0x' ... bin_string += map_dict[hexdigit] ... return bin_string to test our decimal -> binary converter: >>> binary(5) '0101' >>> binary(50) '00110010' Now we can test the whole thing: bitStrings() (this uses the default, 3 places) for more places: >>> bitStrings(5) ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111', '00010000', '00010001', '00010010', '00010011', '00010100', '00010101', '00010110', '00010111', '00011000', '00011001', '00011010', '00011011', '00011100', '00011101', '00011110', '00011111'] As you can see, there's still some problems here. I've been doing this all in the interactive window, and it's getting a bit cumbersome. Perhaps it's time for someone else to continue this ;P It's pretty much there, and it's prettyextendable as well. (I would appreciate some feedback on this from some of the more experienced tutor list members as well ;) anyway, i hope this helps! Thanks, - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/lg032tSuYV7JfuERAjW7AKCQXafrATb5HcJwtBWdheoGFDQWCQCfUZ1X 8dKMIJ4hZvSueTUSfvhycUQ= =bMx+ -----END PGP SIGNATURE----- From thomi at imail.net.nz Wed Oct 22 00:59:22 2003 From: thomi at imail.net.nz (Thomi Richards) Date: Wed Oct 22 01:10:06 2003 Subject: [Tutor] Bit Strings In-Reply-To: <200310221753.11830.thomi@imail.net.nz> References: <005801c39852$07468c30$6600a8c0@winxp> <200310221753.11830.thomi@imail.net.nz> Message-ID: <200310221759.22986.thomi@imail.net.nz> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > 1.- we could/should? pad the binary values with zero's.. so binary 1 > becomes 001, or 00000001 (for an 8 bit number) > > 2.- we can't do a direct map from decimal->hex-> binary, because we might > be given a decimal larger than 15, which will result in a two digit hex > number... > Sorry.. I just realised that these really don't make any sense whatsoever, when you look at the code ;) sorry, it's been a long day ;( - -- Thomi Richards, http://once.sourceforge.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQE/lg6q2tSuYV7JfuERAmh6AJ94FJeBUxbdlhoUWoJMOEEdk7TI4wCePDb2 Bt56N6CMAkvgSdnSdGKOcPk= =lKD3 -----END PGP SIGNATURE----- From dyoo at hkn.eecs.berkeley.edu Wed Oct 22 02:03:26 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 22 02:03:33 2003 Subject: [Tutor] General construction of alpha lists? In-Reply-To: Message-ID: On Tue, 21 Oct 2003, Clay Shirky wrote: > Next stop, making it possible to generate an alphabetical list, based on > the array number. I'd like to do something like > > class_groups = range(12) > > and then have it print from A through L. Hi Clay, Yes, there's a nice way to do it. Karl Fast's approach is probably the best one. But if we didn't have that nice string constant handy, we can still do it easily. Here are two ingredients: chr() -- http://www.python.org/doc/lib/built-in-funcs.html#l2h-15 ord() -- http://www.python.org/doc/lib/built-in-funcs.html#l2h-56 With some list manipulation, you should be able to cook something up pretty nicely. *grin* Talk to you later! From tbrauch at mindless.com Wed Oct 22 02:13:34 2003 From: tbrauch at mindless.com (Timothy M. Brauch) Date: Wed Oct 22 02:13:35 2003 Subject: [Tutor] Bit Strings References: <005801c39852$07468c30$6600a8c0@winxp> <200310221753.11830.thomi@imail.net.nz> Message-ID: <007201c39863$a01179f0$6600a8c0@winxp> From: "Thomi Richards" > > I may have an idea ;) > > essentially, what your code does is a binary count from 0 to 2^n (where n is > the number of iterations / bits). right? > > Unless I'm mistaken, couldn't you do something like this: > > >>> def bitStrings(iterations=3): > ... binary_strlist = [] > ... for num in range(2**iterations): > ... binary_strlist.append(binary(num)) > ... return binary_strlist > ... > >>> bitStrings(5) > ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', > '1001', '1010', '1011', '1100', '1101', '1110', '1111', '00010000', > '00010001', '00010010', '00010011', '00010100', '00010101', '00010110', > '00010111', '00011000', '00011001', '00011010', '00011011', '00011100', > '00011101', '00011110', '00011111'] > > As you can see, there's still some problems here. > > > - -- > Thomi Richards, > http://once.sourceforge.net/ Ah, very good, very good indeed. Your result for bitStrings(5) was so close to being right. The only thing left to do would be to clean up the strings so that they all have 5 digits. Thus '0000' becomes '00000' and '00011001' becomes '11001' and so forth. I think that can be done pretty easily. Something like the following before we append... bits = binary(num) while len(bits) < iterations: bits = '0' + bits while len(bits) > iterations: if bits[0] != '1': #check to be sure first digit isn't a one, bits = bits[1:] #but it shouldn't be anyway binary_strlist.append(bits) Let's put it all together and see what we get... def bitStrings(iterations=3): binary_strlist = [] for num in range(2**iterations): bits = binary(num) while len(bits) < iterations: bits = '0' + bits while len(bits) > iterations: if bits[0] != '1': #check to be sure first digit isn't a one, bits = bits[1:] #but it shouldn't be anyway binary_strlist.append(bits) return binary_strlist >>> bitStrings(5) ['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111'] Checking bitStrings(6) and bitStrings(7) gives the correct answer as well. Perfect. I'm sure the padding/stripping part could be written a little more effective, but it fits my needs for right now. Thanks. The next task would be what if I needed strings that used 0, 1, and 2. We'd need a decimal to trinary function. Or if I needed strings that used all digits from 0 to (n-1). Hmm, I think I know how I will be spending my weekend. - Tim --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003 From dyoo at hkn.eecs.berkeley.edu Wed Oct 22 02:33:37 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 22 02:34:46 2003 Subject: [Tutor] Bit Strings [a recursive approach] In-Reply-To: <005801c39852$07468c30$6600a8c0@winxp> Message-ID: On Wed, 22 Oct 2003, Timothy M. Brauch wrote: > There has to be an easy way to do this that I am just not seeing. I am > trying to create all bit strings of length n. Hi Timothy, Have you tried a recursive approach? It might be useful to outline how to solve this recursively, so here goes! *grin* Let's say that we have a function called bitstrings(n) that gives us all the bit strings of length n. Then we can say a few things about it: bitstrings(0) = [] bitstrings(1) = ["0", "1"] bitstrings(2) = ["00", "01", "10", "11"] bitstrings(3) = ["000", "001", "010", "011", "100", "101", "110", "111"] With this, we can already write something down in Python: ### >>> def bitstrings(n): ... if n == 0: return [] ... if n == 1: return ["0", "1"] ... if n == 2: return ["00", "01", "10", "11"] ... if n == 3: return ["000", "001", "010", "011", "100", "101", "110", "111"] ... >>> bitstrings(0) [] >>> bitstrings(1) ['0', '1'] >>> bitstrings(2) ['00', '01', '10', '11'] >>> bitstrings(3) ['000', '001', '010', '011', '100', '101', '110', '111'] >>> bitstrings(4) >>> ### And this sorta works, except it handles things up only up to n=4. *grin* How do we define it for larger values of n? One key to a recursive solution is to look at how the smaller solutions are built up. Let's look at the difference between bitstrings(2) and bitstrings(3): ### >>> bitstrings(2) ['00', '01', '10', '11'] >>> bitstrings(3) ['000', '001', '010', '011', '100', '101', '110', '111'] ### Here's a weird question: if we want to build up bitstrings(3) out of components of bitstrings(2), is there a way to do it? The key here is to see that bitstrings(3) almost looks like two copies of bitstrings(2): ### >>> bitstrings(3) ['000', '001', '010', '011', '100', '101', '110', '111'] >>> bitstrings(2) + bitstrings(2) ['00', '01', '10', '11', '00', '01', '10', '11'] ### It's really darn close, except we need to augment the the first half of that result list so that each element has a '0' in front of it, and augment the second half with '1' in front. But that's not too difficult to do: ### >>> def appendInFront(x, L): ... return [x + element for element in L] ... >>> appendInFront("0", bitstrings(2)) ['000', '001', '010', '011'] ### So now that we have something like appendInFront(), we can rewrite bitstrings() this way: ### def bitstrings(n): if n == 0: return [] if n == 1: return ["0", "1"] if n == 2: return ["00", "01", "10", "11"] if n == 3: return (appendInFront("0", bitstrings(2)) + appendInFront("1", bitstrings(2))) ### In fact, with some thought, we can even expand this to work for n=4: ### def bitstrings(n): if n == 0: return [] if n == 1: return ["0", "1"] if n == 2: return ["00", "01", "10", "11"] if n == 3: return (appendInFront("0", bitstrings(2)) + appendInFront("1", bitstrings(2))) if n == 4: return (appendInFront("0", bitstrings(3)) + appendInFront("1", bitstrings(3))) ### Or even n=5. ### def bitstrings(n): if n == 0: return [] if n == 1: return ["0", "1"] if n == 2: return ["00", "01", "10", "11"] if n == 3: return (appendInFront("0", bitstrings(2)) + appendInFront("1", bitstrings(2))) if n == 4: return (appendInFront("0", bitstrings(3)) + appendInFront("1", bitstrings(3))) if n == 5: return (appendInFront("0", bitstrings(4)) + appendInFront("1", bitstrings(4))) ### We can go on this this for some time. *grin* (By the way, notice that when n=4, we end up doing something like: bitstrings(4) --> appendInFront(0, bitstrings(3)) + ... [repeat] / \ / \ / \ appendInFront('0', appendInFront('1', bitstrings(2)) bitstrings(2)) ) But that's ok, since bitstrings(2) is something our bitstrings() function can handle perfectly well. Here's the punchline: things will work if we take a leap of faith, and just write: ### def bitstrings(n): if n == 0: return [] if n == 1: return ["0", "1"] if n == 2: return ["00", "01", "10", "11"] else: return (appendInFront("0", bitstrings(n-1)) + appendInFront("1", bitstrings(n-1))) ### Does this make sense so far? Please feel free to ask questions on this. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Oct 22 03:20:10 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 22 03:20:39 2003 Subject: [Tutor] can someone explain to me how this works [comparison functions] In-Reply-To: <3F960A79.3030501@netzero.net> Message-ID: On Wed, 22 Oct 2003, Kirk Bailey wrote: > Not inverts the logical vallue of a returned logical value. Again, > a[1]=12 and b[1]=4. with this test, and those values, the return is 0. > Were the values reversed, this would be a 1 return, which is true, as is > a -1 return value. IF the value HAS to be 0 or -1, we need to define the > function with customized values. And a simple way to do it is: > > def compare(a,b): > return (a[1]>b[1])-1 Hi Kirk, True, it's simpler for the computer, but it's depending on the fact that True and False are represented as 1 and 0. Personally, I like: ### def compare(a,b): if a[1] > b[1]: return 0 else: return -1 ### better. Even though it's more wordy, it won't surprise anyone who is coming from a language with stricter boolean types. But even so, I feel: ### def compare(a,b): if a[1] < b[1]: return -1 elif a[1] == b[1]: return 0 else: return 1 ### is clearer as a comparison function. Comparison functions are meant to be triple-valued. The original function obscured this point because it only returned either -1 or 0, which isn't quite right. By making three distinct cases, we can convince anyone reading this that it is triple-valued. (By the way, the shortest definition I can think that's equivalent to the above example is: "def compare(a,b): return cmp(a[1], b[1])".) It's very important to know that comparison functions must not be boolean functions. We can even see sort() malfunction if we accidently make it return either 0 or 1! ### >>> def brokenCompare(a, b): ... if a > b: return 1 ... return 0 ... >>> numbers = [5,4,3,2,1] >>> numbers.sort(brokenCompare) >>> numbers [5, 4, 3, 2, 1] ### It's only by a coincidence of implementation that sort() works on a comparison function that returns either 0 or -1. Even so, we should strive to make a comparison function return either -1, 0, or 1. One last point: I've been fudging. *grin* Comparison functions don't have to return -1, 0, or 1: they can return negatives, zero, or positives. If we know this, then it's tempting to avoid writing: ### def compare(a,b): if a[1] < b[1]: return -1 elif a[1] == b[1]: return 0 else: return 1 ### and instead say something like ### def compare(a, b): return a[1] - b[1] ### to avoid all that wordy comparison logic. It's fast, it involves a single numeric operation, so what can be the problem with it? Actually, it is dangerous. It's not so bad in Python, since we have long ints, but in a language that doesn't automagically use bignums, this definition is broken: subtraction can overflow! That's one reason why I personally remind myself that the range of a comparison function is (-1, 0, 1), and not (negative, zero, positive) --- it pretty much forces me to do the explicit comparisons. *grin* Talk to you later! From tbrauch at mindless.com Wed Oct 22 03:48:59 2003 From: tbrauch at mindless.com (Timothy M. Brauch) Date: Wed Oct 22 03:48:58 2003 Subject: [Tutor] Bit Strings [a recursive approach] References: Message-ID: <009a01c39870$f4402730$6600a8c0@winxp> Whilst trying to find all bit strings of a certain length, I struggled. Danny Yoo was helpful with: > Have you tried a recursive approach? It might be useful to outline how to > solve this recursively, so here goes! *grin* I should have thought of this, since the way I was doing it by hand was basically recursive... > >>> def appendInFront(x, L): > ... return [x + element for element in L] > ... > >>> appendInFront("0", bitstrings(2)) > ['000', '001', '010', '011'] > ### ... > Here's the punchline: things will work if we take a leap of faith, and > just write: > > ### > def bitstrings(n): > if n == 0: return [] > if n == 1: return ["0", "1"] > if n == 2: return ["00", "01", "10", "11"] > else: > return (appendInFront("0", bitstrings(n-1)) > + appendInFront("1", bitstrings(n-1))) > ### > > > Does this make sense so far? Please feel free to ask questions on this. Yes, that is the way I was doing it by hand. First right down the n=1 case. Then for n=2, write it down a second time and put a zero in front of the first half, a 1 in front of the second half. For n=3, write down n=2 twice, putting a 0 infront of the first half, a 1 in front of the second... I guess I just didn't realize what I was doing by hand would have worked if I had coded it correctly. And, the nice thing about this is that it should be pretty easy to extend the idea if my strings need to have more characters. Just a few more base cases and the else:return needs to be have a few more lines. Thanks. - Timothy P.S. I guess it is the mathematician in me that doesn't like recursively defined functions. We tend to like closed form things better. And it was my stumbling block in my algorithm classes. Although, recursive is often much more elegant... --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003 From alan.gauld at blueyonder.co.uk Wed Oct 22 04:36:44 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Oct 22 04:36:02 2003 Subject: [Tutor] Bit Strings [a recursive approach] References: Message-ID: <00cc01c39877$9fb8bb80$6401a8c0@xp> > Here's the punchline: things will work if we take a leap of faith, and > just write: > > ### > def bitstrings(n): > if n == 0: return [] > if n == 1: return ["0", "1"] > if n == 2: return ["00", "01", "10", "11"] > else: > return (appendInFront("0", bitstrings(n-1)) > + appendInFront("1", bitstrings(n-1))) > ### And in fact you could even remove the if n== 2 line. It works just fine using the appendInFRont function! def bitstrings(n): if n == 0: return [] if n == 1: return ["0", "1"] else: return (appendInFront("0", bitstrings(n-1)) + appendInFront("1", bitstrings(n-1))) :-) Alan G. From charlie at begeistert.org Wed Oct 22 04:41:45 2003 From: charlie at begeistert.org (Charlie Clark) Date: Wed Oct 22 04:40:57 2003 Subject: [Tutor] Re: Bit strings In-Reply-To: References: Message-ID: <20031022104145.542.1@bepc.gormenghast> On 2003-10-22 at 09:21:50 [+0200], tutor-request@python.org wrote: > >>> bitStrings(5) > ['00000', '00001', '00010', '00011', '00100', '00101', '00110', '00111', > '01000', '01001', '01010', '01011', '01100', '01101', '01110', '01111', > '10000', '10001', '10010', '10011', '10100', '10101', '10110', '10111', > '11000', '11001', '11010', '11011', '11100', '11101', '11110', '11111'] > > Checking bitStrings(6) and bitStrings(7) gives the correct answer as > well. Perfect. I'm sure the padding/stripping part could be written a > little more effective, but it fits my needs for right now. Thanks. > > The next task would be what if I needed strings that used 0, 1, and 2. > We'd need a decimal to trinary function. Or if I needed strings that > used all digits from 0 to (n-1). Hmm, I think I know how I will be > spending my weekend. Reading this last paragraph makes me think that you are looking for a generic base converter. I'm sure there are lots of examples around there but it should be quite easy to come up with your own using a recursive function. I'm very bad at designing these myself but in theory you can convert any decimal to another base by dividing recursively and adding the modulus to the result. You can build this into a lazy function which can operate on a range for you and use "zfill" to generate your formatted strings. Quick sketch 9 / 2, 9 % 2 = 4, 1 4 / 2, 4 % 2 = 2, 0 2 / 2, 2 % 2 = 1, 0 1 / 2, 2 % 1 = 0, 0 # this tells us we're at the end of anaylsis The trick is to turn this into something like 1 0 0 + 1 and to test it with other values. The nice thing about division and modulo is that we don't have to worry about what is the maximal value in any particular base. Charlie From dhanvik at gmx.net Wed Oct 22 06:20:58 2003 From: dhanvik at gmx.net (dhanvik@gmx.net) Date: Wed Oct 22 06:20:16 2003 Subject: [Tutor] Python Class functionality idiosyncrasy.. Message-ID: <200310221550.58631.dhanvik@gmx.net> Dear Friends, While just playing arnd with Python .. I just came across this curious implementation of Python Object Oriented Techniques.. The base class here is calling a function of the derived class even befre the function of the derived class is defined..A similar implementation in C++ would not even compile.. My question is doesnt this implementation break some tennants of OO techniques ?? How can the base class call functions of the derived class ?? >>> class base1 : ... def baseFunc1( self ): ... print "Base class Function" ... self.derivedFunc() ... >>> class derived( base1 ): ... def derivedFunc(self ): ... print "derived Func.." ... >>> b = base1() >>> b.baseFunc1() Traceback (most recent call last): File "", line 1, in ? TypeError: unbound method baseFunc1() must be called with base1 instance as first argument (got nothing instead) >>> d = derived() >>> d.baseFunc1() Base class Function derived Func.. >>> Cheers Dhanvi K From project5 at redrival.net Wed Oct 22 06:47:54 2003 From: project5 at redrival.net (Andrei) Date: Wed Oct 22 06:50:11 2003 Subject: [Tutor] Re: Python Class functionality idiosyncrasy.. In-Reply-To: <200310221550.58631.dhanvik@gmx.net> References: <200310221550.58631.dhanvik@gmx.net> Message-ID: dhanvik@gmx.net wrote: > Dear Friends, > The base class here is calling a function of the derived > class even befre the function of the derived class is > defined..A similar implementation in C++ would not even > compile.. My question is doesnt this implementation break No, it doesn't call it because no calling is performed at compile time. Note that Python has no compile-time checking of whether a method is defined or not. After all, what's not there at compile-time, can be there at runtime (dynamic as opposed to static languages). > some tennants of OO techniques ?? How can the base class > call functions of the derived class ?? It doesn't. I think you've done something wrong, here's my run: >>> class base1: ... def baseFunc1(self): ... print "Base class Function" ... self.derivedFunc() ... >>> class derived(base1): ... def derivedFunc(self): ... print "derived Func..." ... >>> b = base1() >>> b.baseFunc1() Base class Function Traceback (most recent call last): File "", line 1, in ? File "", line 4, in baseFunc1 AttributeError: base1 instance has no attribute 'derivedFunc' >>> d = derived() >>> d.baseFunc1() Base class Function derived Func... So I get an AttributeError, mentioning there's no derivedFunc. Seems about right to me (not sure why you got a typeerror). If we look at the dicts of b and de: >>> dir(b) ['__doc__', '__module__', 'baseFunc1'] >>> dir(d) ['__doc__', '__module__', 'baseFunc1', 'derivedFunc'] See, d has both methods. So when you call baseFunc1 on it, derivedFunc is there for baseFunc1 to access. The method is there at runtime and that's all baseFunc1 cares about. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dhanvik at gmx.net Wed Oct 22 07:06:18 2003 From: dhanvik at gmx.net (dhanvik@gmx.net) Date: Wed Oct 22 07:05:48 2003 Subject: [Tutor] Re: Python Class functionality idiosyncrasy.. In-Reply-To: References: <200310221550.58631.dhanvik@gmx.net> Message-ID: <200310221636.18552.dhanvik@gmx.net> Dear Andrei, thats right .. Dynamic Checking in Python is the reason that the base class is allowing the using of function that is yet to be defined any there else in the program. But the function can be accessed using the 'self' variable.. Any program that would be implemented this way would be bad programming and more than that bad designing of OO structure for the prgram. this was something that struck immediately as being wrong and coming form C++ background to Python, I found it blasphemous ( :)) )..after all the base class is something thats supposed to be the mother of all later classes and hence how can it call the functions of the derived class which hasnt even been defined... but some thgt and it falls in line with the basic line of thgt of python implementation.. - Dhanvi On Wednesday 22 October 2003 04:17 pm, Andrei wrote: > dhanvik@gmx.net wrote: > > Dear Friends, > > The base class here is calling a function of the > > derived class even befre the function of the derived > > class is > > > > defined..A similar implementation in C++ would not > > even compile.. My question is doesnt this > > implementation break > > No, it doesn't call it because no calling is performed at > compile time. Note that Python has no compile-time > checking of whether a method is defined or not. After > all, what's not there at compile-time, can be there at > runtime (dynamic as opposed to static languages). > > > some tennants of OO techniques ?? How can the base > > class call functions of the derived class ?? > > It doesn't. I think you've done something wrong, here's my run: > >>> class base1: > > ... def baseFunc1(self): > ... print "Base class Function" > ... self.derivedFunc() > ... > > >>> class derived(base1): > ... def derivedFunc(self): > ... print "derived Func..." > ... > > >>> b = base1() > >>> b.baseFunc1() > > Base class Function > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in baseFunc1 > AttributeError: base1 instance has no attribute > 'derivedFunc' > > >>> d = derived() > >>> d.baseFunc1() > > Base class Function > derived Func... > > So I get an AttributeError, mentioning there's no > derivedFunc. Seems about right to me (not sure why you > got a typeerror). If we look at the > > dicts of b and de: > >>> dir(b) > > ['__doc__', '__module__', 'baseFunc1'] > > >>> dir(d) > > ['__doc__', '__module__', 'baseFunc1', 'derivedFunc'] > > See, d has both methods. So when you call baseFunc1 on > it, derivedFunc is there for baseFunc1 to access. The > method is there at runtime and that's all baseFunc1 cares > about. From project5 at redrival.net Wed Oct 22 07:13:04 2003 From: project5 at redrival.net (Andrei) Date: Wed Oct 22 07:15:17 2003 Subject: [Tutor] Re: Python Class functionality idiosyncrasy.. In-Reply-To: <200310221636.18552.dhanvik@gmx.net> References: <200310221550.58631.dhanvik@gmx.net> <200310221636.18552.dhanvik@gmx.net> Message-ID: dhanvik@gmx.net wrote: > Dear Andrei, > thats right .. Dynamic Checking in Python is the reason that > the base class is allowing the using of function that is > yet to be defined any there else in the program. But the > function can be accessed using the 'self' variable.. > > Any program that would be implemented this way would be bad > programming and more than that bad designing of OO > structure for the prgram. > Hm... well, if it makes you feel more comfortable (and I suppose it would be better design too), you can define a dummy method in base1: >>> class base1: ... def baseFunc1(self): ... self.derivedFunc() ... def derivedFunc(self): ... """Dummy method, override by children""" ... pass -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From amk at amk.ca Wed Oct 22 07:17:42 2003 From: amk at amk.ca (amk@amk.ca) Date: Wed Oct 22 07:17:47 2003 Subject: [Tutor] General construction of alpha lists? In-Reply-To: References: Message-ID: <20031022111742.GB1331@rogue.amk.ca> On Tue, Oct 21, 2003 at 09:42:46PM -0400, Clay Shirky wrote: > So I have this bit of code: > class_groups[next:next+1] = [] 'del class_groups[next]' will also work. BTW, there is a random.shuffle() function which generates a permutation of a list, though it does it by randomly exchanging list elements. > and then have it print from A through L. Is there an easy way to specify a > list that is simply letters in order, or do I have to write out Easiest is probably list(string.ascii_letters), or list(string.ascii_lowercase). string.letters is the list of letters for the current locale, and therefore will usually include a bunch of accented characters; the .ascii_* variables are fixed. --amk From amk at amk.ca Wed Oct 22 07:27:55 2003 From: amk at amk.ca (amk@amk.ca) Date: Wed Oct 22 07:28:01 2003 Subject: [Tutor] Timing a loop In-Reply-To: <3F95F495.4050102@myrealbox.com> References: <3F95F495.4050102@myrealbox.com> Message-ID: <20031022112755.GC1331@rogue.amk.ca> On Tue, Oct 21, 2003 at 11:08:05PM -0400, Ben Mazer wrote: > I also looked at time.clock(), but I can't get that to display an > accurate readout, so I dont think that works (or Im not using it right). time.clock() displays CPU time for the process; for an I/O bound task like file creation, the process likely won't use much CPU -- it'll spend its time idly waiting for disk blocks to be read. You want time.time(), which returns "wall clock" time. Your results will therefore vary depending on your system's load; if cron runs in the middle of your timing interval, you'll measure a longer time, so usually people make several runs, discard outliers, and average them. > Any help you could provide on timing a loop would be really helpful. If you're using a big loop such as 'for i in range(100000)', you don't want to measure the time to create the list of 100000 integer objects, so you should write something like: L = range(100000) s = time.time() for i in L: .... e = time.time() print 'Total time:', e-s, 'sec'. > OT: How many files can reiserfs hold? I keep hitting "file system full" > limits when I get into large amounts of files (hundreds of thousands). Look at the output of os.statvfs('/filesystem'). files, ffree, favail are the number of free i-nodes. (Though on my ReiserFS partition they're all reported as 2**32-1 -- does ReiserFS have a fixed i-node limit?) --amk From amk at amk.ca Wed Oct 22 07:40:10 2003 From: amk at amk.ca (amk@amk.ca) Date: Wed Oct 22 07:40:36 2003 Subject: [Tutor] Re: Python Class functionality idiosyncrasy.. In-Reply-To: <200310221636.18552.dhanvik@gmx.net> References: <200310221550.58631.dhanvik@gmx.net> <200310221636.18552.dhanvik@gmx.net> Message-ID: <20031022114010.GD1331@rogue.amk.ca> On Wed, Oct 22, 2003 at 04:36:18PM +0530, dhanvik@gmx.net wrote: > Any program that would be implemented this way would be bad > programming and more than that bad designing of OO > structure for the prgram. No, it's not necessarily bad style. In fact it's fairly common to provide an abstract base class that isn't usable on its own; the user is supposed to subclass it and provide one method that implements some particular behaviour. A good example from the Python stdlib is the SocketServer module, which is used like this: from SocketServer import ForkingTCPServer class NNTPServer (ForkingTCPServer): def handle (self): ... process request ... --amk From dhanvik at gmx.net Wed Oct 22 07:51:20 2003 From: dhanvik at gmx.net (dhanvik@gmx.net) Date: Wed Oct 22 07:50:34 2003 Subject: [Tutor] Re: Python Class functionality idiosyncrasy.. In-Reply-To: <20031022114010.GD1331@rogue.amk.ca> References: <200310221550.58631.dhanvik@gmx.net> <200310221636.18552.dhanvik@gmx.net> <20031022114010.GD1331@rogue.amk.ca> Message-ID: <200310221721.20113.dhanvik@gmx.net> Abstract classes have the abstract keyword preceeding then and hence it makes sense for a reader of the program to know that the function would be implemented in the derived classes..but in this case theres no way of knowing whether the function was defined or not.. Hence, I was talking in terms of programming in Python. :-) On Wednesday 22 October 2003 05:10 pm, amk@amk.ca wrote: > On Wed, Oct 22, 2003 at 04:36:18PM +0530, dhanvik@gmx.net wrote: > > Any program that would be implemented this way would be > > bad programming and more than that bad designing of OO > > structure for the prgram. > > No, it's not necessarily bad style. In fact it's fairly > common to provide an abstract base class that isn't > usable on its own; the user is supposed to subclass it > and provide one method that implements some particular > behaviour. A good example from the Python stdlib is the > SocketServer module, which is used like this: > > from SocketServer import ForkingTCPServer > > class NNTPServer (ForkingTCPServer): > def handle (self): > ... process request ... > > --amk > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Wed Oct 22 08:07:38 2003 From: project5 at redrival.net (Andrei) Date: Wed Oct 22 08:09:52 2003 Subject: [Tutor] Re: Python Class functionality idiosyncrasy.. In-Reply-To: <200310221721.20113.dhanvik@gmx.net> References: <200310221550.58631.dhanvik@gmx.net> <200310221636.18552.dhanvik@gmx.net> <20031022114010.GD1331@rogue.amk.ca> <200310221721.20113.dhanvik@gmx.net> Message-ID: dhanvik@gmx.net wrote: > Abstract classes have the abstract keyword preceeding then > and hence it makes sense for a reader of the program to > know that the function would be implemented in the derived > classes..but in this case theres no way of knowing whether > the function was defined or not.. That's what docstrings are for :). Providing dummy methods which are just meant to be implemented by subclasses is extremely common practice indeed; even I do it :). -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From ms_barry2000 at yahoo.com Wed Oct 22 08:27:37 2003 From: ms_barry2000 at yahoo.com (=?iso-8859-1?q?Marc=20Barry?=) Date: Wed Oct 22 08:27:42 2003 Subject: [Tutor] Bit Strings In-Reply-To: <005801c39852$07468c30$6600a8c0@winxp> Message-ID: <20031022122737.46247.qmail@web11701.mail.yahoo.com> Tim: Here is an example script of what I think you were looking for. It is fairly simple and doesn't use any recursion. See explanation after script. #---- def decToBin(dec_number): bit_string = "" # The following just does simple decimal to binary conversion. if(dec_number == 0): bit_string = "0" else: while(dec_number != 0): if(dec_number % 2 == 1): bit_string = "1" + bit_string dec_number = dec_number - 1 dec_number = dec_number / 2 else: bit_string = "0" + bit_string dec_number = dec_number / 2 return bit_string def createBitStrings(bit_string_length): bit_strings = [] bit_string = "" # This just here to illustrate a point that the maximum decimal number # represented by n bits is (2^n)-1. We have to add 1 below when using # range because it generates values in the range [start, end). max_decimal_number = (2**bit_string_length) - 1 # This for loop just loops through all the decimal numbers that can be # represented by n bits. for i in range(0, max_decimal_number + 1): bit_string = decToBin(i) # At this point the bit string needs to be padded with 0's so # that it contains n bits. while(len(bit_string) < bit_string_length): bit_string = "0" + bit_string bit_strings.append(bit_string) return bit_strings # Print the list of bit strings. print createBitStrings(4) #--- The output from the above script is: ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'] Basically, what I have done is created two functions called decToBin and createBitStrings. The decToBin function takes as input a decimal number and convertes it to it binary string representation. The createBitStrings function takes the length of the bit string for which all possible combinations should be generated. It just loops through all possible decimal numbers, converts them to binary and pads with 0's as necessary so that you have n bits. I hope this helps. Regards, Marc --- "Timothy M. Brauch" wrote: > There has to be an easy way to do this that I am just not seeing. I am > trying to create all bit strings of length n. Right now my code is as > follows: > > bitStrings = [] > for a0 in [0,1]: > for a1 in [0,1]: > for a2 in [0,1]: > oneString = str(a0)+str(a1)+str(a2) > bitStrings.append(oneString) > print bitStrings > > I know this is ugly and when I need longer strings, say n = 10, the code > gets way too repetitive with 10 nested for loops. Surely there is an easier > way to do this, but I just can't figure it out. I have a function that will > generate the above functions, but it is uglier and probably way not the > correct way to go about this. > > def generator(n): > tb = " " > stringMaker = "" > print "bitStrings = []" > for i in xrange(0,n+1): > print i*tb + "for a"+str(i)+" in [0,1]:" > stringMaker = stringMaker + "str"+chr(40)+"a"+str(i)+chr(41)+chr(43) > stringMaker = stringMaker[:-1] #strip the last chr(43) > print (i+1)*tb + "oneString = "+stringMaker > print (i+1)*tb + "bitStrings.append(oneString)" > print "print bitStrings" > > > Any suggestions? > > - Tim > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.528 / Virus Database: 324 - Release Date: 10/17/2003 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ________________________________________________________________________ Want to chat instantly with your online friends? Get the FREE Yahoo! Messenger http://mail.messenger.yahoo.co.uk From op73418 at mail.telepac.pt Wed Oct 22 06:58:34 2003 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Oct 22 08:29:07 2003 Subject: [Tutor] Python Class functionality idiosyncrasy.. In-Reply-To: <200310221550.58631.dhanvik@gmx.net> References: <200310221550.58631.dhanvik@gmx.net> Message-ID: <9sncpv4nu6vt07qlb89c9rl3l95rgolvq0@4ax.com> On Wed, 22 Oct 2003 15:50:58 +0530, you wrote: >Dear Friends, > While just playing arnd with Python .. I just came across >this curious implementation of Python Object Oriented >Techniques.. > >The base class here is calling a function of the derived >class even befre the function of the derived class is >defined..A similar implementation in C++ would not even >compile.. My question is doesnt this implementation break >some tennants of OO techniques ?? What tenets (not tennants I believe :-) are being broken? >How can the base class >call functions of the derived class ?? > I'm not sure I understand your question. Your example below shows how that is done. >>>> class base1 : >... def baseFunc1( self ): >... print "Base class Function" >... self.derivedFunc() >... >>>> class derived( base1 ): >... def derivedFunc(self ): >... print "derived Func.." >... >>>> b = base1() >>>> b.baseFunc1() >Traceback (most recent call last): > File "", line 1, in ? >TypeError: unbound method baseFunc1() must be called with >base1 instance as first argument (got nothing instead) > >>>> d = derived() >>>> d.baseFunc1() >Base class Function >derived Func.. >>>> > This is called the template pattern. You have a base class providing some functionality implemented in terms of some other, *not* implemented methods. This class is not meant to be intantiated by itself, it is what is called an abstract class, and it's customary to put: class AbstractClass(object): def __init__(self, *args, **kwargs): raise NotImplementedError("Class not to be intantiated.") ... What you do is derive from that class and implement the missing methods. The example you gave explains it: The base class implements a method baseFunc1 in terms of derivedFunc. If you call it on a base1 instance and it will obviously fail because there is no such method. But on a derived instance, it does not fail because you have implemented the derivedFunc method. Somewhere in the net there are some slides by Alex Martelli (the martellibot) explaining the template pattern. I'm having trouble with the internet right now, but I'll get back to you if I can get hold of the url. Hope it helps, with my best regards, G. Rodrigues From clay at shirky.com Wed Oct 22 08:31:49 2003 From: clay at shirky.com (Clay Shirky) Date: Wed Oct 22 08:31:30 2003 Subject: [Tutor] General construction of alpha lists? In-Reply-To: <20031022111742.GB1331@rogue.amk.ca> Message-ID: > On Tue, Oct 21, 2003 at 09:42:46PM -0400, Clay Shirky wrote: >> So I have this bit of code: >> class_groups[next:next+1] = [] > > 'del class_groups[next]' will also work. ...and, as I later figured out, 'print class_groups.pop(next)' actually combines two lines into one. I thought perl was the one where there was more than one way to do it? ;) > BTW, there is a random.shuffle() function which generates a permutation of a > list, though it does it by randomly exchanging list elements. Right, this isn't so much a pressing need as me exploring the language. > Easiest is probably list(string.ascii_letters), Perfect, thanks. The chr(next+65) thing had also occurred to me, but seemed too bletcherous. -c > list(string.ascii_lowercase). string.letters is the list of letters for the > current locale, and therefore will usually include a bunch of accented > characters; the .ascii_* variables are fixed. > > --amk > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rhseabrook at aacc.edu Wed Oct 22 09:12:24 2003 From: rhseabrook at aacc.edu (Seabrook, Richard) Date: Wed Oct 22 09:12:25 2003 Subject: FW: [Tutor] Bit Strings [an iterative approach] Message-ID: <74DAD2F23F03F7438D9BE3436C6846F701290940@AACC-MAIL.aacc.cc.md.us> -----Original Message----- From: Timothy M. Brauch [mailto:tbrauch@mindless.com] Sent: Wed 10/22/2003 3:48 AM To: Python Tutor Cc: Subject: Re: [Tutor] Bit Strings [a recursive approach] Whilst trying to find all bit strings of a certain length, I struggled. Danny Yoo was helpful with: > Have you tried a recursive approach? It might be useful to outline how to > solve this recursively, so here goes! *grin* ============================ I'd not give up the iterative approach so quickly. As others have noted, you can generate the set of values you want but merely counting up to 2^N. However, the values seldom have leading 0 padding to make them N-digit binary numbers, easily convertable to bit-strings, so the old-fashioned solution is to start counting at 2^N and count up to 2^(N+1)-1, converting the right-most N digits in each case. For example, to get all bit strings of size 5, start at 2^5 = 32 and count up to 2^(5+1)-1 = 63 converting the right-most 5 digits, like this: 100000 100001 100010 100011 ... ... 111111 Dick S. From druidmatt at yahoo.com Wed Oct 22 10:47:46 2003 From: druidmatt at yahoo.com (Matt Hehman) Date: Wed Oct 22 10:47:58 2003 Subject: [Tutor] Re: Request for code critique Message-ID: <20031022144746.48588.qmail@web10309.mail.yahoo.com> Well, here goes. Some of the comments wrapped, as did two of the longer lines, which I stuck in parentheses, so this should be about right. Besides anything really glaring, what would I need to do if this was going to be a mere feature of a much longer program? ##retrieve list of known primes import shelve d=shelve.open('primesfile') primes=d['primesfile'] ##defines function for finding common factors def Euclid(a,b): while b>0: a,b=b,a%b return a ##user inputs number for testing (bignum=input("Enter a number to evaluate for primeness.")) ##upper limit for primes to be tested ceiling=int(bignum**0.5) ##new primes are calculated if current list is ##insufficient if primes[-1]+10: limit=int(candidates[0]**0.5) if candidates[0]%primes[n]==0: del candidates[0] n=0 n=n+1 if len(candidates)>0: result.append(candidates[0]) del candidates[0] n=1 ##newly generated primes are saved to file primes.extend(result) d['primesfile']=primes d.close ##primes generated/retrieved are tested as possible ##factors ##progressively slower with larger numbers - next ##planned revision factors=[] while primes and primes[0]1: factors.append(Euclid(bignum,primes[0])) del primes[0] if factors: (print bignum,"is not a prime. Its prime factors up to its square root include:",factors) else: print bignum,"is prime." __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From m.evanetich at att.net Wed Oct 22 10:49:38 2003 From: m.evanetich at att.net (m.evanetich@att.net) Date: Wed Oct 22 10:49:45 2003 Subject: [Tutor] Question about tkFileDialog Message-ID: <102220031449.3797.4bbd@att.net> I am attempting to write a simple data consolidation script that opens files in subtrees and combines the data into a single file at the root. The script starts by asking the user to specify a subtree. Currently I am stumped by the behavior of tkFileDialog. When I try: >>> import tkFileDialog >>> projectFolder = tkFileDialog.askdirectory(initialdir='c:/projectDev', ... mustexist=1, ... title='Choose root directory for the desired project.') >>> print projectFolder C:/projectDev/Foo I get the desired result, but I also get a small application named tk on my desktop and with a taskbar button that I cannot close as a side effect. It is disconcerting and I have not found a way to banish it. Can anyone point me to the relevant documentation or provide advice? Thank you. -- Mark Evanetich > 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: this is ugly (Andrei) > 2. Request for code critique (Matt Hehman) > 3. Re: Request for code critique (Clay Shirky) > 4. Re: Request for code critique (Andrei) > 5. can someone explain to me how this works (Conrad Koziol) > 6. Re: can someone explain to me how this works [comparsion > functions and sort()] (Danny Yoo) > 7. can someone explain to me how this works (Conrad Koziol) > 8. Re: 2nd Python Book (Erik Price) > 9. Nested Lists / Array Module (Harm_Kirchhoff@mail.digital.co.jp) > 10. Re: Nested Lists / Array Module (Andrei) > 11. Re: Nested Lists / Array Module (Danny Yoo) > 12. General construction of alpha lists? (Clay Shirky) > 13. Timing a loop (Ben Mazer) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 22 Oct 2003 00:05:26 +0200 > From: Andrei > Subject: [Tutor] Re: this is ugly > To: tutor@python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii; format=flowed > > Alan Gauld wrote: > >>Can line 3 of the following be improved (especially since I might > > > > want > > > >>to search for even more strings within each line): > >> > >>myfile=open(r'F:\logs\myfile.txt', 'r') > >>for line in myfile.readlines(): > >> if line.find("KeC 923") != -1 or line.find("ZEF 156") != -1 or > >>line.find("pBX 88347") != -1 or line.find("FZX 17255") != -1: > >> #code if found > > > > > > Yes use a regular expression. You can combine conditions in one > > expression and it will only search the string once instead of > > once per condition. > > > > I'll leave it to someone else to explain how to combine the > > regexs! I'm going to bed and my brain is tired.... :-) > > Well, here's a RE which would match any of those things: > > KeC 923|ZEF 156|pBX 88347|FZX 17255 > > I don't know if evaling that regex would be faster/easier than using the > find methods, especially not with one of the shortcut notations > mentioned earlier in this thread. Perhaps a more generic RE would be in > order, e.g.: > > \S{3}\s\d{3,5} > > which (if compiled with the IGNORECASE flag) matches any sequence of 3 > letters followed by a space and 3 to 5 digits. Of course I don't know > the type of input, perhaps this would match more than desired. > > -- > Yours, > > Andrei > > ===== > Mail address in header catches spam. Real contact info (decode with rot13): > cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V > ernq gur yvfg, fb gurer'f ab arrq gb PP. > > > > > > ------------------------------ > > Message: 2 > Date: Tue, 21 Oct 2003 15:10:23 -0700 (PDT) > From: Matt Hehman > Subject: [Tutor] Request for code critique > To: tutor@python.org > Message-ID: <20031021221023.98586.qmail@web10309.mail.yahoo.com> > Content-Type: text/plain; charset=us-ascii > > I've written a program of about 40 lines including > comments. I am teaching myself to program in my spare > time, working through the various online tutorials. I > started with "Instant Hacking" by Hetland and built on > the example to calculate prime numbers. Basically, I > looked for better ways to do it, then expanded its > functionality by throwing code at it and seeing what > stuck. Before I try to refine it any further, I think > it would be good to get some feedback before I develop > any bad habits. Rather than clog your inboxes by way > of asking for a big favor, any volunteers, please > e-mail me directly. > > Thanks, > Matt Hehman > > __________________________________ > Do you Yahoo!? > SBC Yahoo! DSL - Now only $29.95 per month! > http://sbc.yahoo.com > > > > ------------------------------ > > Message: 3 > Date: Tue, 21 Oct 2003 18:19:24 -0400 > From: Clay Shirky > Subject: Re: [Tutor] Request for code critique > To: Matt Hehman , > Message-ID: > Content-Type: text/plain; charset="US-ASCII" > > > I've written a program of about 40 lines including > > comments. I am teaching myself to program in my spare > > time, working through the various online tutorials. I > > started with "Instant Hacking" by Hetland and built on > > the example to calculate prime numbers. Basically, I > > looked for better ways to do it, then expanded its > > functionality by throwing code at it and seeing what > > stuck. Before I try to refine it any further, I think > > it would be good to get some feedback before I develop > > any bad habits. Rather than clog your inboxes by way > > of asking for a big favor, any volunteers, please > > e-mail me directly. > > As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to > post it here than to do it via CC. That sort of thing is what tutor is good > for. > > -clay > > > > > ------------------------------ > > Message: 4 > Date: Wed, 22 Oct 2003 00:21:21 +0200 > From: Andrei > Subject: [Tutor] Re: Request for code critique > To: tutor@python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii; format=flowed > > Clay Shirky wrote: > > >>I've written a program of about 40 lines including > >>comments. I am teaching myself to program in my spare > >>time, working through the various online tutorials. I > >>started with "Instant Hacking" by Hetland and built on > >>the example to calculate prime numbers. Basically, I > >>looked for better ways to do it, then expanded its > >>functionality by throwing code at it and seeing what > >>stuck. Before I try to refine it any further, I think > >>it would be good to get some feedback before I develop > >>any bad habits. Rather than clog your inboxes by way > >>of asking for a big favor, any volunteers, please > >>e-mail me directly. > > > > > > As a fellow newbie, I'd love to see it, and I'm sure it makes more sense to > > post it here than to do it via CC. That sort of thing is what tutor is good > > for. > > I agree, I can fit more than 50 lines of code on my screen so 40 doesn't > seem like such a big problem. Make sure your mail interface doesn't > break the code though. > > -- > Yours, > > Andrei > > ===== > Mail address in header catches spam. Real contact info (decode with rot13): > cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V > ernq gur yvfg, fb gurer'f ab arrq gb PP. > > > > > > ------------------------------ > > Message: 5 > Date: Tue, 21 Oct 2003 15:42:42 -0700 > From: Conrad Koziol > Subject: [Tutor] can someone explain to me how this works > To: tutor@python.org > Message-ID: <1066776162.5035.4.camel@quercus> > Content-Type: text/plain > > Hey thanks for the tips !!! > > def compare(a,b): > if a[1]>b[1]: return 0 > else: return -1 > > i tried this out and it works, but i dont understand the logic behind it > :( > can someone help me out > > i also dont get how it compares all the tuples in a list. Dont you need to enter > in two values not just one list????? > > > > ------------------------------ > > Message: 6 > Date: Tue, 21 Oct 2003 16:13:22 -0700 (PDT) > From: Danny Yoo > Subject: Re: [Tutor] can someone explain to me how this works > [comparsion functions and sort()] > To: Conrad Koziol > Cc: tutor@python.org > Message-ID: > > Content-Type: TEXT/PLAIN; charset=US-ASCII > > > > On Tue, 21 Oct 2003, Conrad Koziol wrote: > > > Hey thanks for the tips !!! > > > > def compare(a,b): > > if a[1]>b[1]: return 0 > > else: return -1 > > > > i tried this out and it works, but i dont understand the logic behind it > > :( can someone help me out > > Hi Conrad, > > A "comparison function" is something that takes two things, and checks to > see if one is smaller than another. In math notation: > > compare(a,b) = { -1 if a < b > 0 if a == b > 1 if a > b > } > > The important thing to see is that a comparison function is not meant to > be a "boolean" true-false thing: it's meant to return either a positive, > zero, or negative value. > > Is this what's confusing, or is it something else? Please feel free to > ask more questions about this, as it is definitely a confusing topic when > we first see it. > > > > > i also dont get how it compares all the tuples in a list. Dont you need > > to enter in two values not just one list????? > > Yes, this would be true if we were directly calling compare() on the list > itself. However, that's not what's happening: instead, we're calling > sort, and sort() itself is calling compare() on pairs of elements on our > list. > > > Here's a concrete toy example of a similar situation: > > ### > >>> def applyOnList(function, L): > ... """Destructivly applies a 'function' on the list 'L'.""" > ... for index, element in enumerate(L): > ... L[index] = function(element) > ... > >>> def square(x): return x * x > ... > >>> numbers = range(10) > >>> applyOnList(square, numbers) > >>> numbers > [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] > ### > > In this case, we've written a function called applyOnList() that takes in > a function, as well as a list of things. Notice that the function we pass > in isn't being called on the whole list, but only on single elements of > that list. > > > sort() does something somewhat similar when it takes in that comparison > function. sort() uses it as a helper toward some greater goal --- sorting > things --- but doesn't need to try applying it to the whole list at once. > > > Hope that made some sort of sense. *grin* Please feel free to ask more > questions: if you'd like, we can talk about how comparsion functions > actually help sort() figure out how to sort. > > > > > ------------------------------ > > Message: 7 > Date: Tue, 21 Oct 2003 15:42:42 -0700 > From: Conrad Koziol > Subject: [Tutor] can someone explain to me how this works > To: tutor@python.org > Message-ID: <1066776162.5035.4.camel@quercus> > Content-Type: text/plain > > Hey thanks for the tips !!! > > def compare(a,b): > if a[1]>b[1]: return 0 > else: return -1 > > i tried this out and it works, but i dont understand the logic behind it > :( > can someone help me out > > i also dont get how it compares all the tuples in a list. Dont you need to enter > in two values not just one list????? > > > > ------------------------------ > > Message: 8 > Date: Tue, 21 Oct 2003 20:43:41 -0400 > From: Erik Price > Subject: Re: [Tutor] 2nd Python Book > To: John Duarte > Cc: tutor@python.org > Message-ID: > Content-Type: text/plain; charset=US-ASCII; format=flowed > > > On Monday, October 20, 2003, at 06:37 PM, John Duarte wrote: > > > I have seen recommendations for a first Python book, ie Alan Guald's > > Learn to > > Program Using Python, and Lutz & Asher's Learning Python. (Which are > > both > > terrific books!) > > > > I was wondering if anyone could recommend a '2nd book'. > > The Python Cookbook. You already know Python, this book teaches you > how to do specific tasks or sophisticated programming idioms specific > to Python. It's one of my favorite Python books. > > > I was glancing through Deitel & Deitel's How to Program Python, and it > > looks > > very thorough. Are their any opinions about this book specifically. > > I didn't even know these guys had a Python book. Neat. > > > > Erik > > > > > ------------------------------ > > Message: 9 > Date: Wed, 22 Oct 2003 09:07:57 +0900 > From: Harm_Kirchhoff@mail.digital.co.jp > Subject: [Tutor] Nested Lists / Array Module > To: tutor@python.org > Message-ID: > > .com> > > Content-Type: text/plain; charset="us-ascii" > > Python supports nested lists, which is very nice and can be used for very > simple databases. > > However, I could not find a way to write nested lists to files & retrieve > them easily. > The .writelines() method expects a string as an argument. > > Is there a method to dump any list on disk & read it back, or is it > necessary to code this task ? > > The array module seems to have such method, however, I could not find > sufficient code examples to understand how the array module works. The > Python Library Reference mentions the .fromfile() and .tofile() methods, > does anyone have experience with the array module, especially whether it > allows to write & retrieve nested arrays without problems ? Could you pass > me some sample code ? > > > Harm > > > > > ------------------------------ > > Message: 10 > Date: Wed, 22 Oct 2003 02:33:27 +0200 > From: Andrei > Subject: [Tutor] Re: Nested Lists / Array Module > To: tutor@python.org > Message-ID: > Content-Type: text/plain; charset=us-ascii; format=flowed > > Harm_Kirchhoff@mail.digital.co.jp wrote: > > Python supports nested lists, which is very nice and can be used for very > > simple databases. > > > > However, I could not find a way to write nested lists to files & retrieve > > them easily. > > The .writelines() method expects a string as an argument. > > > > Is there a method to dump any list on disk & read it back, or is it > > necessary to code this task ? > > Not too long ago a similar question (or was it the same?) was on the list > I believe. You can either pickle or convert your list to a string using > str(), > e.g. str(MyList). It doesn't matter how deep that list is. > > > > -- > Yours, > > Andrei > > ===== > Mail address in header catches spam. Real contact info (decode with rot13): > cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V > ernq gur yvfg, fb gurer'f ab arrq gb PP. > > > > > > ------------------------------ > > Message: 11 > Date: Tue, 21 Oct 2003 17:54:28 -0700 (PDT) > From: Danny Yoo > Subject: Re: [Tutor] Nested Lists / Array Module > To: Harm_Kirchhoff@mail.digital.co.jp > Cc: tutor@python.org > Message-ID: > > Content-Type: TEXT/PLAIN; charset=US-ASCII > > > > On Wed, 22 Oct 2003 Harm_Kirchhoff@mail.digital.co.jp wrote: > > > Python supports nested lists, which is very nice and can be used for very > > simple databases. > > > > However, I could not find a way to write nested lists to files & > > retrieve them easily. The .writelines() method expects a string as an > > argument. > > > > Is there a method to dump any list on disk & read it back, or is it > > necessary to code this task ? > > > Hi Harm, > > Yes. For simple cases, the 'shelve' module can help to "serialize" > these nested structures to and from disk. "Serialization" is a term we > use to transform arbitrary Python objects to byte strings, and it's pretty > easy to do in Python. > > In fact, we talked about this about a week ago: > > http://mail.python.org/pipermail/tutor/2003-October/025741.html > > The example at that link uses only a flat list, but 'shelve' should work > with lists in lists too. > > > If you have more questions, please feel free to ask. Good luck! > > > > > ------------------------------ > > Message: 12 > Date: Tue, 21 Oct 2003 21:42:46 -0400 > From: Clay Shirky > Subject: [Tutor] General construction of alpha lists? > To: > Message-ID: > Content-Type: text/plain; charset="US-ASCII" > > So I have this bit of code: > > class_groups = [ 'A', 'B', 'C', 'D', 'E' ] > > while class_groups: > next = random.choice( range( len(class_groups) )) > print class_groups[next] > class_groups[next:next+1] = [] > > which will give me some random permutation of the items in the list > class_groups. > > Next stop, making it possible to generate an alphabetical list, based on the > array number. I'd like to do something like > > class_groups = range(12) > > and then have it print from A through L. Is there an easy way to specify a > list that is simply letters in order, or do I have to write out > > alpha = [ 'A', 'B', ... 'Z', 'a', 'b', ... 'z' ] > > Thanks > > -clay > > > > > ------------------------------ > > Message: 13 > Date: Tue, 21 Oct 2003 23:08:05 -0400 > From: Ben Mazer > Subject: [Tutor] Timing a loop > To: tutor@python.org > Message-ID: <3F95F495.4050102@myrealbox.com> > Content-Type: text/plain; charset=us-ascii; format=flowed > > I have written a small script that creates a bunch of small text files. > I'm doing this because I want to benchmark file creation/deletion times > on different file systems. > > Im looking right now about how to time how long it takes to create the > files. I looked at the Timeit() module, and that doesn't seem to work, > its for small algorithms. > > I also looked at time.clock(), but I can't get that to display an > accurate readout, so I dont think that works (or Im not using it right). > > I know I could use the UNIX "time" command, but it would be nice if > Python had a built in function. They probably do, but I can't find it. :P > > Any help you could provide on timing a loop would be really helpful. > > OT: How many files can reiserfs hold? I keep hitting "file system full" > limits when I get into large amounts of files (hundreds of thousands). > > Thanks. > -- > /"\ Ben Mazer > \ / > X ASCII RIBBON CAMPAIGN AGAINST HTML MAIL > / \ > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 3, Issue 37 > ************************************ From m.evanetich at att.net Wed Oct 22 11:22:28 2003 From: m.evanetich at att.net (m.evanetich@att.net) Date: Wed Oct 22 11:22:33 2003 Subject: [Tutor] Re: Tutor Digest, Vol 3, Issue 40 Message-ID: <102220031522.6599.73c4@att.net> My apology for including the digest. It was a newbie mistake. -- Mark Evanetich From dyoo at hkn.eecs.berkeley.edu Wed Oct 22 12:25:30 2003 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Oct 22 12:26:16 2003 Subject: [Tutor] Bit Strings [a recursive approach / Herbert Wilf's Algorithms and Complexity] In-Reply-To: <009a01c39870$f4402730$6600a8c0@winxp> Message-ID: > I guess I just didn't realize what I was doing by hand would have worked > if I had coded it correctly. And, the nice thing about this is that it > should be pretty easy to extend the idea if my strings need to have more > characters. Just a few more base cases and the else:return needs to be > have a few more lines. Thanks. Hi Timothy, Yes, the recursive approach generalizes easily beyond binary strings. So you should be able to get this done well before the weekend. *grin* > P.S. I guess it is the mathematician in me that doesn't like recursively > defined functions. We tend to like closed form things better. And it > was my stumbling block in my algorithm classes. Although, recursive is > often much more elegant... By the way, I just discovered that the mathematician Herbert Wilf has made his book "Algorithms and Complexity", freely available from his web site! http://www.cis.upenn.edu/%7Ewilf/AlgComp2.html It's a nice 2**6 pages of quirky mathy goodness. Chapter 2 gives a talk about recursive algorithms, so this is not totally off topic. *grin* I wish I had seen it earlier, as well as his other book "generatingfunctionology", which is also available off his web site. From python at dhumketu.cjb.net Wed Oct 22 06:57:59 2003 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Wed Oct 22 13:36:35 2003 Subject: [Tutor] Re: Nested Lists / Array Module In-Reply-To: References: Message-ID: <20031022105759.GA219@dhumketu.homeunix.net> +-- Harm_Kirchhoff@mail.digital.co.jp [python-tutor] [22-10-03 05:37 IST]: | Python supports nested lists, which is very nice and can be used for very | simple databases. | | However, I could not find a way to write nested lists to files & retrieve | them easily. | The .writelines() method expects a string as an argument. | | Is there a method to dump any list on disk & read it back, or is it | necessary to code this task ? | | The array module seems to have such method, however, I could not find | sufficient code examples to understand how the array module works. The | Python Library Reference mentions the .fromfile() and .tofile() methods, | does anyone have experience with the array module, especially whether it | allows to write & retrieve nested arrays without problems ? Could you pass | me some sample code ? | | | Harm import pickle f=open('test','w+') a=[[1,2,3,4],[1,2,[123]]] pickle.dump(a,f) f.seek(0) b=pickle.load(f) print a,b -- With Best Regards, Shantanoo Mahajan From project5 at redrival.net Wed Oct 22 13:59:41 2003 From: project5 at redrival.net (Andrei) Date: Wed Oct 22 14:02:01 2003 Subject: [Tutor] Re: Request for code critique In-Reply-To: <20031022144746.48588.qmail@web10309.mail.yahoo.com> References: <20031022144746.48588.qmail@web10309.mail.yahoo.com> Message-ID: Matt Hehman wrote: > Well, here goes. Some of the comments wrapped, as did > two of the longer lines, which I stuck in parentheses, > so this should be about right. Besides anything > really glaring, what would I need to do if this was > going to be a mere feature of a much longer program? For one thing, wrap everything up in classes or at the very least functions. If you import your module in a larger program, everything is executed at import time so the larger program can't really use it. Not to mention that if you program without classes (and even more so when you program without functions), the results are unmaintainable. > ##new primes are calculated if current list is > ##insufficient > if primes[-1]+1 candidates=range((primes[-1]+2),ceiling+1,2) For the sake of clarity, I think it would be better if you added 1 to ceiling the first time you defined it. > n=1 > result=[] Why do you need results? You could just as well work directly on your primes list. Btw, I prefer spaces to the left and right of equal signs and to the richt of commas; makes code easier to read. > while candidates: > limit=int(candidates[0]**0.5) > while primes[n]<=limit and len(candidates)>0: > limit=int(candidates[0]**0.5) > if candidates[0]%primes[n]==0: > del candidates[0] > n=0 > n=n+1 > if len(candidates)>0: > result.append(candidates[0]) > del candidates[0] > n=1 You should look into the pop() method which deletes an item and returns it as well. Also I think that your while-solution is not as pythonic as it could be (making it harder to follow for me). It's more common to use a break statement than to define a loop variable outside the while-loop: # no limit variable outside the while loop while len(candidates)>0: limit = int(candidates[0] ** 0.5) if primes[n]>limit: # stops the loop break # the rest of your code Regardless of this, I'm not sure that deleting items is the fastest possible way to do it. In fact, I'm tempted to think that looping through the items in candidates would be faster (and IMO looks better too), using a for-loop: for candidate in candidates: # find out if the candidate is indeed a prime limit = int(candidate ** 0.5) for prime in primes: if prime > limit: # we've found a new prime, go to next one primes.append(candidate) break elif candidate % prime == 0: # candidate is not a prime, go to next one break This does assume that you start out with primes containing at least [2, 3] and is 50% shorter than your solution (not counting comments). Bonus points if you can get that in a list comprehension :). > ##progressively slower with larger numbers - next > ##planned revision > factors=[] > while primes and primes[0] if Euclid(bignum,primes[0])>1: > factors.append(Euclid(bignum,primes[0])) > del primes[0] Again, I think a for-loop might be more appropriate here, looping "for prime in primes". -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jim_938 at hotmail.com Wed Oct 22 14:18:43 2003 From: jim_938 at hotmail.com (Jimmy verma) Date: Wed Oct 22 14:18:48 2003 Subject: [Tutor] xml question Message-ID: Hello, I am getting caught in a problem for which i need some suggestions. I have an xml file like

<\dir> <\XYZ> I want to make two tables out of this: one is 'header' and other is 'dir'. Tables can be in the form of list: like header = [1,2,0,0,0] dir = [ [0,1,2,3], [4,5,6,7] ] I just want the values in the tables not the tags. Is there some pythonic way of doing it. Thanks in advance. Regards, J+ _________________________________________________________________ Special offer from American Express.Don't miss out. http://server1.msn.co.in/features/amex/index.asp Apply now! From klappnase at freenet.de Wed Oct 22 14:27:07 2003 From: klappnase at freenet.de (Michael Lange) Date: Wed Oct 22 14:25:06 2003 Subject: [Tutor] Question about tkFileDialog In-Reply-To: <102220031449.3797.4bbd@att.net> References: <102220031449.3797.4bbd@att.net> Message-ID: <20031022202707.54488a8d.klappnase@freenet.de> On Wed, 22 Oct 2003 14:49:38 +0000 m.evanetich@att.net wrote: > I am attempting to write a simple data consolidation script that opens files > in subtrees and combines the data into a single file at the root. The script > starts by asking the user to specify a subtree. Currently I am stumped by > the behavior of tkFileDialog. When I try: > > >>> import tkFileDialog > >>> projectFolder = tkFileDialog.askdirectory(initialdir='c:/projectDev', > ... mustexist=1, > ... title='Choose root directory > for the desired project.') > >>> print projectFolder > C:/projectDev/Foo > > I get the desired result, but I also get a small application named tk on my > desktop and with a taskbar button that I cannot close as a side effect. It > is disconcerting and I have not found a way to banish it. Can anyone point > me to the relevant documentation or provide advice? > > Thank you. > Hi, the File Dialog window is called as a Toplevel window of a Tk window that is usually defined before. If you haven't defined this root window before, it is automatically created (otherwise an exception had to be raised). I must admit I have never tried this before, but that seems to be what happens here. If you don't want to see the root window, try this: >>> from Tkinter import * >>> import tkFileDialog >>> r = Tk() >>> r.withdraw()# removes r from the screen '' >>> f = tkFileDialog.askdirectory() >>>etc. Hope this helps Michael From project5 at redrival.net Wed Oct 22 14:34:51 2003 From: project5 at redrival.net (Andrei) Date: Wed Oct 22 14:37:03 2003 Subject: [Tutor] Re: Request for code critique In-Reply-To: References: <20031022144746.48588.qmail@web10309.mail.yahoo.com> Message-ID: Andrei wrote: > Matt Hehman wrote: > > for candidate in candidates: > # find out if the candidate is indeed a prime > limit = int(candidate ** 0.5) > for prime in primes: > if prime > limit: > # we've found a new prime, go to next one > primes.append(candidate) > break > elif candidate % prime == 0: > # candidate is not a prime, go to next one > break > > This does assume that you start out with primes containing at least [2, > 3] and is 50% shorter than your solution (not counting comments). Bonus > points if you can get that in a list comprehension :). Just because I like torturing myself (don't ask), I ended up writing the comprehension too: [ primes.append(C) for C in candidates if not [1 for P in primes if not C%P ] ] Much shorter, but I should point out that when running up to 100000000, the comprehension is 30-50 times slower than the explicit for-loops :). The while loop in Matt's code is ~3 times slower than the for-loops. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alan.gauld at blueyonder.co.uk Wed Oct 22 14:46:39 2003 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Oct 22 14:45:50 2003 Subject: [Tutor] Python Class functionality idiosyncrasy.. References: <200310221550.58631.dhanvik@gmx.net> Message-ID: <011201c398cc$d416f310$6401a8c0@xp> > The base class here is calling a function of the derived > class even befre the function of the derived class is > defined.. Actually its not actually calling it at that point. Its just a reference stored for future resolution. It doesn't actually call the function until the method gets called. > A similar implementation in C++ would not even > compile.. In fact you can do this in C++ but it involves some clever magic using templates. Stroustrup gives an example in his book "The Design & Evolution of C++" > My question is doesnt this implementation break > some tennants of OO techniques ?? How can the base class > call functions of the derived class ?? It isn't in an OO sense doing that, its simply sending a message to itself. The fact that the implementation is in the baseclass is irrelevant. It simply means that the class cannot be safely used on its own. This technique is most commonly used in the OO style known as "mixin" programming. This technique is possible in many OO languages including C++, Lisp, Smalltalk (via class methods I think) and I suspect Objective C plus others - almost any dynamically dispatched message based implenentation. Its a good example of the very real difference between sending a message and calling a function! PS IN Java you could implement the same design trick by defining an interface... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From tpc at csua.berkeley.edu Wed Oct 22 14:52:12 2003 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Oct 22 14:52:36 2003 Subject: [Tutor] xml question In-Reply-To: Message-ID: <20031022114638.R49312-100000@localhost.name> hi Jimmy, If you want to extract the PCDATA from your XML file you may want to look at xmllib: http://www.python.org/doc/current/lib/module-xmllib.html I have experience parsing XHTML with HTMLParser.HTMLParser and I imagine this class shouldn't be that much different. Here's an example of an XHTML Parser that ignores stuff inside