From stygian at tesco.net Tue Feb 1 00:01:39 2005 From: stygian at tesco.net (Glen) Date: Tue Feb 1 00:01:32 2005 Subject: [Tutor] Newbie struggling with Tkinter/canvas tags In-Reply-To: <41FE9DF8.7030606@tds.net> References: <41FE9DF8.7030606@tds.net> Message-ID: <1107212499.4944.5.camel@localhost> > > Have you tried the addtag_withtag() method? It looks like it should be > > able to do what you're thinking of. The documentation here: > > > > http://tkinter.unpythonic.net/pydoc/Tkinter.Canvas.html > > > > should talk about addtag_withtag(). > > itemconfig() also looks promising. > > http://www.pythonware.com/library/tkinter/introduction/x2017-concepts.htm > Thanks Danny and Kent, I see it now. With so many options on offer it's easy to miss the obvious. All of this new information should keep me occupied for quite some time. Thanks again. Glen From mlaberge at labergedaylight.com Tue Feb 1 00:27:24 2005 From: mlaberge at labergedaylight.com (Michiyo LaBerge) Date: Tue Feb 1 00:27:30 2005 Subject: [Tutor] Comparing files, Counting Value Message-ID: Hello all, I'm very new to Python and have been trying to write a script to compare data from 2 files and getting a total. One of the two files contains x, y positions of pixels and a color value(z) of each, so it has three columns in the file. The other file has two columns; x1, y1. I'd like to get only x, y positions which match to x1, y1 of the second file and then look up the z value. If the z value is greater than a certain number, it counts 1, otherwise it moves on the next x, y position. Finally, I'm able to get total count of the pixels that are over the threshold. The script I'm using is below step by step, however, I haven't been able to figure out the error massage "IndexError: list index out of range" on z value. Any comments would be appreciated! Regards, Michiyo file 1: file 2: 299 189 8.543e-02 260 168 300 189 0.000e+00 270 180 301 189 0.000e+00 299 189 302 189 0.000e+00 300 170 0 188 5.095e-02 301 189 1 188 5.108e-02 . . . . . . . . . . . . #!usr/local/bin/python import sys i=open("file 1") #value data o=open("file 2") #look-up file l=open("result", 'w')#result results={} line=i.readline() line=o.readline() while line: fields=line.split() x1=fields[0, 1] in i #x,y position in file 1 z=fields[2] in i #value data in file 1 x2=fields[0, 1] in o #x,y position in file 2 if x1 == x2: read(z) if z >= 5.000e-02: z=1 count(n=0) print>>l, count(1) i.close() o.close() l.close() From apple_py at biz-experts.net Tue Feb 1 01:01:59 2005 From: apple_py at biz-experts.net (Victor Rex) Date: Tue Feb 1 01:02:02 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <41FC558A.7090402@gmail.com> References: <41FC40C8.1050308@fastmail.fm><166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> Message-ID: <41FEC6F7.3050301@biz-experts.net> Orri Ganel wrote: > Jacob S. wrote: > >> Thanks Kent and Max!!!!! >> >> Wow, I didn't know it did that. I'm too dumb to figure it out on my >> own I guess... >> Oh well! I found a cool new thing to play with at least! >> >> Thanks, >> Jacob >> >> >> >>> >>> On Jan 30, 2005, at 02:40, Jacob S. wrote: >>> >>>> I don't think that's what he wants. I think he wants to *overwrite* >>>> what's in the shell with new output. >>>> For example. >>>> >>>> >>>> so that the whole line is overwritten. In my experience, this is >>>> not possible and if anyone can show me how to do it, >>>> I would be grateful. >>>> >>>> HTH, >>>> Jacob >>> >>> >>> >>> It *is* possible, that's exactly what my code does (well, as long as >>> you don't run it on Mac OS 9). The carriage return (\r, as opposed >>> to the linefeed \n) moves the cursor to the beginning of the >>> *current* line. >>> >>> -- Max >>> maxnoel_fr at yahoo dot fr -- ICQ #85274019 >>> "Look at you hacker... A pathetic creature of meat and bone, panting >>> and sweating as you run through my corridors... How can you >>> challenge a perfect, immortal machine?" >>> >>> >>> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Just a note: This does not work on IDLE, so for those who try this and > are frustrated when it fails, try it in the dos-box (command prompt). > I played around with this output issue and I love the way it works. Now, how do you do this in *nix? I tried the same approach and I get a blank line for 5 seconds (or whatever number of cycles you have on your example) and the a final line with the last value of the iterable. Do you happen to know how this in done? Thanks. Victor worked around this problem and I love the solution. From bill.mill at gmail.com Tue Feb 1 01:13:27 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue Feb 1 01:13:30 2005 Subject: [Tutor] Comparing files, Counting Value In-Reply-To: References: Message-ID: <797fe3d405013116132a19ea99@mail.gmail.com> Michiyo, When you ask a question to the list, you should be more careful to highlight your problem so that it doesn't seem like you're asking people to write a script for you. I don't think that's what you were doing, but just try to reduce your problem to a minimal example in the future. I don't know what your script is doing; array[0, 2] is not legal as far as I know in python (it is legal on numarray.array types, but not on regular python lists AFAIK). I also don't know what that "in i" stuff you're doing means. When I run your code, I get a "TypeError: list indices must be integers" on the fields[0, 1] line. You should try to write your code in small bites to make it easier to debug. That said, I dig doing this sort of text processing, so I wrote my own script to do it. Perhaps it'll help clear up some ideas for you; if you have any questions, feel free to ask me about them: ==========begin file testprocess.py===================== one = open('one') two = open('two') out = open('out', 'w') THRESHOLD = .05 #build dict of {(x,y): z} from 'one' pts = {} for line in one: x, y, z = [float(i) for i in line.split()] #convert strings to floats pts[(x,y)] = z #insert point into dictionary #now check to find each pixel in 'two' in the pts dictionary bigpixels = 0 for line in two: x, y = [float(i) for i in line.split()] #convert strings to floats if (x,y) in pts and pts[(x,y)] > THRESHOLD: bigpixels += 1 print "%d pixels over %f" % (bigpixels, THRESHOLD) ============end file============================== Peace Bill Mill bill.mill at gmail.com On Mon, 31 Jan 2005 15:27:24 -0800, Michiyo LaBerge wrote: > Hello all, > > I'm very new to Python and have been trying to write a script to > compare data from 2 files and getting a total. One of the two files > contains x, y positions of pixels and a color value(z) of each, so it > has three columns in the file. The other file has two columns; x1, y1. > I'd like to get only x, y positions which match to x1, y1 of the second > file and then look up the z value. If the z value is greater than a > certain number, it counts 1, otherwise it moves on the next x, y > position. Finally, I'm able to get total count of the pixels that are > over the threshold. The script I'm using is below step by step, > however, I haven't been able to figure out the error massage > "IndexError: list index out of range" on z value. Any comments would be > appreciated! > > Regards, > Michiyo > > file 1: file 2: > 299 189 8.543e-02 260 168 > 300 189 0.000e+00 270 180 > 301 189 0.000e+00 299 189 > 302 189 0.000e+00 300 170 > 0 188 5.095e-02 301 189 > 1 188 5.108e-02 . . > . . . . . > . . . . . > > #!usr/local/bin/python > > import sys > > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result > > results={} > > line=i.readline() > line=o.readline() > > while line: > fields=line.split() > x1=fields[0, 1] in i #x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 > > if x1 == x2: > read(z) > > if z >= 5.000e-02: > z=1 > count(n=0) > print>>l, count(1) > > i.close() > o.close() > l.close() > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From guillermo.fernandez.castellanos at gmail.com Tue Feb 1 01:15:51 2005 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Feb 1 01:15:53 2005 Subject: [Tutor] Traffic Network simulator In-Reply-To: <20050131225034.38172.qmail@web53810.mail.yahoo.com> References: <20050131225034.38172.qmail@web53810.mail.yahoo.com> Message-ID: <7d7029e7050131161569621a77@mail.gmail.com> Hi, Don't know if there's any network simulator. But I know about SimPy: http://simpy.sourceforge.net/ Looks well documented. Check the examples, it seems you can do pretty robust things with not toomuch code. I readed about it in the charming python section of IBM developers works: http://www-106.ibm.com/developerworks/linux/library/l-simpy.html?dwzone=linux Check also the SimPy Wiki: http://www.mcs.vuw.ac.nz/cgi-bin/wiki/SimPy?SimPy Enjoy, Guille On Mon, 31 Jan 2005 14:50:34 -0800 (PST), Shitiz Bansal wrote: > Hi, > > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. > does anyone know where i can find something of the > sort or are there any special modules available which > can help me build one? > > Shitiz > > > __________________________________ > Do you Yahoo!? > All your favorites on one personal page ? Try My Yahoo! > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Feb 1 01:18:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 01:18:35 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <41FEC6F7.3050301@biz-experts.net> References: <41FC40C8.1050308@fastmail.fm><166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> Message-ID: <41FECAD4.5010702@tds.net> Victor Rex wrote: > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. It sounds like the '\r' is erasing the line, not just moving the cursor. Try putting the '\r' at the beginning of the output rather than the end: for i in range(10): print '\r', 'i is', i time.sleep(1) Kent From dyoo at hkn.eecs.berkeley.edu Tue Feb 1 01:21:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 1 01:22:03 2005 Subject: [Tutor] Comparing files, Counting Value In-Reply-To: Message-ID: Hi Michiyo, Ok, let's take a look at the code. > i=open("file 1") #value data > o=open("file 2") #look-up file > l=open("result", 'w')#result We strongly recommend renaming these names to ones that aren't single characters. It's difficult to tell here what 'i', 'o', and 'l' mean, outside of the context of the assignments. The letters 'i' and 'o' often stand for the words "input" and "output". The way that you're using these as variable names for input files will break the expectation of people who read the code. Futhermore, 'l' can easily be misread as 'i'. In short, those names should be changed to something readable. This is a pure style issue, but I think it's important as programmers to make the code easy for humans to understand. > results={} > > line=i.readline() > line=o.readline() This looks problematic. The 'line' name here, by the end of these two statements, is bound to the value of the look-up file's line. I believe you need to keep those values distinct. > while line: > fields=line.split() > x1=fields[0, 1] in i #x,y position in file 1 > z=fields[2] in i #value data in file 1 > x2=fields[0, 1] in o #x,y position in file 2 There are several fundamental issues with this. Conventionally, a file-loop has the following structure: ### for line in inputFile: # ... do something with that line ### and anything that tries to iterate across a file in a different way should be looked at with some care. The way that your code is trying to iterate across the file won't work. We strongly recommend you read through a tutorial like: http://www.freenetpages.co.uk/hp/alan.gauld/tutfiles.htm which has examples of how to write programs that work with files. The way the program's structured also seems a bit monolithic. I'd recommend breaking down the problem into some phases: Phase 1: read the value-data file into some data structure. Phase 2: taking that data structure, read in the lookup file and identify which positions are matching, and record matches in the output file. This partitioning of the problem should allow you to work on either phase of the program without having to get it correct all at once. The phases can be decoupled because we can easily feed in some kind of hardcoded data structure into Phase 2, just to check that the lookup-file matching is doing something reasonable. For example: ### hardcodedDataStructure = { (299, 189) : 8.543e-02, (300, 189) : 0.000e+00, (301, 189) : 0.000e+00, (1, 188) : 5.108e-02 } ### is a very small subset of the information that your value data contains. We can then take this hardcodedDataStructure and work on the second part of the program using 'hardcodedDataStructure'. Later on, when we do get Phase 1 working ok, we can use the result of Phase 1 instead of the hardcodedDataStructure, and it should just fit into place. Does this make sense? Don't try writing the program all at once and then start trying to make it all work. But instead, try building small simple programs that do work, and then put those together. The statements: > fields=line.split() > x1=fields[0, 1] in i #x,y position in file 1 won't work. 'fields[0, 1]' does not represent the first and second elements of 'fields': it means something else, but you should get errors from it anyway. For example: ### >>> values = ["hello", "world", "testing"] >>> values[0, 1] Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers ### So you should have already seen TypeErrors by this point of the program. What you probably meant to write was: ### fields = line.split() x1 = (fields[0], fields[1]) ### Alternatively: ### fields = line.split() x1 = fields[0:1] ### The significance of accidentely using the comma there won't make too much sense until you learn about tuples and dictionaries, so I won't press on this too much. I'd recommend that you read through one of the Python tutorials before trying to finishing the program. Some of the things that your program contains are... well, truthfully, a little wacky. There are several good tutorials linked here: http://www.python.org/moin/BeginnersGuide/NonProgrammers If you have more questions, please feel free to ask! From dyoo at hkn.eecs.berkeley.edu Tue Feb 1 02:27:15 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 1 02:27:19 2005 Subject: [Tutor] Better structure? In-Reply-To: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> Message-ID: On Mon, 31 Jan 2005, Jacob S. wrote: > I think this thing is screaming for better structure, but previous attempts > at using oop for it have failed. Hi Jacob, Ok, I see one big refactoring that should help things quite a bit. There's a large case-analysis off if/elif/elif statements that involves 'y'. Let me just grep for the lines here: > if y == 'clear': > elif y == 'quit': > elif y == 'remove lines': > elif y == 'return lines': > elif y.startswith('gatl'): > elif y.startswith('ganl'): > elif y.startswith('gotl'): > elif y.startswith('gonl'): > elif y.startswith('getpt'): > elif y == 'regraph': The structure can be improves by using that dispatch-table method we talked about a few days ago. We can't directly apply the dispatch technique, because there's a little bit of nonuniformity. Some of the statements compare y by equality, while others use 'startswith' checks. But I think we can handle it by making everything a little bit more uniform: we can make everything an 'equality' check against the first word on the line. Here's some pseudocode for the proposed fix: ### Pseudocode commandDispatchTable = {'clear' : clearCommand 'quit' : quitCommand 'remove' : removeCommand 'return' : returnCommand 'gatl' : gatlCommand 'ganl' : ganlCommand 'gotl' : gotlCommand 'gonl' : gonlCommand 'getpt' : getplCommand 'regraph': regraphCommand def evaluate(line): """Evaluates the line.""" pieces = line.split() cmd, rest = pieces[0], pieces[1:] if cmd in commandDispatchTable: dispatchTable[cmd](rest) elif isAssignment(line): ... else: ... ### The evaluate() function tries to handle the common-case stuff with a dispatch-table method, and otherwise follows up with special-case stuff to handle the rest of the case analysis. One other neat feature of this is that, because we split() against the whole line, we've broken down the line into 'cmd' and the 'rest' of the arguments to that command. This might also help clean up some of the logic that grabbing the argument on the rest of the line, step2 = float(y.lstrip("gatl ")) x = float(y.lstrip('gotl ')) x = float(y.lstrip('gonl ')) y = y.lstrip("getpt ") You can avoid doing so many lstrip()s by using the 'rest' argument list. Best of wishes to you! From p.hartley at spitech.com Tue Feb 1 17:35:41 2005 From: p.hartley at spitech.com (Paul Hartley) Date: Tue Feb 1 03:33:43 2005 Subject: [Tutor] Presentation Message-ID: <003f01c5087c$117cb6c0$012118ac@SP1179> I am trying to get Python established here in the Philippines. Currently I am in charge of operations at a business based in Manila and I have asked my IT staff to start using Python (with some success). A local university has now asked that I give a talk to their IT people on Python - so here is an opportunity to spread the word and get some more converts and maybe introduce python into their computer science courses. Any help I can get would be much appreciated - such as language comparisons, companies and systems that use python, debates about what python is good for (almost everything), examples of elegant code.. When I was a member of the Forth Interest Group in the USA we learned that Forth was used on the buggy that went to mars, that it started life controlling huge radio telescopes which only had 4k (yes 4k) of memory for both language and application. Anything like the above concerning python would be useful. Any other suggestions would help also, the audience will have computers, so a demonstration of small workshop would also be good - the presentation/session is for 4 hours on the 10th February. Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050201/1e0e22d0/attachment.html From maxnoel_fr at yahoo.fr Tue Feb 1 03:43:32 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Feb 1 03:43:38 2005 Subject: [Tutor] Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <61684d94f666d2cb496f617cf83f4582@yahoo.fr> On Feb 1, 2005, at 16:35, Paul Hartley wrote: > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started > life controlling huge radio telescopes which only had 4k (yes 4k) of > memory for both language and application. > ? > Anything like the above concerning python would be useful. Well, that's probably not as awe-inspiring, but BitTorrent is written entirely in Python (with the wxPython graphical toolkit for the Windows and X11 versions, and PyObjC for the Mac OS X version). Google also use the language extensively, although I don't exactly know why, thanks to their obsession with secrecy. You could point out that Python's greatest strength (aside from its extreme readability -- unlike most people, The Whitespace Thing always struck me as an excellent design decision, although had I been Guido, I'd have forced the use of either tabs or spaces but not allowed both) is the fact that it's multi-paradigm. You can work procedurally, object-orientedly, and even in some cases functionally. And you can mix-and-match those 3 paradigms depending on your needs. This can be very useful. Oh, and make sure you mention iterators and list comprehensions at some point. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From carroll at tjc.com Tue Feb 1 04:18:58 2005 From: carroll at tjc.com (Terry Carroll) Date: Tue Feb 1 04:19:01 2005 Subject: [Tutor] Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: On Tue, 1 Feb 2005, Paul Hartley wrote: > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started life > controlling huge radio telescopes which only had 4k (yes 4k) of memory > for both language and application. > > Anything like the above concerning python would be useful. I just did a google on "Pyton success stories," and found this page, which you may find useful. http://www.pythonology.com/success See also the two O'Reilley links on that page. Since you mentioned use in space exploration, always a sexy example, I search for "Nasa Python" also turned up these: NASA Ames Processing in Python: http://home.badc.rl.ac.uk/astephens/software/nappy/ Space shuttle engineers use Python to streamline mission design: http://builder.com.com/5100-6401-1045764.html ... and others. From keridee at jayco.net Tue Feb 1 05:34:09 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Feb 1 05:34:55 2005 Subject: [Tutor] Better structure? References: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> <00af01c507c5$f06ec470$d1b48651@xp> Message-ID: <001701c50817$6f454d90$6d5428cf@JSLAPTOP> >> def start(): > .... lots of lines... >> global xaxis >> global yaxis > > Its traditional to put global statements at the top of the function. > Also you only need one line to list all of the global variables > >> global radiusaxis >> global radiusaxis2 What, like global radiusaxis, radiusaxis2 > Similarly here., and again you can put all four in one place. > >> radiusaxis2.visible = 0 > And since there is no input parameter and no return statement > and you only call start() once... Not true. If y == 'clear', then start is called to "redraw" the window. Very important part. >> def graphit(type,f,range2,step): >> li = curve(color=color.blue) >> if type in ['y','x']: >> x = -15 >> radiusaxis.visible = 0 >> radiusaxis2.visible = 0 >> while -15 <= x <= 15: >> if eval(range2): >> try: >> a = f(x) >> if -15 <= a <= 15: >> if type == 'y': >> li.append(pos=(x,a,0)) >> elif type == 'x': >> li.append(pos=(a,x,0)) >> else: >> li = curve(color=color.blue) >> except: >> pass > > This is iffy. If *anthing* happens you ignore it. > Now suppose due to a bug you go into an infinite > loop and you try to stop using CTRL-C - it won't work! > > If you must use a catch-all except then do something > with it - print a message at least! I think I'll do that, but of course I'll have to add ValueError -- because of math domain errors on my function. That's what the try except block is for. Otherwise I wouldn't need it. > I got a sore head after that... I'll leave the rest for > others to remark upon. :-) > > Alan G. I'd send some Advil or something, but it doesn't work too well through email. ;-) Thanks for the help, Jacob Schmidt From keridee at jayco.net Tue Feb 1 05:38:03 2005 From: keridee at jayco.net (Jacob S.) Date: Tue Feb 1 05:38:17 2005 Subject: [Tutor] Better structure? References: Message-ID: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> Ah, I like. BTW, it was a few months ago, not days... but the thought still counts. At least you remember. I was getting stumped by the difference in comparing y The check for seeing what the first word is made me slamp my forehead... Thanks! Jacob Schmidt > > > On Mon, 31 Jan 2005, Jacob S. wrote: > >> I think this thing is screaming for better structure, but previous >> attempts >> at using oop for it have failed. > > > Hi Jacob, > > > Ok, I see one big refactoring that should help things quite a bit. > There's a large case-analysis off if/elif/elif statements that involves > 'y'. Let me just grep for the lines here: > >> if y == 'clear': >> elif y == 'quit': >> elif y == 'remove lines': >> elif y == 'return lines': >> elif y.startswith('gatl'): >> elif y.startswith('ganl'): >> elif y.startswith('gotl'): >> elif y.startswith('gonl'): >> elif y.startswith('getpt'): >> elif y == 'regraph': > > > The structure can be improves by using that dispatch-table method we > talked about a few days ago. > > > We can't directly apply the dispatch technique, because there's a little > bit of nonuniformity. Some of the statements compare y by equality, while > others use 'startswith' checks. But I think we can handle it by making > everything a little bit more uniform: we can make everything an 'equality' > check against the first word on the line. Here's some pseudocode for the > proposed fix: > > > ### Pseudocode > commandDispatchTable = {'clear' : clearCommand > 'quit' : quitCommand > 'remove' : removeCommand > 'return' : returnCommand > 'gatl' : gatlCommand > 'ganl' : ganlCommand > 'gotl' : gotlCommand > 'gonl' : gonlCommand > 'getpt' : getplCommand > 'regraph': regraphCommand > > def evaluate(line): > """Evaluates the line.""" > pieces = line.split() > cmd, rest = pieces[0], pieces[1:] > if cmd in commandDispatchTable: > dispatchTable[cmd](rest) > elif isAssignment(line): > ... > else: > ... > ### > > The evaluate() function tries to handle the common-case stuff with a > dispatch-table method, and otherwise follows up with special-case stuff to > handle the rest of the case analysis. > > > One other neat feature of this is that, because we split() against the > whole line, we've broken down the line into 'cmd' and the 'rest' of the > arguments to that command. This might also help clean up some of the > logic that grabbing the argument on the rest of the line, > > step2 = float(y.lstrip("gatl ")) > x = float(y.lstrip('gotl ')) > x = float(y.lstrip('gonl ')) > y = y.lstrip("getpt ") > > You can avoid doing so many lstrip()s by using the 'rest' argument list. > > > > Best of wishes to you! > > > From alan.gauld at freenet.co.uk Tue Feb 1 05:39:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 05:38:50 2005 Subject: [Tutor] Traffic Network simulator References: <20050131225034.38172.qmail@web53810.mail.yahoo.com> Message-ID: <004e01c50817$f39e6040$68b78851@xp> > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. I don't jnow of anything ready made. But a Google search may find someting somewhere... > does anyone know where i can find something of the > sort or are there any special modules available which > can help me build one? These kinds of simulators usually entail a set of interacting queues. There might be python modules around for building queues. You might also find a math book or web site on queuing theory useful... Also you will certainly want to use the random module for this. Alan G. From andrewm at object-craft.com.au Tue Feb 1 08:01:41 2005 From: andrewm at object-craft.com.au (Andrew McNamara) Date: Tue Feb 1 08:01:43 2005 Subject: [Tutor] Traffic Network simulator In-Reply-To: <004e01c50817$f39e6040$68b78851@xp> References: <20050131225034.38172.qmail@web53810.mail.yahoo.com> <004e01c50817$f39e6040$68b78851@xp> Message-ID: <20050201070141.897863C889@coffee.object-craft.com.au> > I need a traffic network simulator(for roads) for my > project work.I would prefer the simulator to be in > python so that i can reprogram/modify it according to > my needs. Have you looked at SimPy: http://simpy.sourceforge.net/ -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From kraus at hagen-partner.de Tue Feb 1 09:15:53 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Tue Feb 1 09:16:02 2005 Subject: [Tutor] Re: Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: Paul Hartley wrote: [...] > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started > life controlling huge radio telescopes which only had 4k (yes 4k) of > memory for both language and application. Well, the rover used Forth, but the rover-website is Plone powered: http://plone.org/newsitems/mars-rover Plone is a CMS built on top of Zope, which itself is Python powered. For more sites running plone see: http://plone.org/about/sites/ HTH, Wolfram From dyoo at hkn.eecs.berkeley.edu Tue Feb 1 10:21:29 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 1 10:21:33 2005 Subject: [Tutor] Better structure? In-Reply-To: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> Message-ID: On Mon, 31 Jan 2005, Jacob S. wrote: > BTW, it was a few months ago, not days... but the thought still counts. > At least you remember. Hi Jacob, Wait, was it really a few months ago? Let me check the archive... http://mail.python.org/pipermail/tutor/2004-December/033728.html You're right. Wow, I'm getting that much more senile by the minute. > I was getting stumped by the difference in comparing y The check for > seeing what the first word is made me slamp my forehead... I'm glad that you enjoyed one of those "ah ha!" moments. *grin* If you ever get the chance, you may want to take a look at a book called Programming Pearls: http://www.cs.bell-labs.com/cm/cs/pearls/ for a few more examples of "ah ha!" moments of enlightenment. As a side note: it's possible to do the same sort of thing that we did in the last post --- with class instances --- but it's slightly more heavyweight compared to using first-class function values. Let's see what that looks like, just for comparison. The following variant will probably feel more comfortable to Java programmers: here's a sketch of how we can do this dispatch technique with classes instead of first-class functions: ###### class Command(object): def execute(self, args): raise NotImplementedError class ClearCommand(Command): def execute(self, args): ... class QuitCommand(Command): def execute(self, args): ... ... commandDispatchTable = { 'clear' : ClearCommand(), 'quit' : QuitCommand(), ... } def evaluate(line): """Evaluates the line.""" pieces = line.split() cmd, rest = pieces[0], pieces[1:] if cmd in commandDispatchTable: dispatchTable[cmd].execute(rest) elif isAssignment(line): ... else: ... ###### It's the same general idea. But just more typing. *grin* An advantage of using the class approach is that it is easy to extend the commands to respond to different methods besides direct execution. For example, we might want to add a "help()" Command that provides a functionality similar to the one provided by the builtin Python help() function. If each of the Commands implements a help() method, then we can do something like: ### class Command(object): def execute(self, args): raise NotImplementedError def help(self): return self.__doc__ class HelpCommand(Command): """Displays help for a command. Syntax: help [command name]. Example Usage: help clear """ def getHelpString(self, commandName): if commandName in dispatchTable: return dispatchTable[commandName].help() else: return "Unknown command." def execute(self, args): if not args: commandName = 'help' else: commandName = args[0] print "help on %r: %s" % (commandName, self.getHelpString(commandName)) ### We can get more complicated from here. I'm not sure if this help() Command is a good idea, but it's an option. And perhaps not coincidently, if we look at your program's structure again now, we might notice that it's gradually looking more and more like an interpreter. *grin* Best of wishes to you! From kent37 at tds.net Tue Feb 1 11:49:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 11:49:16 2005 Subject: [Tutor] Presentation In-Reply-To: <003f01c5087c$117cb6c0$012118ac@SP1179> References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <41FF5EA9.3090000@tds.net> Eric Raymond's "Why Python?" essay is a classic: http://pythonology.org/success&story=esr Bruce Eckel's "Why I love Python" presentation is here: http://64.78.49.204/pub/eckel/LovePython.zip This page has lots of links you might be interested in: http://www.ferg.org/python_presentations/index.html This page has links to language comparisons: http://www.python.org/moin/LanguageComparisons Good luck! Kent Paul Hartley wrote: > I am trying to get Python established here in the Philippines. Currently > I am in charge of operations at a business based in Manila and I have > asked my IT staff to start using Python (with some success). > > A local university has now asked that I give a talk to their IT people > on Python - so here is an opportunity to spread the word and get some > more converts and maybe introduce python into their computer science > courses. > > Any help I can get would be much appreciated - such as language > comparisons, companies and systems that use python, debates about what > python is good for (almost everything), examples of elegant code.. > > When I was a member of the Forth Interest Group in the USA we learned > that Forth was used on the buggy that went to mars, that it started life > controlling huge radio telescopes which only had 4k (yes 4k) of memory > for both language and application. > > Anything like the above concerning python would be useful. > > Any other suggestions would help also, the audience will have computers, > so a demonstration of small workshop would also be good - the > presentation/session is for 4 hours on the 10th February. > > Paul > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 1 11:57:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 11:57:11 2005 Subject: [Tutor] Better structure? In-Reply-To: References: Message-ID: <41FF6082.70005@tds.net> Danny Yoo wrote: > > On Mon, 31 Jan 2005, Jacob S. wrote: > ### Pseudocode > commandDispatchTable = {'clear' : clearCommand > 'quit' : quitCommand > 'remove' : removeCommand > 'return' : returnCommand > 'gatl' : gatlCommand > 'ganl' : ganlCommand > 'gotl' : gotlCommand > 'gonl' : gonlCommand > 'getpt' : getplCommand > 'regraph': regraphCommand > > def evaluate(line): > """Evaluates the line.""" > pieces = line.split() > cmd, rest = pieces[0], pieces[1:] > if cmd in commandDispatchTable: > dispatchTable[cmd](rest) > elif isAssignment(line): > ... > else: > ... > ### > > The evaluate() function tries to handle the common-case stuff with a > dispatch-table method, and otherwise follows up with special-case stuff to > handle the rest of the case analysis. Jacob, if you like this you might want to look into the cmd module, it supports dispatching on the first word of a command with support for help, etc. > step2 = float(y.lstrip("gatl ")) > x = float(y.lstrip('gotl ')) > x = float(y.lstrip('gonl ')) > y = y.lstrip("getpt ") This code is broken. lstrip('gonl ') will remove *all* leading g, o, n, l and space, in any order: >>> s='go long on log buddy!' >>> s.lstrip('gonl ') 'buddy!' Instead of y.lstrip('gonl ') you should use y[5:] or maybe y[len('gonl '):] Kent From polatel at gmail.com Tue Feb 1 12:08:39 2005 From: polatel at gmail.com (Ali Polatel) Date: Tue Feb 1 12:09:11 2005 Subject: [Tutor] Programming Challenge C++ and Python Message-ID: <3c51d5180502010308149302c2@mail.gmail.com> I need a favor.I play chess at a chess server with the name ICC(www.chessclub.com). I want to write a plugin for their interface using Python. I don't have any idea about how to write a plugin but I found out that the server administrator has written a Plugin Development Kit in C++ for those who wish to write plugins for the interface.I don't know C++ so I cannot convert this kit into python scripts.Can anyone do this for me? or can anyone examine those scripts and tell me a way how to write those with python?The development kit is avaliable at the site ftp://ftp.chessclub.com/pub/icc/interface/blitzin2/plugins/ under the name PluginDevkit.zip Any kind of help is appreciated. Regards, Ali Polatel From cyresse at gmail.com Tue Feb 1 12:37:50 2005 From: cyresse at gmail.com (Liam Clarke) Date: Tue Feb 1 12:37:54 2005 Subject: [Tutor] Better structure? In-Reply-To: References: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> Message-ID: > http://www.cs.bell-labs.com/cm/cs/pearls/ That link seems to be dead. Pity. My whole programming experience is comprised of Ah-Ha's followed by Um's... -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From godoy at ieee.org Tue Feb 1 13:14:21 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Tue Feb 1 13:16:01 2005 Subject: [Tutor] Re: Better structure? References: <001b01c50817$d6846cc0$6d5428cf@JSLAPTOP> Message-ID: <1289640.DAVN76bQ42@jupiter.g2ctech> Liam Clarke wrote: >> http://www.cs.bell-labs.com/cm/cs/pearls/ > That link seems to be dead. Pity. My whole programming experience is > comprised of Ah-Ha's followed by Um's... It worked here. -- Godoy. From mi.janssen at gmail.com Tue Feb 1 13:40:36 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue Feb 1 13:40:41 2005 Subject: [Tutor] How does import work? In-Reply-To: <41FA7925.80109@freenet.de> References: <41FA7925.80109@freenet.de> Message-ID: <1ff2dfbf05020104407bd21929@mail.gmail.com> On Fri, 28 Jan 2005 18:40:53 +0100, Johan Nilsson wrote: > >>> from scipy.signal.signaltools import * > > /Traceback (most recent call last): > File "", line 1, in -toplevel- > from scipy.signal.signaltools import * > ImportError: No module named signaltools/ > > So I try the methodic way and this works, giving me access to the > functions I need > > >>> from scipy import * > >>> from scipy.signal import * > >>> from scipy.signal.signaltools import * seems like overkill (and I don't understand why it works better than the above, but that's more an issue about my understanding and not about python ;-). Try from scipy.signal import signaltools # don't import everything from signal and go on using functions from signaltools like this: signaltools.function > Now what confuses me is that when I put the above three lines in a file > (of course without the >>>) and execute them I get a long error message. perhaps different python versions? > / Traceback (most recent call last): > File "/home/johan/pyton/import_test.py", line 5, in -toplevel- > from scipy.signal import * note that the error occours while importing everything from scipy.signal . The chance are well that this error goes away when using a reduced import statement. [snip long traceback talking about scipy and Numerics imports] > import lapack_lite > ImportError: > /usr/local/lib/python2.3/site-packages/Numeric/lapack_lite.so: undefined > symbol: dgesdd_/ given the fact that I'm no c-programmer this seems to me like a broken c module. I would try to reinstall Numeric/ scipy (After hunting the problem down to a specific import). The most obvious reason why the import in idle works is that idle uses another version of python (ask sys.version) regards Michael From mi.janssen at gmail.com Tue Feb 1 14:30:37 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Tue Feb 1 14:30:41 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <41FEC6F7.3050301@biz-experts.net> References: <41FC40C8.1050308@fastmail.fm> <166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> Message-ID: <1ff2dfbf05020105307f2ee5d2@mail.gmail.com> On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex wrote: > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. > > Do you happen to know how this in done? you might want to flush stdout after printing to it. "print" will cares for this only when not using that trailing comma. "flush" means to write immedatly instead to wait for a fair amount of data. import sys,time for i in range(8): sys.stdout.write( "step: %s\r" % i) # or: print "step: %s\r" % i, sys.stdout.flush() time.sleep(.5) There's still another possibilty using ansi control sequences. The dirty way is to print (without trailing comma) and go back to previous line: import time for i in range(8): print "step: %s\033[A" % i # print subsystem has done stdout.flush time.sleep(.5) It's dirty cause the next line was already entered and thus is written (as an empty line) and content of older "steps" will stay an screen, when subsequents lines aren't long enough to overwrite them. Which also applies to \r: import sys,time for i in range(8,0,-1): # printing 8**8, ..., 0**0 on line. Forget to overwrite sys.stdout.write( "step: %s\r" % (i**i)) sys.stdout.flush() time.sleep(.5) Fixes are to add whitespace to the line. Stepping back with \033[D fixes the empty newline issue (which is most often not worth the effort): import sys,time for i in range(8,0,-1): # fixing output length to 30 output = "%-30s" % "step: %s" % (i**i) length = len(output) sys.stdout.write(output) # "print output," would be different, because of implizit spaces sys.stdout.write("\033[D"* (length)) sys.stdout.flush() time.sleep(.5) regards Michael From mark.brown at rogers.com Tue Feb 1 15:40:06 2005 From: mark.brown at rogers.com (Mark Brown) Date: Tue Feb 1 15:40:10 2005 Subject: [Tutor] Test Message-ID: <41FF94C6.2070709@rogers.com> Test, please disregard. From apple_py at biz-experts.net Tue Feb 1 17:28:31 2005 From: apple_py at biz-experts.net (Victor Rex) Date: Tue Feb 1 17:28:34 2005 Subject: [Tutor] carriage return on windows In-Reply-To: <1ff2dfbf05020105307f2ee5d2@mail.gmail.com> References: <41FC40C8.1050308@fastmail.fm> <166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP> <41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> <1ff2dfbf05020105307f2ee5d2@mail.gmail.com> Message-ID: <41FFAE2F.80500@biz-experts.net> Michael Janssen wrote: >On Mon, 31 Jan 2005 18:01:59 -0600, Victor Rex wrote: > > > >>I played around with this output issue and I love the way it works. >>Now, how do you do this in *nix? I tried the same approach and I get a >>blank line for 5 seconds (or whatever number of cycles you have on your >>example) and the a final line with the last value of the iterable. >> >>Do you happen to know how this in done? >> >> > >you might want to flush stdout after printing to it. "print" will >cares for this only when not using that trailing comma. "flush" means >to write immedatly instead to wait for a fair amount of data. > >import sys,time >for i in range(8): > sys.stdout.write( "step: %s\r" % i) > # or: print "step: %s\r" % i, > sys.stdout.flush() > time.sleep(.5) > > >There's still another possibilty using ansi control sequences. The >dirty way is to print (without trailing comma) and go back to previous >line: > >import time >for i in range(8): > print "step: %s\033[A" % i > # print subsystem has done stdout.flush > time.sleep(.5) > >It's dirty cause the next line was already entered and thus is written >(as an empty line) and content of older "steps" will stay an screen, >when subsequents lines aren't long enough to overwrite them. Which >also applies to \r: > >import sys,time >for i in range(8,0,-1): > # printing 8**8, ..., 0**0 on line. Forget to overwrite > sys.stdout.write( "step: %s\r" % (i**i)) > sys.stdout.flush() > time.sleep(.5) > >Fixes are to add whitespace to the line. Stepping back with \033[D >fixes the empty newline issue (which is most often not worth the >effort): > >import sys,time >for i in range(8,0,-1): > # fixing output length to 30 > output = "%-30s" % "step: %s" % (i**i) > length = len(output) > sys.stdout.write(output) > # "print output," would be different, because of implizit spaces > sys.stdout.write("\033[D"* (length)) > sys.stdout.flush() > time.sleep(.5) > > >regards >Michael > > > > Excellent. Thanks Kent and Michael. Great tutorial ;-) You're right Michael. This last one works nicely but it is probably not worth the effort. I likes the previous one but adding fixed formatting to the number output, something like "step: %9s\r" instead of just "step: %s\r". Thanks again. Victor From jsmith at medplus.com Tue Feb 1 17:40:18 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 1 17:40:23 2005 Subject: [Tutor] Matching with beginning of the line in the character set Message-ID: I want to match a string which is preceeded by a space or occurs at the beginning of the line. I also don't want to catch the preceeding character as a group. I have found both of the following to work re.compile('(?:^|\s)string') re.compile('(?:\A|\s)string') But would prefer to use the more concise [] notation. However re.compile('[^\s]string') Does not work and re.compile('[\A\s]string') throws an exception: Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\sre.py", line 180, in compile return _compile(pattern, flags) File "C:\Python24\Lib\sre.py", line 227, in _compile raise error, v # invalid expression error: internal: unsupported set operator Why don't either of these work (particularly the latter)? Jeff From mark.kels at gmail.com Tue Feb 1 18:08:41 2005 From: mark.kels at gmail.com (Mark Kels) Date: Tue Feb 1 19:08:50 2005 Subject: [Tutor] Tkinter questions Message-ID: Hello, I got some Tkinter questions that I need the answer for to complete a little project of mine: 1. How can I make the program to open in a X*Y sized window ? 2. How can I open another window from the first one (without closing it) ? 3. How can I add a file browser for my app (like the one you get when you press "Save as..." in windows apps) ? 4. How do I configure the font size on the Text widget (its realy huge, and I would like to change it to somthing like 12). 5. [OT] Do you know any web-sites that I can store my project at (like sourceforge and others) ? This is all for now :) Thanks in advence . -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From kent37 at tds.net Tue Feb 1 19:15:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 19:15:27 2005 Subject: [Tutor] Matching with beginning of the line in the character set In-Reply-To: References: Message-ID: <41FFC736.1090106@tds.net> Smith, Jeff wrote: > I want to match a string which is preceeded by a space or occurs at the > beginning of the line. I also don't want to catch the preceeding > character as a group. > > I have found both of the following to work > re.compile('(?:^|\s)string') > re.compile('(?:\A|\s)string') How about r'\bstring' ? It doesn't mean quite the same as \sstring but it might work for you. > > But would prefer to use the more concise [] notation. However > re.compile('[^\s]string') As the first character in [], ^ means 'not'. > Does not work and > re.compile('[\A\s]string') I guess \A doesn't count as a 'character class'? Or do you need to be using raw strings? Kent From jsmith at medplus.com Tue Feb 1 19:30:44 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 1 19:30:47 2005 Subject: [Tutor] Matching with beginning of the line in the character set Message-ID: Kent, I think \b will work for me since I was really looking for [\A\W] anyway. That still doesn't answer the generalized question about something like [\A\d] for instance. Thanks, Jeff BTW, I was using raw strings although I forgot to put that in. -----Original Message----- From: Kent Johnson [mailto:kent37@tds.net] Sent: Tuesday, February 01, 2005 1:15 PM Cc: Tutor@python.org Subject: Re: [Tutor] Matching with beginning of the line in the character set Smith, Jeff wrote: > I want to match a string which is preceeded by a space or occurs at > the beginning of the line. I also don't want to catch the preceeding > character as a group. > > I have found both of the following to work > re.compile('(?:^|\s)string') > re.compile('(?:\A|\s)string') How about r'\bstring' ? It doesn't mean quite the same as \sstring but it might work for you. > > But would prefer to use the more concise [] notation. However > re.compile('[^\s]string') As the first character in [], ^ means 'not'. > Does not work and > re.compile('[\A\s]string') I guess \A doesn't count as a 'character class'? Or do you need to be using raw strings? Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 1 19:49:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 1 19:49:30 2005 Subject: [Tutor] Matching with beginning of the line in the character set In-Reply-To: References: Message-ID: <41FFCF30.2090504@tds.net> Smith, Jeff wrote: > Kent, > > I think \b will work for me since I was really looking for [\A\W] > anyway. > > That still doesn't answer the generalized question about something like > [\A\d] for instance. I know :-) The docs say [] is "Used to indicate a set of characters." So it kind of makes sense that it works for \w and \s, which are just shortcuts for sets of characters themselves, but not for \A which is something different. Kent > > Thanks, > Jeff > > BTW, I was using raw strings although I forgot to put that in. > > -----Original Message----- > From: Kent Johnson [mailto:kent37@tds.net] > Sent: Tuesday, February 01, 2005 1:15 PM > Cc: Tutor@python.org > Subject: Re: [Tutor] Matching with beginning of the line in the > character set > > > > > Smith, Jeff wrote: > >>I want to match a string which is preceeded by a space or occurs at >>the beginning of the line. I also don't want to catch the preceeding >>character as a group. >> >>I have found both of the following to work >> re.compile('(?:^|\s)string') >> re.compile('(?:\A|\s)string') > > > How about r'\bstring' ? It doesn't mean quite the same as \sstring but > it might work for you. > > >>But would prefer to use the more concise [] notation. However >> re.compile('[^\s]string') > > > As the first character in [], ^ means 'not'. > > >>Does not work and >> re.compile('[\A\s]string') > > > I guess \A doesn't count as a 'character class'? Or do you need to be > using raw strings? > > Kent > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ternary at gmail.com Tue Feb 1 19:58:49 2005 From: ternary at gmail.com (Mike Bell) Date: Tue Feb 1 19:58:52 2005 Subject: [Tutor] Matching with beginning of the line in the character set In-Reply-To: References: Message-ID: <82975b0c05020110581244f840@mail.gmail.com> Alternatively, you could .split() your string and not invoke the mechanisms dealing with regular expressions. Is this considered stylistically sloppy in the event that the split results in a very long array? Sloppier than REs are to begin with? I think that the problem with [\A\d] is that \A is zero-length, which doesn't make sense in the context of []. Brackets aren't shorthand for "'or' a bunch of small things together" but rather "'or' a bunch of these single-character matches together" mike On Tue, 1 Feb 2005 13:30:44 -0500, Smith, Jeff wrote: > Kent, > > I think \b will work for me since I was really looking for [\A\W] > anyway. > > That still doesn't answer the generalized question about something like > [\A\d] for instance. > > Thanks, > Jeff > > BTW, I was using raw strings although I forgot to put that in. > > -----Original Message----- > From: Kent Johnson [mailto:kent37@tds.net] > Sent: Tuesday, February 01, 2005 1:15 PM > Cc: Tutor@python.org > Subject: Re: [Tutor] Matching with beginning of the line in the > character set > > Smith, Jeff wrote: > > I want to match a string which is preceeded by a space or occurs at > > the beginning of the line. I also don't want to catch the preceeding > > character as a group. > > > > I have found both of the following to work > > re.compile('(?:^|\s)string') > > re.compile('(?:\A|\s)string') > > How about r'\bstring' ? It doesn't mean quite the same as \sstring but > it might work for you. > > > > > But would prefer to use the more concise [] notation. However > > re.compile('[^\s]string') > > As the first character in [], ^ means 'not'. > > > Does not work and > > re.compile('[\A\s]string') > > I guess \A doesn't count as a 'character class'? Or do you need to be > using raw strings? > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Tue Feb 1 20:14:21 2005 From: ps_python at yahoo.com (kumar s) Date: Tue Feb 1 20:14:25 2005 Subject: [Tutor] Append function In-Reply-To: Message-ID: <20050201191421.7520.qmail@web53702.mail.yahoo.com> Hi Danny: I have ~50 files in this format: File1: 680:209 3006.3 266:123 250.5 62:393 117.3 547:429 161.5 341:311 546.5 132:419 163.3 98:471 306.3 File 2: 266:123 168.0 62:393 119.3 547:429 131.0 341:311 162.3 132:419 149.5 98:471 85.0 289:215 207.0 75:553 517.0 I am generating these files using this module: f1 = open("test2_cor.txt","r") ana = f1.read().split('\n') ana = ana[:-1] pbs = [] for line in ana: cols = line.split('\t') pb = cols[0] pbs.append(pb) ##########CEL Files section ######## files = glob.glob("c:\files\*.cel") def parSer(file): f1 = open(file,'r') celf = f1.read().split('\n') celfile = celf[24:409624] my_vals = celParser(celfile,pbs) f2 = open(file+'.txt','w') for line in my_vals: f2.write(line+'\t') f2.write('\n') f2.close() def main(): for each in files: parSer(each) main() Because, I asked to write a file with the name of the file as output, it is generating 50 output files for 50 input files. What I am interested in is to append the output to one single file but with tab delimmitation. For example: for each file there are 2 columns. Cor and val file 1 file 2 file 3 file 4 cor val cor val cor val cor val x:x 1345 x:x 5434 x:x 4454 x:x 4462 x:y 3463 x:y 3435 x:y 3435 x:y 3435 Could you suggest a way. Thank you. __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From alan.gauld at freenet.co.uk Tue Feb 1 22:12:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:11:53 2005 Subject: [Tutor] Better structure? References: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> <00af01c507c5$f06ec470$d1b48651@xp> <001701c50817$6f454d90$6d5428cf@JSLAPTOP> Message-ID: <005f01c508a2$b14ec1e0$68b78851@xp> > What, like > global radiusaxis, radiusaxis2 exactly. > > And since there is no input parameter and no return statement > > and you only call start() once... > > Not true. If y == 'clear', then start is called to "redraw" the window. > Very important part. OK, I missed that, but its still better to hide the call to start inside an if name== main clause since otherwise you can't ever import your file without drawing the screen. > I think I'll do that, but of course I'll have to add ValueError -- because > of math domain errors on my function. That's what the try except block is for. In that case just put the ValueError clause in and leave other erors to raise an error stack - that way you get to see the source of the problem. Then wrap your call to start in a try/except to catch the errors and print a message at the outer level. That way its easy to turn error reporting on/off Alan G. From alan.gauld at freenet.co.uk Tue Feb 1 22:23:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:25:13 2005 Subject: [Tutor] Presentation References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <008f01c508a4$43947a30$68b78851@xp> > Any help I can get would be much appreciated - such as > language comparisons, companies and systems that use python, > debates about what python is good for Most of that can be found under the General FAQ on the python web site. And links to other similar material. Alan G From ps_python at yahoo.com Tue Feb 1 22:36:32 2005 From: ps_python at yahoo.com (kumar s) Date: Tue Feb 1 22:36:35 2005 Subject: [Tutor] Append function In-Reply-To: <41FD6E9B.6030200@tds.net> Message-ID: <20050201213632.46115.qmail@web53710.mail.yahoo.com> Hi Kent, Thank you for your suggestion. I keep getting IOError permission denied every time I try the tips that you provided. I tried to lookup on this error and did not get reasonable answer. Is this error something to do with Windows OS? Any suggestions. Thank you K >>> allColumns = [readColumns("C:\Documents and Settings\myfiles")for filePath in file_list] Traceback (most recent call last): File "", line 1, in -toplevel- allColumns = [readColumns("C:\Documents and Settings\myfiles")for filePath in file_list] File "", line 2, in readColumns rows = [line.split() for line in open(filePath)] IOError: [Errno 13] Permission denied: 'C:\\Documents and Settings\\myfiles' >>> > def readColumns(filePath): > rows = [ line.split() for line in > open(filePath) ] > return zip(*rows) > > # list of all the files to read > allFiles = [ 'f1.txt', 'f2.txt' ] > > # both columns from all files > allColumns = [ readColumns(filePath) for filePath in > allFiles ] > > # just the second column from all files > allSecondColumns = [ cols[1] for cols in allColumns > ] > > # a representative first column > col1 = allColumns[0][0] > > # zip it up into rows > allRows = zip(col1, *allSecondColumns) > > for row in allRows: > print '\t'.join(row) > > > Kent __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Tue Feb 1 22:37:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:37:24 2005 Subject: [Tutor] Better structure? References: Message-ID: <00ad01c508a6$3e727910$68b78851@xp> > ever get the chance, you may want to take a look at a book called > Programming Pearls: > > http://www.cs.bell-labs.com/cm/cs/pearls/ > I'll second that. Personally I try to read both books (I have the original 2 volume version!) every couple of years - they are that valuable. Most newbie programmers can learn a lot from Bentley's book(s) - especially about programming for performance. But loads of other tricks too. Alan G. From alan.gauld at freenet.co.uk Tue Feb 1 22:40:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 1 22:40:09 2005 Subject: [Tutor] Programming Challenge C++ and Python References: <3c51d5180502010308149302c2@mail.gmail.com> Message-ID: <00c601c508a6$a7bf4290$68b78851@xp> > I don't have any idea about how to write a plugin but I found out > that the server administrator has written a Plugin Development Kit in > C++ for those who wish to write plugins for the interface.I don't know > C++ so I cannot convert this kit into python scripts. Caveat: I've never done this so don't know how easy it is but... There is a tool called SWIG which is for creating Python(or Perl or Tcl etc) wrappers around C/C++ APIs. So SWIG might be able to wrap your plug-in API for you. But I've no idea how easy that is! Alan G. From jhomme at libcom.com Tue Feb 1 23:15:33 2005 From: jhomme at libcom.com (jhomme) Date: Tue Feb 1 23:17:32 2005 Subject: [Tutor] Introductory Links Message-ID: <9a8eb73ba1935359202338cfbb407fba@libcom.com> -----Original message----- From: "Alan Gauld" alan.gauld@freenet.co.uk Date: Tue, 1 Feb 2005 16:15:14 -0500 To: "jhomme" jhomme@libcom.com Subject: Re: [Tutor] Dictionary Nesting > > Um, thanks for reminding me about the prompt. > > ....work my way through some other stuff before wasting people's > time. > > It was your own time I was thinking of. Its much quicker to > experiment briefly if you think you might know the answer > than to compose an email, send it and then wait for replies! > > Then if you do send a mail you can be much more specific too, > because you know what doesn't work! :-) > > Alan G. > Hi, Is it possible to get a copy of the message sent to us when we first join? I want to follow the links in it so I can learn how to do the research and ask questions on the list. Thanks. Jim From kent37 at tds.net Wed Feb 2 00:00:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 00:00:52 2005 Subject: [Tutor] Append function In-Reply-To: <20050201213632.46115.qmail@web53710.mail.yahoo.com> References: <20050201213632.46115.qmail@web53710.mail.yahoo.com> Message-ID: <42000A1D.9090005@tds.net> You seem to be giving a path to a directory rather than a single file. Also you are putting it in the wrong place, you should edit the allFiles list. Kent kumar s wrote: > Hi Kent, > Thank you for your suggestion. I keep getting > IOError permission denied every time I try the tips > that you provided. I tried to lookup on this error and > did not get reasonable answer. Is this error something > to do with Windows OS? > > Any suggestions. > > Thank you > K > > >>>>allColumns = [readColumns("C:\Documents and > > Settings\myfiles")for filePath in file_list] > > Traceback (most recent call last): > File "", line 1, in -toplevel- > allColumns = [readColumns("C:\Documents and > Settings\myfiles")for filePath in file_list] > File "", line 2, in readColumns > rows = [line.split() for line in open(filePath)] > IOError: [Errno 13] Permission denied: 'C:\\Documents > and Settings\\myfiles' > > > > >>def readColumns(filePath): >> rows = [ line.split() for line in >>open(filePath) ] >> return zip(*rows) >> >># list of all the files to read >>allFiles = [ 'f1.txt', 'f2.txt' ] >> >># both columns from all files >>allColumns = [ readColumns(filePath) for filePath in >>allFiles ] >> >># just the second column from all files >>allSecondColumns = [ cols[1] for cols in allColumns >>] >> >># a representative first column >>col1 = allColumns[0][0] >> >># zip it up into rows >>allRows = zip(col1, *allSecondColumns) >> >>for row in allRows: >> print '\t'.join(row) >> >> >>Kent > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > From bvande at po-box.mcgill.ca Wed Feb 2 00:09:01 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 2 00:09:17 2005 Subject: [Tutor] Introductory Links In-Reply-To: <9a8eb73ba1935359202338cfbb407fba@libcom.com> References: <9a8eb73ba1935359202338cfbb407fba@libcom.com> Message-ID: <42000C0C.9030003@po-box.mcgill.ca> jhomme said unto the world upon 2005-02-01 17:15: > Hi, Is it possible to get a copy of the message sent to us when we > first join? I want to follow the links in it so I can learn how to > do the research and ask questions on the list. > > Thanks. > > Jim Hi Jim, I don't still have a copy of my Welcome msg. But the following links all are good places to look: The Python wwiki's beginner's page Search com.lang.python The Python Wiki page -- not the front, but the recent changes which is how I like to enter it. The Python Sidebar for Mozilla -- works for FireFox, too. A useful tool if you're using the right [ambiguity intended ;-)] browser. How To Ask Questions The Smart Way by Eric Raymond. The Tutor list won't bite you if you don't follow any of the advice in that essay. But it is a very useful thing to read to learn how best to frame your questions so as to get maximum return from everyone's effort (your and those who answer you both). HTH, Brian vdB From alan.gauld at freenet.co.uk Wed Feb 2 00:11:00 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 00:10:50 2005 Subject: [Tutor] Introductory Links References: <9a8eb73ba1935359202338cfbb407fba@libcom.com> Message-ID: <012701c508b3$546a0690$68b78851@xp> > > Then if you do send a mail you can be much more specific too, > > because you know what doesn't work! :-) > > > Is it possible to get a copy of the message sent to us when we first join? >I want to follow the links in it so I can learn how to do the research > and ask questions on the list. I'm not sure which message you mean, but assuming its the one you get when you start a new thread on tutor then I guess thats a question for the list admin team. It sounds emminently sensible to send a welcome message with some kind of set of intro links in it. Its so long sice I joined I can't recall what happened!! Danny? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From ismaelgf at adinet.com.uy Wed Feb 2 00:08:19 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Wed Feb 2 00:28:38 2005 Subject: [Tutor] Classes Message-ID: <42000BE3.60309@adinet.com.uy> Hello. I was just wondering, what magic can you do with classes? I mean, things like "class Name(Exception)" or "class Name(threading.Thread), which other classes are interesting to subclass? I've seen Object too, but I don't understand what it does. Thanks Ismael From maxnoel_fr at yahoo.fr Wed Feb 2 00:44:28 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 2 00:44:35 2005 Subject: [Tutor] Classes In-Reply-To: <42000BE3.60309@adinet.com.uy> References: <42000BE3.60309@adinet.com.uy> Message-ID: <6c4daf2ca96450b2a6b0606bfb4313af@yahoo.fr> On Feb 1, 2005, at 23:08, Ismael Garrido wrote: > Hello. > > I was just wondering, what magic can you do with classes? I mean, > things like "class Name(Exception)" or "class Name(threading.Thread), > which other classes are interesting to subclass? I've seen Object too, > but I don't understand what it does. Basically, Object is the class all your classes should be deriving from (when you do that, you're using "new-style classes"). It's the root in the class hierarchy of Python. This gives you access to a lot of nifty features for free, such as properties. Oh, and the best classes are those you create yourself, of course :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kp8 at mac.com Wed Feb 2 00:53:13 2005 From: kp8 at mac.com (kevin parks) Date: Wed Feb 2 00:53:18 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <20050113181855.9CBEC1E4014@bag.python.org> References: <20050113181855.9CBEC1E4014@bag.python.org> Message-ID: <80a3c832a484b4eeb57c06111afbb931@mac.com> Greetings, I am working on a program to produce patterns. What would like is for it to exhaustively produce all possible permutations of a sequence of items but for each permutation produce variations, and also a sort of stutter based on probability / weighted randomess. Let us say we have tiles of four primary colors: ['Red', 'Blue', 'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown'] We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green'] Now I would like to pick the primary colors substitute (say 30% chance for each element) so instead of our plain ['Red', 'Blue', 'Yellow', 'Green'] we might end up with: ['Red', 'Navy_Blue', 'Yellow', 'Forest_Green'] or ['Maroon', 'Navy_Blue', 'Yellow', 'Green'] Whatever... The main point is that sometimes the original color is retained and sometimes the dark color is substituted. Now I want to take this list and sometimes stutter an element so that there is, let us say a 50% chance for each element, that it is stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So that we could get: ['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow', 'Green'] The program would quit when all 24 (in the case of 4 elements) was exhausted. I have code that makes weighted randomness. I have code that makes permutations, but I am having trouble putting this all together... While i work on it though that i might ask for help... I'd like for the code to be reusable and am building a library of functions for patterns. cheers, kevin ### This is not mine, it is from a python book... I believe the Lutz book def permute(list): if not list: # shuffle any sequence return [list] # empty sequence else: res = [] for i in range(len(list)): rest = list[:i] + list[i+1:] # delete current node for x in permute(rest): # permute the others res.append(list[i:i+1] + x) # add node at front return res mport random ### This this is mine, but seems to work anyway hee hee def windex(lst): '''an attempt to make a random.choose() function that makes weighted choices accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x)''' n = random.uniform(0, 1) for item, weight in lst: if n < weight: break n = n - weight return item From apple_py at biz-experts.net Wed Feb 2 02:32:50 2005 From: apple_py at biz-experts.net (Victor Rex) Date: Wed Feb 2 02:33:00 2005 Subject: [Tutor] Presentation In-Reply-To: <41FF5EA9.3090000@tds.net> References: <003f01c5087c$117cb6c0$012118ac@SP1179> <41FF5EA9.3090000@tds.net> Message-ID: <42002DC2.1030202@biz-experts.net> This is a great series of links. I found the following on Pythology too: Python Spotting http://pythonology.org/spotting Best of luck. Kent Johnson wrote: > Eric Raymond's "Why Python?" essay is a classic: > http://pythonology.org/success&story=esr > > Bruce Eckel's "Why I love Python" presentation is here: > http://64.78.49.204/pub/eckel/LovePython.zip > > This page has lots of links you might be interested in: > http://www.ferg.org/python_presentations/index.html > > This page has links to language comparisons: > http://www.python.org/moin/LanguageComparisons > > Good luck! > Kent > > Paul Hartley wrote: > >> I am trying to get Python established here in the Philippines. >> Currently I am in charge of operations at a business based in Manila >> and I have asked my IT staff to start using Python (with some success). >> >> A local university has now asked that I give a talk to their IT >> people on Python - so here is an opportunity to spread the word and >> get some more converts and maybe introduce python into their computer >> science courses. >> >> Any help I can get would be much appreciated - such as language >> comparisons, companies and systems that use python, debates about >> what python is good for (almost everything), examples of elegant code.. >> >> When I was a member of the Forth Interest Group in the USA we learned >> that Forth was used on the buggy that went to mars, that it started >> life controlling huge radio telescopes which only had 4k (yes 4k) of >> memory for both language and application. >> >> Anything like the above concerning python would be useful. >> >> Any other suggestions would help also, the audience will have >> computers, so a demonstration of small workshop would also be good - >> the presentation/session is for 4 hours on the 10th February. >> >> Paul >> >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Feb 2 02:43:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 02:43:56 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <80a3c832a484b4eeb57c06111afbb931@mac.com> References: <20050113181855.9CBEC1E4014@bag.python.org> <80a3c832a484b4eeb57c06111afbb931@mac.com> Message-ID: <42003058.6040502@tds.net> kevin parks wrote: > Greetings, > > I am working on a program to produce patterns. What would like is for it > to exhaustively produce all possible permutations of a sequence of > items but for each permutation produce variations, and also a sort of > stutter based on probability / weighted randomess. > > Let us say we have tiles of four primary colors: ['Red', 'Blue', > 'Green', 'Yellow']. Now we also have 4 alternatives or substitutes for > each color ['Maroon', 'Navy_Blue', 'Forest_Green', 'Dark_Brown'] > > We pick a unique permutation, say: ['Red', 'Blue', 'Yellow', 'Green'] > > Now I would like to pick the primary colors substitute (say 30% chance > for each element) so instead of our plain > > ['Red', 'Blue', 'Yellow', 'Green'] > > we might end up with: > > ['Red', 'Navy_Blue', 'Yellow', 'Forest_Green'] > > or > > ['Maroon', 'Navy_Blue', 'Yellow', 'Green'] > > Whatever... The main point is that sometimes the original color is > retained and sometimes the dark color is substituted. > > Now I want to take this list and sometimes stutter an element so that > there is, let us say a 50% chance for each element, that it is > stuttered, and it may be repeated 1 (34%), 2(66%), or 3(33%) times. So > that we could get: > > ['Maroon','Maroon','Navy_Blue', 'Yellow','Yellow','Yellow','Yellow', > 'Green'] > > The program would quit when all 24 (in the case of 4 elements) was > exhausted. > > I have code that makes weighted randomness. I have code that makes > permutations, but I am having trouble putting this all together... While > i work on it though that i might ask for help... I'd like for the code > to be reusable and am building a library of functions for patterns. If you had a randomizeList function and a stutterList function then your top-level function would look like this: permutations = permute(['Red', 'Blue', 'Yellow', 'Green']) permutations = [ randomizeList(list) for list in permutations ] permutations = [ stutterList(list) for list in permutations ] In other words you start with the basic permutations, then apply the randomize function to each permutation, then apply the stutter function. The randomizeList function should walk through the list, find the right randomize list for that list element (a dict could help with that - look up the list element and get the randomize list), and build a new list with the randomized values. The stutterList function walks through the list building a new list with possibly repeated elements. HTH, Kent > > cheers, > kevin > > > ### This is not mine, it is from a python book... I believe the Lutz book > > def permute(list): > if not list: # shuffle any > sequence > return [list] # empty sequence > else: > res = [] > for i in range(len(list)): > rest = list[:i] + list[i+1:] # delete current > node > for x in permute(rest): # permute the > others > res.append(list[i:i+1] + x) # add node at front > return res > > mport random > > ### This this is mine, but seems to work anyway hee hee > > def windex(lst): > '''an attempt to make a random.choose() function that makes > weighted choices > > accepts a list of tuples with the item and probability as a pair > like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] > >>> y=windex(x)''' > n = random.uniform(0, 1) > for item, weight in lst: > if n < weight: > break > n = n - weight > return item > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Tue Feb 1 05:42:12 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 02:58:07 2005 Subject: [Tutor] carriage return on windows References: <41FC40C8.1050308@fastmail.fm><166443577941.20050129211823@columbus.rr.com> <8b67b003454f617189945135968facfc@yahoo.fr> <001b01c50675$0a2f00c0$275328cf@JSLAPTOP> <0943e4bba36230c65951716acb5f1241@yahoo.fr> <000601c5067b$ca454ad0$d25428cf@JSLAPTOP><41FC558A.7090402@gmail.com> <41FEC6F7.3050301@biz-experts.net> Message-ID: <005301c50818$6620f380$68b78851@xp> > I played around with this output issue and I love the way it works. > Now, how do you do this in *nix? I tried the same approach and I get a > blank line for 5 seconds (or whatever number of cycles you have on your > example) and the a final line with the last value of the iterable. On Unix it is easiest to use the curses library. There are so many different terminals in use on Unix that no single set of control codes can be guaranteed to work. Curses provides an abstract terminal that you can control by positioning the cursor at x,y coordinates etc. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Tue Feb 1 16:20:28 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 2 03:02:46 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net> Message-ID: <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> I don't know who's going crazy here... but I checked that straight from the python 2.4 interpreter... Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> a = "go on long buddy" >>> a.lstrip("gonl") ' on long buddy' >>> a = "go long on log buddy!" >>> a.lstrip('gonl') ' long on log buddy!' >>> In both cases, lstrip just removed the first word... I don't see how this code is broken. Hope we figure it out. Jacob > This code is broken. lstrip('gonl ') will remove *all* leading g, o, n, l > and space, in any order: > >>> s='go long on log buddy!' > >>> s.lstrip('gonl ') > 'buddy!' > > Instead of y.lstrip('gonl ') you should use y[5:] or maybe y[len('gonl > '):] > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Wed Feb 2 03:12:00 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 2 03:11:54 2005 Subject: [Tutor] Tkinter questions References: Message-ID: <001d01c508cc$9e02ee70$3b5428cf@JSLAPTOP> I suggest looking at Introduction to Tkinter. http://www.pythonware.com/library/tkinter/introduction/index.htm HTH, Jacob > Hello, > I got some Tkinter questions that I need the answer for to complete a > little project of mine: > 1. How can I make the program to open in a X*Y sized window ? > 2. How can I open another window from the first one (without closing it) ? > 3. How can I add a file browser for my app (like the one you get when > you press "Save as..." in windows apps) ? > 4. How do I configure the font size on the Text widget (its realy > huge, and I would like to change it to somthing like 12). > 5. [OT] Do you know any web-sites that I can store my project at (like > sourceforge and others) ? > > This is all for now :) > Thanks in advence . > > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Wed Feb 2 03:14:10 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Feb 2 03:13:23 2005 Subject: [Tutor] Better structure? In-Reply-To: <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> References: <41FF6082.70005@tds.net> <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> Message-ID: <42003772.4010808@ccvcorp.com> Jacob S. wrote: > I don't know who's going crazy here... but I checked that straight from > the python 2.4 interpreter... >>> a = "go on long buddy" >>> a.lstrip('gonl') ' on long buddy' >>> a.lstrip('gonl ') 'buddy' >>> Note that in the second case, I've included a space in the lstrip() parameter. lstrip() is essentially saying "remove all leading characters until you find a character that's not in this sequence" -- a space counts as a character. (Took me trying it out before I saw this, so don't feel bad. ;) ) Jeff Shannon Technician/Programmer Credit International From keridee at jayco.net Wed Feb 2 03:23:10 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 2 03:22:54 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> <42003772.4010808@ccvcorp.com> Message-ID: <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> So, how would one go about this in a non broken code way? Don't they have something like what I'm requesting. It seems to me that a few things are flawed in the standard distribution. Little things like the overlooking of adding a method or function to decimal for returning an instance with x places right of the decimal. I know of quantize, but that's junk and not simple. Also why shouldn't string methods include stuff like lstrip which do precisely what I request? Maybe because they don't want to bother putting def mylstrip(string,stripstring): return string[len(stripstring):] as a method or something? Messy, just plain messy. Jacob Schmidt > Jacob S. wrote: > >> I don't know who's going crazy here... but I checked that straight from >> the python 2.4 interpreter... > > >>> a = "go on long buddy" > >>> a.lstrip('gonl') > ' on long buddy' > >>> a.lstrip('gonl ') > 'buddy' > >>> > > Note that in the second case, I've included a space in the lstrip() > parameter. lstrip() is essentially saying "remove all leading characters > until you find a character that's not in this sequence" -- > a space counts as a character. (Took me trying it out before I saw this, > so don't feel bad. ;) ) > > Jeff Shannon > Technician/Programmer > Credit International > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From jeff at ccvcorp.com Wed Feb 2 03:37:00 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Feb 2 03:36:12 2005 Subject: [Tutor] Better structure? In-Reply-To: <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> <42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> Message-ID: <42003CCC.5060300@ccvcorp.com> Jacob S. wrote: > So, how would one go about this in a non broken code way? Don't they > have something like what I'm requesting. No, but it's pretty easy to do: def exact_lstrip(astring, stripstring): if astring.startswith(stripstring): astring = astring[len(stripstring):] return astring > [...] Also why > shouldn't string methods include stuff like lstrip which do precisely > what I request? Maybe it's because other people would have different expectations? The current implementation of strip() (including lstrip() and rstrip()) seems to work well for the most common case, and I'm not sure that your expectation is necessarily more generally useful than the current behavior. Especially given that your behavior is the one that's easier to hand-code if it's desired. Jeff Shannon Technician/Programmer Credit International From kp8 at mac.com Wed Feb 2 03:42:13 2005 From: kp8 at mac.com (kevin parks) Date: Wed Feb 2 03:42:19 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: <20050202015810.47F641E4004@bag.python.org> References: <20050202015810.47F641E4004@bag.python.org> Message-ID: Tremendously helpful!!!! One question though. How can i pluck a unique item from my exhaustive list of permutations without repeats making sure that each one is used once? Like filling a bag, shaking it, and then picking from the bag and removing that item from the bag so it isn't used again.... -k On Feb 1, 2005, at 8:58 PM, tutor-request@python.org wrote: > f you had a randomizeList function and a stutterList function then > your top-level function would > look like this: > > permutations = permute(['Red', 'Blue', 'Yellow', 'Green']) > permutations = [ randomizeList(list) for list in permutations ] > permutations = [ stutterList(list) for list in permutations ] > > In other words you start with the basic permutations, then apply the > randomize function to each > permutation, then apply the stutter function. > > The randomizeList function should walk through the list, find the > right randomize list for that list > element (a dict could help with that - look up the list element and > get the randomize list), and > build a new list with the randomized values. > > The stutterList function walks through the list building a new list > with possibly repeated elements. > > HTH, > Kent From p.hartley at spitech.com Wed Feb 2 17:57:57 2005 From: p.hartley at spitech.com (Paul Hartley) Date: Wed Feb 2 03:55:58 2005 Subject: [Tutor] Presentation References: <003f01c5087c$117cb6c0$012118ac@SP1179> Message-ID: <016a01c50948$5877aae0$012118ac@SP1179> Thank you for all your feedback on this - powerpoint presentations and all!! Not only is the language amazing but the community is fantastic!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050202/1411e8ec/attachment.html From carroll at tjc.com Wed Feb 2 04:04:01 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Feb 2 04:04:07 2005 Subject: [Tutor] Presentation In-Reply-To: <016a01c50948$5877aae0$012118ac@SP1179> Message-ID: On Wed, 2 Feb 2005, Paul Hartley wrote: > Not only is the language amazing but the community is fantastic!! The community is one of the things I particularly like about Python. I always hated asking a question in the Perl newsgroups; although you usually got an answer, you were almost certain to be told you're stupid for not already knowing it. From kent37 at tds.net Wed Feb 2 04:38:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 04:38:54 2005 Subject: [Tutor] permutations, patterns, and probability In-Reply-To: References: <20050202015810.47F641E4004@bag.python.org> Message-ID: <42004B49.4070004@tds.net> kevin parks wrote: > Tremendously helpful!!!! One question though. How can i pluck a unique > item from my exhaustive list of permutations without repeats making sure > that each one is used once? Like filling a bag, shaking it, and then > picking from the bag and removing that item from the bag so it isn't > used again.... Use random.shuffle() to 'shake' the list. Then use pop() to remove an item: >>> import random >>> l=range(10) >>> random.shuffle(l) >>> l [4, 5, 0, 8, 9, 6, 2, 1, 7, 3] >>> l.pop() 3 >>> l.pop() 7 >>> l.pop() 1 >>> l [4, 5, 0, 8, 9, 6, 2] Kent From nbbalane at gmail.com Wed Feb 2 08:10:36 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed Feb 2 08:10:39 2005 Subject: [Tutor] how to separate hexadecimal Message-ID: <2cad209005020123107fb43105@mail.gmail.com> i have a 4 digit hex number (2 bytes) and i want to separate it into 2 digit hex (1 byte each) meaning i want to get the upper byte and the lower byte since i am going to add this two. how am i going to do this? should i treat it just like a normal string? please help, thanks. ex. hexa = '0x87BE" # what i want to do is: a = 0x87, b = 0xBE # so that i could do this: c = a + b #which should be equal to 0x145 From kraus at hagen-partner.de Wed Feb 2 09:12:55 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 2 09:12:26 2005 Subject: [Tutor] Re: how to separate hexadecimal In-Reply-To: <2cad209005020123107fb43105@mail.gmail.com> References: <2cad209005020123107fb43105@mail.gmail.com> Message-ID: jrlen balane wrote: > i have a 4 digit hex number (2 bytes) and i want to separate it into 2 > digit hex (1 byte each) meaning i want to get the upper byte and the > lower byte since i am going to add this two. > how am i going to do this? > should i treat it just like a normal string? > please help, thanks. > > ex. hexa = '0x87BE" # what i want to do is: > a = 0x87, b = 0xBE # so that i could do this: > c = a + b #which should be equal to 0x145 Not sure where you get hexa from, but given your example you can use int(x, base) with base = 16 to convert your string to an integer and then use the %x formatstring: >>> hexa = '0x87BE' >>> upper = int(hexa[2:4], 16) >>> lower = int(hexa[4:6], 16) >>> print '0x%x + 0x%x = 0x%x' % (upper, lower, upper+lower) 0x87 + 0xbe = 0x145 HTH, Wolfram From alan.gauld at freenet.co.uk Wed Feb 2 09:32:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 09:32:27 2005 Subject: [Tutor] Classes References: <42000BE3.60309@adinet.com.uy> Message-ID: <014d01c50901$cde680e0$68b78851@xp> > I was just wondering, what magic can you do with classes? You can define your own types. Thats what classes are for. Those types can be as 'magic' as your imagination (and programming skills!) allow. > other classes are interesting to subclass? I've seen Object too, but I > don't understand what it does. It's 'object' - lowercase o - and that is the way to tell Python to use "new-style" classes, which are not very new now! Essentially all the basic types in Python are descended from object and the object class provides access to some special features that won't be available if you don't subclass object (as in classic style classes) OTOH subclsassing object does add overhead to your class and so makes it a bit slower. You can also subclass any other Python type, thus class bigfloat(float): .... would provide a special type of floating point number - maybe with unlimited precision, provided you wrote the code to allow that... Finally classes are themselves objects and can be used as a way of monitoring and controlling a collection of objects. This is often called meta-programming and if you want to twist your head in knots read the paper that Guido wrote on meta programming in Python :-) Read the OOP topic in my tutorial for more about using classes. (but not about meta programming!! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Feb 2 09:35:47 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 09:35:26 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net> <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> Message-ID: <016101c50902$323efae0$68b78851@xp> > I don't know who's going crazy here... but I checked that straight from the > python 2.4 interpreter... > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> a = "go on long buddy" > >>> a.lstrip("gonl") > ' on long buddy' > >>> a = "go long on log buddy!" > >>> a.lstrip('gonl') > ' long on log buddy!' > >>> > > In both cases, lstrip just removed the first word... I don't see how this > code is broken. It removed all the g,o,n & l's up till it found a character that wasn't in your list - a space. Thats what you told it to do. If you want the space stripped add one to your list... Alan G. From dyoo at hkn.eecs.berkeley.edu Wed Feb 2 09:40:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 2 09:41:05 2005 Subject: [Tutor] Better structure? In-Reply-To: <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> Message-ID: On Tue, 1 Feb 2005, Jacob S. wrote: > Also why shouldn't string methods include stuff like lstrip which do > precisely what I request? Hi Jacob, I think the confusion here is that, in Python, strings can be considered a concrete single thing, but they can also be considered an ordered collection of characters. And we might not even care about order. As a concrete example, we might write a function that sees if something is a vowel: ### >>> def isvowel(letter): ... return len(letter) == 1 and letter in "aeiou" ... ### Here, we're using a string simply as a collection of characters, but our definition doesn't really depend on the order of the vowels. So some functions will use strings merely because they're good containers of letters. lstrip() (and rstrip()) are designed so that they consider their arguments a collection of characters to strip off, but it doesn't care about the order of the characters. Admittedly, the documentation of lstrip() doesn't really spell this out with perfect clarity: """ lstrip([chars]) Return a copy of the string with leading characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the beginning of the string this method is called on. """ So this can definitely be improved. The documentation of lstrip() should emphasize that 'chars' here is used to define the set of characters that it'll toss out, to keep people aware that it doesn't care about the sequence-y nature of its input string. > Maybe because they don't want to bother putting > > def mylstrip(string,stripstring): > return string[len(stripstring):] The implementation of rstrip() (the cousin of lstrip()) does come in really handy when we're dealing with line terminators, since we can "chomp()" a line by doing: ### def chomp(line): return line.rstrip('\r\n') ### It is debatable what lstrip() and rstrip() should consider as the common case. The library designers decided the behavior they felt would help people the most, but that may not handle all the ways we might like to use it. But, then, that's why we have 'def'. *grin* Best of wishes to you! From alan.gauld at freenet.co.uk Wed Feb 2 09:52:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 09:51:54 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> Message-ID: <016a01c50904$81e75db0$68b78851@xp> Jacob, Writing library code is a difficult and unrewarding task - I've been there so I sympathise, however... > So, how would one go about this in a non broken code way? Don't they have > something like what I'm requesting. Its not broken, its just different to what you want. What you want is much simpler than what lstrip does so you can easily code your requirements. Try writing the code to do what lstrip actually does - its much harder. So the library includes the more difficult function and lets you code the easy ones. > It seems to me that a few things are flawed in the standard distribution. No library is perfect - you should try using C! But the Python library isually has good reasons for its apparent limitations. > Little things like the overlooking of adding a method or function to decimal > for returning an instance with x places right of the decimal. But there is very little need to do that. Usually you only want to do that in presentation - ie printing. Thus the mechanism for doing that is in the string formatting code - where it makes sense. Why would limiting the precision of the internal number representation be something you'd want to do? Very occassionally maybe, but in those cases its easy to fake (and it is a fake because the number is in binary and not true decimal so its always an approximation - in any language!) > quantize, but that's junk and not simple. You mean it does a complex job and not the one youd like it to do? :-) > Also why shouldn't string methods include stuff like > lstrip which do precisely what I request? strings do include lstrip() but as I said they couldn't predict what you thought it shjould do, so they built it to do what they thought would be the most generally useful function. Stripping off a string literal is such a trivial programming task that you can easily write that yourself. You can even subclass string and make it a method if you like. > Maybe because they don't want to bother putting > > def mylstrip(string,stripstring): > return string[len(stripstring):] > > as a method or something? > Messy, just plain messy. Such a method would indeed be plain messy. Do you really want code like this: >>> s = "Here is a longish string" >>> s.mylstrip('foo') >>> print s e is a longish string >>> s.mylstrip('supercalifragilisticexpalidocious') >>> print s >>> I suspect your function should probably be: def mylstrip(str,stripstring): if str.startswith(stripstring) and len(stripstring) < len(str): return str[len(stripstring):] But thats just my guess at what *you* really want... And finally remember that Python is built by volunteers mostly. You should be pleased the *bothered* to write any of it! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld > > Jacob Schmidt > > > > Jacob S. wrote: > > > >> I don't know who's going crazy here... but I checked that straight from > >> the python 2.4 interpreter... > > > > >>> a = "go on long buddy" > > >>> a.lstrip('gonl') > > ' on long buddy' > > >>> a.lstrip('gonl ') > > 'buddy' > > >>> > > > > Note that in the second case, I've included a space in the lstrip() > > parameter. lstrip() is essentially saying "remove all leading characters > > until you find a character that's not in this sequence" -- > > a space counts as a character. (Took me trying it out before I saw this, > > so don't feel bad. ;) ) > > > > Jeff Shannon > > Technician/Programmer > > Credit International > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From dyoo at hkn.eecs.berkeley.edu Wed Feb 2 09:59:44 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 2 09:59:50 2005 Subject: [Tutor] Presentation In-Reply-To: Message-ID: > The community is one of the things I particularly like about Python. I > always hated asking a question in the Perl newsgroups; although you > usually got an answer, you were almost certain to be told you're stupid > for not already knowing it. Hi Terry, Just to act as Devil's advocate: the programming language communities are large enough to support subcultures. So the experiences you have had in the seedy corners of comp.lang.perl are probably not representative of the Perl community as a whole. Some newsgroups are notoriously noisy, and even comp.lang.python can get a little hairy at times. The mailing list communities tend to be a bit more civilized because they have a strong topical focus. For people who do want to learn Perl, the web site: http://learn.perl.org/ and Casey West's 'beginners' Perl mailing list: http://www.nntp.perl.org/group/perl.beginners/ appear to be excellent resources. So the Perl community there is also doing what they can to help folks learn Perl. We, as Python programmers, should do one step better: we should help folks learn programming as well as Python. *grin* Best of wishes to you! From alan.gauld at freenet.co.uk Wed Feb 2 10:07:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 2 10:07:36 2005 Subject: [Tutor] Re: how to separate hexadecimal References: <2cad209005020123107fb43105@mail.gmail.com> Message-ID: <018101c50906$a14d5220$68b78851@xp> > >>> hexa = '0x87BE' > >>> upper = int(hexa[2:4], 16) > >>> lower = int(hexa[4:6], 16) FWIW : You don't need to strip the '0x' from the front, int() is smart enough to do that automatically for base 16 conversions... Alan G. From cyresse at gmail.com Wed Feb 2 10:12:07 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 2 10:12:11 2005 Subject: [Tutor] Presentation In-Reply-To: References: Message-ID: Hi Danny, I think that learning Python naturally leads to learning programming. It's like learning to fly, you learn to fly in a Cessna or Piper Cherokee. Simple, elegant, easy to operate. You can then focus on the art of flying, not on how exactly you lower the flaps. Then, once you're good at flying, you move to the Pitt's Special. (Actually could you imagine a plane built by Perl enthusiasts... How do I lower the flaps? Well, you can push this button, or pull that lever, or lean to the right, or you could install this cool module that lowers them when you wink your left eye twice in 5 seconds. Remember, there's more than one way to do it!) Regards, Liam Clarke On Wed, 2 Feb 2005 00:59:44 -0800 (PST), Danny Yoo wrote: > > > > The community is one of the things I particularly like about Python. I > > always hated asking a question in the Perl newsgroups; although you > > usually got an answer, you were almost certain to be told you're stupid > > for not already knowing it. > > Hi Terry, > > Just to act as Devil's advocate: the programming language communities are > large enough to support subcultures. So the experiences you have had in > the seedy corners of comp.lang.perl are probably not representative of the > Perl community as a whole. > > Some newsgroups are notoriously noisy, and even comp.lang.python can get a > little hairy at times. The mailing list communities tend to be a bit more > civilized because they have a strong topical focus. > > For people who do want to learn Perl, the web site: > > http://learn.perl.org/ > > and Casey West's 'beginners' Perl mailing list: > > http://www.nntp.perl.org/group/perl.beginners/ > > appear to be excellent resources. So the Perl community there is also > doing what they can to help folks learn Perl. > > We, as Python programmers, should do one step better: we should help folks > learn programming as well as Python. *grin* > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Feb 2 10:58:47 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 2 10:58:51 2005 Subject: [Tutor] Better structure? In-Reply-To: <016a01c50904$81e75db0$68b78851@xp> References: <41FF6082.70005@tds.net> <000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP> <42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> Message-ID: Hello all, > > So, how would one go about this in a non broken code way? Don't they > have > > something like what I'm requesting. If not,it's a challenge you can implement yourself! Ever use QBasic? Had a command - a$ = inkey$(1) Which would return a key press as a$. Very handy for 'press any key. It's next to the space bar. Honest' dialogues. Anyway, I come to Python, I want inkey$ damnit! So, I examine, and build it - import msvcrt def inkey(): print "Press any key. It's next to the space bar. Honest." while not msvcrt.kbhit(): pass return Save it, and et voila. Anytime I want my inkey, I import a file called pause, and call pause.inkey(). Now, how many other peoples would need that? I use string.lstrip() in the same way you do - to strip prefixes. What Kent has mentioned is a caveat on using it, that's all. > > And finally remember that Python is built by volunteers mostly. > You should be pleased the *bothered* to write any of it! > Exactly. You shouldn't complain that something free doesn't have the precise features you require. If you installed Linux and you can't play your DirectX capable games, should Linux support DirectX just for you, or should you install Windows? Don't mean to sound too censorious, but the Python library is fantastic, and it's free. It's got some twists, but it's mostly documented and usually works. Not bad for $0.00 eh? Regards, Liam Clarke On Wed, 2 Feb 2005 08:52:20 -0000, Alan Gauld wrote: > Jacob, > > Writing library code is a difficult and unrewarding task > - I've been there so I sympathise, however... > > > So, how would one go about this in a non broken code way? Don't they > have > > something like what I'm requesting. > > Its not broken, its just different to what you want. > What you want is much simpler than what lstrip does > so you can easily code your requirements. > Try writing the code to do what lstrip actually does > - its much harder. So the library includes the more > difficult function and lets you code the easy ones. > > > It seems to me that a few things are flawed in the standard > distribution. > > No library is perfect - you should try using C! > > But the Python library isually has good reasons for its > apparent limitations. > > > Little things like the overlooking of adding a method or function to > decimal > > for returning an instance with x places right of the decimal. > > But there is very little need to do that. Usually you only want > to do that in presentation - ie printing. Thus the mechanism > for doing that is in the string formatting code - where it > makes sense. Why would limiting the precision of the internal > number representation be something you'd want to do? Very > occassionally maybe, but in those cases its easy to fake > (and it is a fake because the number is in binary and not > true decimal so its always an approximation - in any language!) > > > quantize, but that's junk and not simple. > > You mean it does a complex job and not the one youd like it to do? :-) > > > Also why shouldn't string methods include stuff like > > lstrip which do precisely what I request? > > strings do include lstrip() but as I said they couldn't predict > what you thought it shjould do, so they built it to do what > they thought would be the most generally useful function. > Stripping off a string literal is such a trivial programming > task that you can easily write that yourself. You can even > subclass string and make it a method if you like. > > > Maybe because they don't want to bother putting > > > > def mylstrip(string,stripstring): > > return string[len(stripstring):] > > > > as a method or something? > > Messy, just plain messy. > > Such a method would indeed be plain messy. > Do you really want code like this: > > >>> s = "Here is a longish string" > >>> s.mylstrip('foo') > >>> print s > e is a longish string > >>> s.mylstrip('supercalifragilisticexpalidocious') > >>> print s > > >>> > > I suspect your function should probably be: > > def mylstrip(str,stripstring): > if str.startswith(stripstring) and > len(stripstring) < len(str): > return str[len(stripstring):] > > But thats just my guess at what *you* really want... > > And finally remember that Python is built by volunteers mostly. > You should be pleased the *bothered* to write any of it! > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > Jacob Schmidt > > > > > > > Jacob S. wrote: > > > > > >> I don't know who's going crazy here... but I checked that > straight from > > >> the python 2.4 interpreter... > > > > > > >>> a = "go on long buddy" > > > >>> a.lstrip('gonl') > > > ' on long buddy' > > > >>> a.lstrip('gonl ') > > > 'buddy' > > > >>> > > > > > > Note that in the second case, I've included a space in the > lstrip() > > > parameter. lstrip() is essentially saying "remove all leading > characters > > > until you find a character that's not in this sequence" -- > > > a space counts as a character. (Took me trying it out before I > saw this, > > > so don't feel bad. ;) ) > > > > > > Jeff Shannon > > > Technician/Programmer > > > Credit International > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From ewald.ertl at hartter.com Wed Feb 2 11:19:45 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Wed Feb 2 11:19:51 2005 Subject: [Tutor] how to separate hexadecimal In-Reply-To: <2cad209005020123107fb43105@mail.gmail.com> References: <2cad209005020123107fb43105@mail.gmail.com> Message-ID: <20050202111945.000025cf@sunray2.hartter.com> Hi! Using binary operations: >>> a='0x87BE' >>> str(hex(int(a,16) & 0xFF)) '0xbe' >>> str(hex((int(a,16) & 0xFF00) / 0xFF)) '0x87' >>> HTH Ewald on Wed, 2 Feb 2005 15:10:36 +0800 jrlen balane wrote : --------------------------------------------------------------------------------------------- jrlen balane > i have a 4 digit hex number (2 bytes) and i want to separate it into 2 jrlen balane > digit hex (1 byte each) meaning i want to get the upper byte and the jrlen balane > lower byte since i am going to add this two. jrlen balane > how am i going to do this? jrlen balane > should i treat it just like a normal string? jrlen balane > please help, thanks. jrlen balane > jrlen balane > ex. hexa = '0x87BE" # what i want to do is: jrlen balane > a = 0x87, b = 0xBE # so that i could do this: jrlen balane > c = a + b #which should be equal to 0x145 jrlen balane > _______________________________________________ jrlen balane > Tutor maillist - Tutor@python.org jrlen balane > http://mail.python.org/mailman/listinfo/tutor jrlen balane > ------------------- end ---------------------- From kent37 at tds.net Wed Feb 2 12:05:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 12:05:43 2005 Subject: [Tutor] How to sum rows and columns of a matrix? In-Reply-To: References: <41FE7477.4020403@aon.at> Message-ID: <4200B403.4020606@tds.net> Liam Clarke wrote: > There's a specific package for arrays > > http://www.stsci.edu/resources/software_hardware/numarray > > that implements array mathematics. I use it for pixel map manipulation > in pygame, so it's relatively fast. Here is one way to do what you want using numarray: >>> import numarray Create a 4x4 array: >>> m=numarray.array(range(16),shape=(4,4)) >>> m array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) Row access: >>> m[1] array([4, 5, 6, 7]) Column access: >>> m[:,1] array([ 1, 5, 9, 13]) Sum all the rows: >>> [sum(m[i]) for i in range(4)] [6, 22, 38, 54] Sum all the columns: >>> [sum(m[:,i]) for i in range(4)] [24, 28, 32, 36] Kent > > > On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl wrote: > >>Hi all of you, >> >>I'm representing a 4x4 matrix as a 16-element list, e.g. >> >>m=range(16) >> >>first 4 elements first row, second four elements second row etc. >>I want to sum rows and columns like >> >>i-th row: >> >>sum(m[4*i:4*i+4]) >> >>and ith column: >> >>sum(m[i::4]) >> >>This seems to be slow because of the formation of the slices. >>I wonder if there is a way using generators or generator-expressions >>(which I didn't study yet) to compute these sums without copying >>parts of the matrix to a new list. (I'd guess that there should exist >>some canonical generator for sequences, which produces their elements >>..., maybe also for slices ?) >> >>All comments, hints, solutions are welcome. >> >>Regards, >>Gregor >> >>-- >>Gregor Lingl >>Reisnerstrasse 3/19 >>A-1030 Wien >> >>Telefon: +43 1 713 33 98 >>Mobil: +43 664 140 35 27 >> >>Autor von "Python f?r Kids" >>Website: python4kids.net >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From maxnoel_fr at yahoo.fr Wed Feb 2 12:31:09 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Feb 2 12:31:14 2005 Subject: [Tutor] how to separate hexadecimal In-Reply-To: <20050202111945.000025cf@sunray2.hartter.com> References: <2cad209005020123107fb43105@mail.gmail.com> <20050202111945.000025cf@sunray2.hartter.com> Message-ID: <2a4c96c64aaa6372bae40254aa02805a@yahoo.fr> On Feb 2, 2005, at 10:19, Ewald Ertl wrote: > Hi! > > Using binary operations: > >>>> a='0x87BE' >>>> str(hex(int(a,16) & 0xFF)) > '0xbe' >>>> str(hex((int(a,16) & 0xFF00) / 0xFF)) > '0x87' >>>> > > HTH Ewald Actually, the int conversions aren't even necessary. >>> hex(0x87BE & 0xFF) '0xbe' >>> hex((0x87BE & 0xFF00) / 0xFF) '0x87' -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Feb 2 13:54:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 13:54:57 2005 Subject: [Tutor] How to sum rows and columns of a matrix? In-Reply-To: <4200B403.4020606@tds.net> References: <41FE7477.4020403@aon.at> <4200B403.4020606@tds.net> Message-ID: <4200CD9D.5010000@tds.net> Kent Johnson wrote: > Liam Clarke wrote: > >> There's a specific package for arrays >> http://www.stsci.edu/resources/software_hardware/numarray >> >> that implements array mathematics. I use it for pixel map manipulation >> in pygame, so it's relatively fast. > > > Here is one way to do what you want using numarray: Here is another way, probably more idiomatic and faster. (I'm just doodling with numarray so there may still be a better way to do this...) >>> import numarray >>> m=numarray.array(range(16),shape=(4,4)) >>> numarray.add.reduce(m) array([24, 28, 32, 36]) >>> numarray.add.reduce(m, axis=1) array([ 6, 22, 38, 54]) Kent > > >>> import numarray > > Create a 4x4 array: > >>> m=numarray.array(range(16),shape=(4,4)) > >>> m > array([[ 0, 1, 2, 3], > [ 4, 5, 6, 7], > [ 8, 9, 10, 11], > [12, 13, 14, 15]]) > > Row access: > >>> m[1] > array([4, 5, 6, 7]) > > Column access: > >>> m[:,1] > array([ 1, 5, 9, 13]) > > Sum all the rows: > >>> [sum(m[i]) for i in range(4)] > [6, 22, 38, 54] > > Sum all the columns: > >>> [sum(m[:,i]) for i in range(4)] > [24, 28, 32, 36] > > Kent > >> >> >> On Mon, 31 Jan 2005 19:09:59 +0100, Gregor Lingl wrote: >> >>> Hi all of you, >>> >>> I'm representing a 4x4 matrix as a 16-element list, e.g. >>> >>> m=range(16) >>> >>> first 4 elements first row, second four elements second row etc. >>> I want to sum rows and columns like >>> >>> i-th row: >>> >>> sum(m[4*i:4*i+4]) >>> >>> and ith column: >>> >>> sum(m[i::4]) >>> >>> This seems to be slow because of the formation of the slices. >>> I wonder if there is a way using generators or generator-expressions >>> (which I didn't study yet) to compute these sums without copying >>> parts of the matrix to a new list. (I'd guess that there should exist >>> some canonical generator for sequences, which produces their elements >>> ..., maybe also for slices ?) >>> >>> All comments, hints, solutions are welcome. >>> >>> Regards, >>> Gregor >>> >>> -- >>> Gregor Lingl >>> Reisnerstrasse 3/19 >>> A-1030 Wien >>> >>> Telefon: +43 1 713 33 98 >>> Mobil: +43 664 140 35 27 >>> >>> Autor von "Python f?r Kids" >>> Website: python4kids.net >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pierre.barbier at cirad.fr Wed Feb 2 14:09:04 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed Feb 2 14:06:57 2005 Subject: [Tutor] How to sum rows and columns of a matrix? In-Reply-To: <4200CD9D.5010000@tds.net> References: <41FE7477.4020403@aon.at> <4200B403.4020606@tds.net> <4200CD9D.5010000@tds.net> Message-ID: <4200D0F0.4010703@cirad.fr> Even better : >>> import numarray >>> m = numarray.arange(16,shape=(4,4)) >>> numarray.sum(m) array([24, 28, 32, 36]) >>> numarray.sum(axis=1) array([ 6, 22, 38, 54]) Pierre Kent Johnson a ?crit : > Kent Johnson wrote: > >> Liam Clarke wrote: >> >>> There's a specific package for arrays >>> http://www.stsci.edu/resources/software_hardware/numarray >>> >>> that implements array mathematics. I use it for pixel map manipulation >>> in pygame, so it's relatively fast. >> >> >> >> Here is one way to do what you want using numarray: > > > Here is another way, probably more idiomatic and faster. (I'm just > doodling with numarray so there may still be a better way to do this...) > > >>> import numarray > >>> m=numarray.array(range(16),shape=(4,4)) > > >>> numarray.add.reduce(m) > array([24, 28, 32, 36]) > > >>> numarray.add.reduce(m, axis=1) > array([ 6, 22, 38, 54]) > > Kent > >> -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From klappnase at freenet.de Wed Feb 2 16:40:52 2005 From: klappnase at freenet.de (Michael Lange) Date: Wed Feb 2 16:38:33 2005 Subject: [Tutor] Tkinter questions In-Reply-To: References: Message-ID: <20050202164052.086a4441.klappnase@freenet.de> On Tue, 1 Feb 2005 19:08:41 +0200 Mark Kels wrote: Hi Mark, > Hello, > I got some Tkinter questions that I need the answer for to complete a > little project of mine: > 1. How can I make the program to open in a X*Y sized window ? from Tkinter import * root = Tk() root.geometry('600x400+0+0') This makes a window of 600x400 pixels placed in the upper left corner of the screen (+0+0 is the x- and y- offset; both of the window size and the offset may be omitted, so you can use '600x400' or '+0+0' as arguments for geometry() as well). > 2. How can I open another window from the first one (without closing it) ? Use instances of Toplevel() to create new windows as children of the root (Tk()) window. > 3. How can I add a file browser for my app (like the one you get when > you press "Save as..." in windows apps) ? import tkFileDialog filename = tkFileDialog.asksaveasfilename() if filename: # save the file...; if the user presses the 'Cancel' button, filename should be set to an empty string. > 4. How do I configure the font size on the Text widget (its realy > huge, and I would like to change it to somthing like 12). text = Text(parent, font=('helvetica', '-12', 'normal'))# "negative" size -> pixel size or: text.configure(font=('helvetica', '12', 'normal'))# "positive" size -> point size You can use any 3-tuple of the form (family, size, weight) as font descriptor; if the requested font is not found, the widget should fall back to some (probably ugly) default; tk guarantees that at least 'times', 'helvetica' and 'courier' font families are available, the availability of other fonts depends on your system. I hope this helps Michael From stygian at tesco.net Wed Feb 2 22:44:24 2005 From: stygian at tesco.net (Glen) Date: Wed Feb 2 22:44:06 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query Message-ID: <1107380664.2964.0.camel@localhost> My setup is Mandrake 10.0 which came with python 2.3 and a standard Python 2.4 build/install. I always start Idle from an icon on my taskbar, when I click the icon, Idle starts after a second but a small rotating timer appears over the taskbar for 30 seconds and then disappears. If I close Idle immediatly, the timer still remains for the 30 seconds. Idle/Python has always seemed to run perfectly so I have ignored the timer until I recently thought to run Idle from a console. Idle/Python still works great but this output appears in the console... [glen@localhost glen]$ idle set([34, 36, 38, 39]) Failed to load extension 'CodeContext' Traceback (most recent call last): File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 737, in load_standard_extensions self.load_extension(name) File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 747, in load_extension mod = __import__(name, globals(), locals(), []) File "/usr/local/lib/python2.4/idlelib/CodeContext.py", line 15, in ? from sets import Set ImportError: cannot import name Set [glen@localhost glen]$ I have only just discovered the set command in python, and it seems a bit of a coincedence that some of the console output lines... set([34, 36, 38, 39]) from sets import Set ImportError: cannot import name Set ...appear connected to code I was playing with a few days ago. I have looked at CodeContext.py, and line 15 is 'from sets import Set' which Python 2.4 doesn't like, as set is already built in. I have rebuilt/installed Python 2.4, but it made no difference. Can anyone give me a clue as to what may be going on? Glen From dyoo at hkn.eecs.berkeley.edu Wed Feb 2 23:02:55 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 2 23:03:01 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query In-Reply-To: <1107380664.2964.0.camel@localhost> Message-ID: On Wed, 2 Feb 2005, Glen wrote: > [glen@localhost glen]$ idle > set([34, 36, 38, 39]) > Failed to load extension 'CodeContext' > Traceback (most recent call last): > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 737, in > load_standard_extensions > self.load_extension(name) > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 747, in > load_extension > mod = __import__(name, globals(), locals(), []) > File "/usr/local/lib/python2.4/idlelib/CodeContext.py", line 15, in ? > from sets import Set > ImportError: cannot import name Set Hi Glen, Ah! Check to see if there's a "sets.py" program somewhere in your current working directory. It's very likely that Python is picking that up, instead of the 'sets' standard library module. This is one thing that does bite people every so often, because it's all too easy to accidently write a program uses the same name as a standard library module. I wrote a small module a while back as a proposed solution to the issue: http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ but I don't think it's really being used. Best of wishes to you! From kent37 at tds.net Wed Feb 2 23:07:22 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed Feb 2 23:07:27 2005 Subject: [Tutor] Better structure? In-Reply-To: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> References: <000301c507a3$f3828c90$7d5428cf@JSLAPTOP> Message-ID: <42014F1A.2010005@tds.net> I would at least introduce some functions. For example each case of your command handling loop could be broken out into a separate function. If there is a lot of shared state between the functions then make them all class methods and put the shared state in the class. Maybe all the drawing commands should be in a class with xaxis, yaxis, radiusaxis, radiusaxis2 at least as member fields. Kent Jacob S. wrote: > I think this thing is screaming for better structure, but previous > attempts at using oop for it have failed. > I think Derintegral is okay, I'm focusing on FunctionGrapher5.py--but > you can comment on both. > (To Johan Nilsson: I haven't had time to implement Simpson's rule > instead of Reimann's sum yet... but I have gotten it to work faster > anyway.) > I will probably expand the code yet... Add extra things like find area > between curve and x axis in interval [a,b]... > Any suggestions are greatly appreciated. If you want the code to work on > your machine, you'll need to have my Derintegral.py sys.path, obviously. > > #### Start of FunctionGrapher5.py ################### > from __future__ import division > from visual import * > import Derintegral > import os, random > from math import * > ja = 0 > > scenexdefault = 375 > > def start(): > for objects in scene.objects: > objects.visible = 0 > scene.title = "Function Grapher by Jacob, Inc." > scene.x = scenexdefault > scene.visible=1 > scene.exit=0 > scene.userspin = 0 > scene.range=(10,10,1) > scene.background=(1,1,1) > global xaxis > global yaxis > xaxis = curve(pos=[(100,0,0),(-100,0,0)],color=color.black) > yaxis = curve(pos=[(0,100,0),(0,-100,0)],color=color.black) > global radiusaxis > global radiusaxis2 > radiusaxis = curve(pos=[(-100,-100),(100,100)],color=color.black) > radiusaxis2 = curve(pos=[(-100,100),(100,-100)],color=color.black) > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > > start() > d = 1 > print """\ > List of Commands: > clear > quit > remove lines > return lines > gotl # (Graph One Tangent Line) w/optional x coordinate > gatl # (Graph All Tangent Lines) w/optional step > gonl # (Graph One Normal Line) w/optional x coordinate > ganl # (Graph All Normal Lines) w/optional step > > Function Syntax: > [y,x,or r] = function [range] ["s" followed by float for step] > Brackets mean that it's not required. > So, in effect, you don't have to type a function > """ > > def graphit(type,f,range2,step): > li = curve(color=color.blue) > if type in ['y','x']: > x = -15 > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > while -15 <= x <= 15: > if eval(range2): > try: > a = f(x) > if -15 <= a <= 15: > if type == 'y': > li.append(pos=(x,a,0)) > elif type == 'x': > li.append(pos=(a,x,0)) > else: > li = curve(color=color.blue) > except: > pass > else: > li = curve(color=color.blue) > x = x+step > elif type == 'r': > exec "def m(t): return f(t)*cos(t)" > exec "def n(t): return f(t)*sin(t)" > t = 0 > while 0 <= t <= 10*pi: > if eval(range2): > try: > li.append(pos=(m(t),n(t),0)) > except: > li = curve(color=color.blue) > t = t+step > > > print 'Please type in functions in below. ' > while 1: > lists=[] > y = raw_input(">") > if y == 'clear': > scene.visible=0 > start() > print "-"*36 > continue > elif y == 'quit': > scene.visible = 0 > del scene > break > elif y == 'remove lines': > a = [radiusaxis,radiusaxis2,xaxis,yaxis] > for x in a: > x.visible = 0 > d = 0 > continue > elif y == 'return lines': > a = [radiusaxis,radiusaxis2,xaxis,yaxis] > for x in a: > x.visible = 1 > d = 1 > continue > elif y.startswith('gatl'): > try: > step2 = float(y.lstrip("gatl ")) > except: > step2 = 0.5 > x = -20 > while -20 <=x<= 20: > try: > der = Derintegral.diffatpt(f,x) > if abs(der)<=25: > if type == 'y': > > curve(pos=[(-15,eval("der*(-15-x)+f(x)")),(15,eval("der*(15-x)+f(x)"))],color=color.red) > > else: > > curve(pos=[(eval("der*(-15-x)+f(x)"),-15),(eval("der*(15-x)+f(x)"),15)],color=color.red) > > except: > pass > x = x + step2 > continue > elif y.startswith('ganl'): > try: > step2 = float(y.lstrip("ganl ")) > except: > step2 = 0.5 > x = -20 > while -20 <=x<= 20: > try: > der = Derintegral.diffatpt(f,x) > if abs(der)<=25: > if type == 'y': > > curve(pos=[(-15,eval("(-1/der)*(-15-x)+f(x)")),(15,eval("(-1/der)*(15-x)+f(x)"))],color > = color.red) > else: > > curve(pos=[(eval("(-1/der)*(-15-x)+f(x)"),-15),(eval("(-1/der)*(15-x)+f(x)"),15)],color > = color.red) > except: > pass > x = x + step2 > continue > elif y.startswith('gotl'): > try: > x = float(y.lstrip('gotl ')) > except: > x = float(raw_input('What x coordinate do you want the > tangent line at? ')) > der = Derintegral.diffatpt(f,x) > try: > if abs(der)<= 25: > if type == 'y': > > curve(pos=[(-15,eval("der*(-15-x)+f(x)")),(15,eval("der*(15-x)+f(x)"))],color=color.red) > > else: > > curve(pos=[(eval("der*(-15-x)+f(x)"),-15),(eval("der*(15-x)+f(x)"),15)],color=color.red) > > except: > pass > continue > elif y.startswith('gonl'): > try: > x = float(y.lstrip('gonl ')) > except: > x = float(raw_input('What x coordinate do you want the > tangent line at? ')) > der = Derintegral.diffatpt(f,x) > try: > if abs(der)<= 25: > if type == 'y': > > curve(pos=[(-15,eval("(-1/der)*(-15-x)+f(x)")),(15,eval("(-1/der)*(15-x)+f(x)"))],color=color.red) > > else: > > curve(pos=[(eval("(-1/der)*(-15-x)+f(x)"),-15),(eval("(-1/der)*(15-x)+f(x)"),15)],color=color.red) > > except: > pass > continue > elif y.startswith('getpt'): > y = y.lstrip("getpt ") > if y: > m = float(eval(y)) > else: > m = float(eval(raw_input("f(?) "))) > try: > print f(m) > except ValueError: > print "Math Domain Error" > continue > elif y == 'regraph': > graphit(type,f,range2,step) > continue > if y.count(" = ") == 1: > y = y.split(" = ") > type = y[0].lower() > y = y[1] > y = y.replace("y","x") > if type == 'r': > defaultrange = '0<=t<=5*pi' > y = y.replace('x','t') > if d == 1: > radiusaxis.visible = 1 > radiusaxis2.visible = 1 > else: > defaultrange = '-15<=x<=15' > else: > type = 'y' > defaultrange = '-15<=x<=15' > y = y.split(" ",1) > tempfunct = y.pop(0) > if y: > y = y[0] > if y.count('st'): > if y.startswith('st'): > y = y.lstrip('st') > step = float(y) > else: > y = y.split(" ") > step = float(y.pop().lstrip('st')) > y = " ".join(y) > range2 = defaultrange > else: > range2 = y > step = 0.005 > else: > range2 = defaultrange > step = 0.005 > y = tempfunct > range2 = range2.replace('and','or') > range2 = range2.replace(',','<=x<=') > try: > exec "def f(x): return %s" % y > except: > continue > graphit(type,f,range2,step) > ###### End of FunctionGrapher5.py ########### > > #### Start of Derintegral.py ########## > from __future__ import division > import psyco > psyco.full() > from math import * > > > def diffatpt(funct,pt): > """Return the derivative of a function at a specific point. """ > sminc = 1e-10 > x = pt+sminc > y2 = funct(x) > x2 = x > x = pt-sminc > y1 = funct(x) > x1 = x > slope = (y2-y1)/(x2-x1) > return slope > > def defintegral(fofx,x,max1): > total = 0 > step = 1e-5 > exec "def f(x): return %s" % fofx > while x <= max1: > try: > total = total+f(x) > except: > pass > x = x+step > return abs(total*step) > ######End of Derintegral.py ########## > > > Like I said, any comments appreciated. > Jacob Schmidt > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Thu Feb 3 00:18:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Feb 3 00:18:42 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Hi, Had the *ahem* joy of learning Perl last night. Egad. Wrote the script in Python to get it right, and then 'translated' it to Perl. Does the style of coding Python engenders suit the Perl environment in anyone's experienc? AFAI can see there is no real 'style' to Perl, apart from white noise of non alphanumeric characters. Just wondering if I should bite the bullet and code from scratch in Perl, or if my Python - Perl is Ok. Two codes are here - Python http://www.rafb.net/paste/results/BVaym940.html Perl http://www.rafb.net/paste/results/LromA876.html [OT begins] By the way, I'm only learning Perl because I need to script some routine HTML maintenance, and I can't be bothered applying to head office IT for an install of Python, as the justification involved is ludicrous, especially considering that my role as defined does not include scripting. First impressions of Perl - 1) I'll use Perl for the regex stuff from now on, Perl is obviously built for this. 2 ) There's More Than One Way To Do It makes debugging hard - i.e. close INFILE; & close (INFILE); are both valid. I like one syntax, cos it's easier to remember. 3) Some stuff is counter-intuitive - $lenOfModList = @moddirList is the Perl equivalent of lenofModList = len(moddirList) @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) I couldn't figure this one out until I read that Perl automatically flattens lists. Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to true for $d = "b" when if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals true also? What's with that? 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! I'm not referring to the $ & @, I can see how they could be useful, although with a list - @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], not $d = $dude[1], that's counterintuitive also. Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile = to read a whole file, and this - I hate Perl for this - open OUTFILE, ">c:/python23/j/index.htm" What's the difference between open OUTFILE, "c:/python23/j/index.htm" and open OUTFILE, ">c:/python23/j/index.htm" ? The first will open index.htm with the handle OUTFILE, to read... The second will open index.htm with the handle OUTFILE to write!. Of course, the documentation I had didn't mention that. It just said to open it and use print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl tutorial, which mentioned using &lst; to open and &gst; to write (or something), which I guessed as lesser/greater than. Why is the read/write modifier part of the filename??? Why is it a > ? In my opinion, there's only one place a > sign should be, in an inequality test. So, Perl in my opinion - great for regexes obviously based around *nix conventions. Big hodge-podge, oozing with inconsistency. I'd hate to work collaboratively on a Perl project. Two steps up from Brainf**k in parts. Obviously in need of a benevolent dictator a la Guido. But then, I've been spoilt by clean, smooth (usually) Python. Lovely, usually consistent Python. Aah, Pythonnnn.... *dreamy look* [end OT rant] -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From johnp at milwaukielumber.com Thu Feb 3 00:24:32 2005 From: johnp at milwaukielumber.com (John Purser) Date: Thu Feb 3 00:24:38 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: Message-ID: <200502022324.j12NOWjV027813@mail.morseintranet.com> Glad someone else thinks so. I tried getting into Perl. The rational made perfect sense and I had picked up several languages by then. Tried. Hated it. Bounced off it. It's like reading alphabet soup. IMHO they took what was wrong with Shell scripting, AWK, Sed and a few other languages and rolled them into one. That's when I came across Python. Never looked back. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Liam Clarke Sent: Wednesday, February 02, 2005 15:18 To: Tutor Tutor Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Hi, Had the *ahem* joy of learning Perl last night. Egad. Wrote the script in Python to get it right, and then 'translated' it to Perl. Does the style of coding Python engenders suit the Perl environment in anyone's experienc? AFAI can see there is no real 'style' to Perl, apart from white noise of non alphanumeric characters. Just wondering if I should bite the bullet and code from scratch in Perl, or if my Python - Perl is Ok. Two codes are here - Python http://www.rafb.net/paste/results/BVaym940.html Perl http://www.rafb.net/paste/results/LromA876.html [OT begins] By the way, I'm only learning Perl because I need to script some routine HTML maintenance, and I can't be bothered applying to head office IT for an install of Python, as the justification involved is ludicrous, especially considering that my role as defined does not include scripting. First impressions of Perl - 1) I'll use Perl for the regex stuff from now on, Perl is obviously built for this. 2 ) There's More Than One Way To Do It makes debugging hard - i.e. close INFILE; & close (INFILE); are both valid. I like one syntax, cos it's easier to remember. 3) Some stuff is counter-intuitive - $lenOfModList = @moddirList is the Perl equivalent of lenofModList = len(moddirList) @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) I couldn't figure this one out until I read that Perl automatically flattens lists. Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to true for $d = "b" when if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals true also? What's with that? 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! I'm not referring to the $ & @, I can see how they could be useful, although with a list - @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], not $d = $dude[1], that's counterintuitive also. Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile = to read a whole file, and this - I hate Perl for this - open OUTFILE, ">c:/python23/j/index.htm" What's the difference between open OUTFILE, "c:/python23/j/index.htm" and open OUTFILE, ">c:/python23/j/index.htm" ? The first will open index.htm with the handle OUTFILE, to read... The second will open index.htm with the handle OUTFILE to write!. Of course, the documentation I had didn't mention that. It just said to open it and use print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl tutorial, which mentioned using &lst; to open and &gst; to write (or something), which I guessed as lesser/greater than. Why is the read/write modifier part of the filename??? Why is it a > ? In my opinion, there's only one place a > sign should be, in an inequality test. So, Perl in my opinion - great for regexes obviously based around *nix conventions. Big hodge-podge, oozing with inconsistency. I'd hate to work collaboratively on a Perl project. Two steps up from Brainf**k in parts. Obviously in need of a benevolent dictator a la Guido. But then, I've been spoilt by clean, smooth (usually) Python. Lovely, usually consistent Python. Aah, Pythonnnn.... *dreamy look* [end OT rant] -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Thu Feb 3 00:25:10 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu Feb 3 00:25:18 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: Message-ID: I got nothing on your Perl rant, but in response to the subject line... http://www.snopes.com/legal/arizona.htm From maxnoel_fr at yahoo.fr Thu Feb 3 00:33:44 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 00:33:48 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <86626245450c1bfcf3190400baffe178@yahoo.fr> On Feb 2, 2005, at 23:18, Liam Clarke wrote: > 1) I'll use Perl for the regex stuff from now on, Perl is obviously > built for this. Actually IIRC Perl *invented* regexes as we know them. The "standard" regex syntax is known as "Perl regex syntax". > 2 ) There's More Than One Way To Do It makes debugging hard - i.e. > close INFILE; & close (INFILE); are both valid. I like one syntax, cos > it's easier to remember. I don't find it that bad. Ruby does it as well, and it's perfectly readable. It's more or less equivalent as if condition: and if(condition): both being valid in Python. > 3) Some stuff is counter-intuitive - > $lenOfModList = @moddirList is the Perl equivalent of lenofModList = > len(moddirList) You sure of that? I was under the impression that len(moddirList) in Perl was $moddirList (@moddirList is the list itself). > Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to > true for $d = "b" when > if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals > true also? What's with that? This probably has to do with operator precedence. It's been lifted from C, so chances are that && has a higher precedence than eq. Use parentheses. > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! > > I'm not referring to the $ & @, I can see how they could be useful, > although with a list - > > @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = > @dude[1], > not $d = $dude[1], that's counterintuitive also. This will be fixed in Perl 6. Then again, Perl 6 is supposed to be pure heaven, as the Parrot virtual machine can theoretically be used with any language and is heavily optimized. Python and Ruby with the speed of Perl, and the possibility to interface your code with CPAN modules. That's really cool. Once Perl 6 is released, of course. > Why is the read/write modifier part of the filename??? Why is it a > ? > In my opinion, there's only one place a > sign should be, in an > inequality test. This is consistent with UNIX redirection. ./foo > bar.txt executes the command foo, and redirects its STDOUT to the file bar.txt. ./foo >> bar.txt does the same, but appends to bar.txt instead f overwriting it. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Thu Feb 3 00:39:32 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 00:39:40 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <86626245450c1bfcf3190400baffe178@yahoo.fr> References: <86626245450c1bfcf3190400baffe178@yahoo.fr> Message-ID: <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> (damn, forgot to add the main part of my argumentation) I learnt Perl as well, a few years ago. It was the first scripting language I came across (all I knew before that were C, Turbo Pascal, and a few calculator programming languages), so I immediately fell in love with its string manipulation capabilities. I came across PHP a little while after, and while it had some things which I liked (PHP.net being the main one), I preferred Perl. However, I never got the opportunity to really use it, and after a while the inconsistency of the syntax grew on me, and the language itself kept eluding me. I was never able to grok it, and thus systematically reverted to C every time I had to code something. Fast forward to last summer. In the span of 1 week, I discovered both Python and Ruby. Fell in love with both and immediately ditched Perl. I never looked back, even though I know Perl is still the fastest scripting language around. I value debugging time more than CPU time these days. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From stygian at tesco.net Thu Feb 3 00:53:29 2005 From: stygian at tesco.net (Glen) Date: Thu Feb 3 00:53:13 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query In-Reply-To: References: Message-ID: <1107388409.3726.6.camel@localhost> On Wed, 2005-02-02 at 22:02, Danny Yoo wrote: > On Wed, 2 Feb 2005, Glen wrote: > > > [glen@localhost glen]$ idle > > set([34, 36, 38, 39]) > > Failed to load extension 'CodeContext' > > Traceback (most recent call last): > > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 737, in > > load_standard_extensions > > self.load_extension(name) > > File "/usr/local/lib/python2.4/idlelib/EditorWindow.py", line 747, in > > load_extension > > mod = __import__(name, globals(), locals(), []) > > File "/usr/local/lib/python2.4/idlelib/CodeContext.py", line 15, in ? > > from sets import Set > > ImportError: cannot import name Set > > Hi Glen, > > > Ah! Check to see if there's a "sets.py" program somewhere in your current > working directory. It's very likely that Python is picking that up, > instead of the 'sets' standard library module. > > This is one thing that does bite people every so often, because it's all > too easy to accidently write a program uses the same name as a standard > library module. > > I wrote a small module a while back as a proposed solution to the issue: > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > but I don't think it's really being used. > > Best of wishes to you! > You're a genius! That's exactly what I'd done. It also explains the odd results I was getting when I did import the sets module. Thanks, I'll have a look at your module. Glen From cyresse at gmail.com Thu Feb 3 01:42:10 2005 From: cyresse at gmail.com (Liam Clarke) Date: Thu Feb 3 01:42:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> References: <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> Message-ID: > I don't find it that bad. Ruby does it as well, and it's perfectly readable. It's more or less equivalent as if condition: and if(condition): both being valid in Python. Yeah, but you'd never call a function foo like this- x = foo in Python. It's just good to be able to say that a function always has . That improves readability (imao). >You sure of that? I was under the impression that len(moddirList) in Perl was $moddirList (@moddirList is the list itself). Well, my one's correct, but I think yours is also. And this is what gets me. @mod = (1,2,3) $mod = 3 $mod[0] = 1 Is inconsistent. Or at least, the logic behind this is not immediately apparent to me. I'm always open to illumination on these things however. >> if ( not $d eq "a" && not $d eq "c") = False for $d = "b" >> if ($d ne "a" && $d ne "c") = True >This probably has to do with operator precedence. It's been lifted from C, so chances are that && has a higher precedence than eq. Use parentheses. Ah... Ironic, I got misled by TMTOWTDI. I figured that if not x=="a" and not x == "c" evaled as True in Python, and "if (not $d eq "a")" evaled as True in Perl, that if ( not $d eq "a" && not $d eq "c") would also eval as true. Of course, what's even weirder to me is that if ($d ne "a" && $d ne "c") does eval as True, as far as I can see, '$d ne "a"' is the same as d != "a" in Python, which is the same as 'if not d == "a"', which, logically, would mean that $d ne "a" is the same as 'if(not $d eq "a") in which case both tests should handle the addition of an AND the same. Once again, illumination is welcomed, as I have a finally that some subtlety of Boolean logic is eluding me, and a 'x != a' test is different to 'if not x == a' in a small but significant way. Max - the foo > std.txt thing explains it, but what about @dude = , where do the brackets originate from? This is another issue I'm having with Perl as opposed to Python - Perl is very much written by *nix users for *nix users, it's implementation of *nix conventions shows, including the `` things. Whereas (correct me if I'm wrong), but Python was written by *nix users for everyone. Python seems very non-OS-denominational in it's current incarnation, it may have been very *nix orientated prior. So here comes me, the guy who installed Linux once, failed to see the big deal and uninstalled it. Up until 3 months ago, my comp was used for gaming, pure and simple, me being a certified Day of Defeat freak, and so Windows has always best served my purpose. Now, I want to programme, so I have to learn Unix conventions to use a crossplatform language! It's like asking *nix users to sign a Microsoft EULA!! (Well, not as bad, but still as anathemic.) >Fast forward to last summer. In the span of 1 week, I discovered both Python and Ruby. Fell in love with both and immediately ditched Perl. How's Ruby? I bookmarked the homepage, but never got around to looking at it. Oh, and I will say this - Perl > Java (and that's an inequality test, not a redirection of output) Cheers, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From lumbricus at gmx.net Thu Feb 3 01:52:50 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Thu Feb 3 01:52:54 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr> Message-ID: <32746.1107391970@www54.gmx.net> Hello! > Actually IIRC Perl *invented* regexes as we know them. The "standard" > regex syntax is known as "Perl regex syntax". Regex are way older than Perl. The roots are in the Fourties(!). They were first used in the editor qed, then ed, then sed and eventually grep. Then awk, emacs, vi lex and finally Perl. "http://en.wikipedia.org/wiki/Regular_expressions#History" > -- Max HTH and Greetings, J"o! -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realit?t. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realit?t zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) Sparen beginnt mit GMX DSL: http://www.gmx.net/de/go/dsl From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 02:46:28 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 02:46:34 2005 Subject: [Tutor] Python 2.4 with Mandrake 10.0 query In-Reply-To: <1107388409.3726.6.camel@localhost> Message-ID: > > Ah! Check to see if there's a "sets.py" program somewhere in your > > current working directory. It's very likely that Python is picking > > that up, instead of the 'sets' standard library module. > > You're a genius! That's exactly what I'd done. Hi Glen, I'd attribute it not to genius, but more to pattern matching: I've seen that particular problem a lot. *sigh* But I'm very glad that the problem's identified and fixed. > > I wrote a small module a while back as a proposed solution to the issue: > > > > http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ > > > > but I don't think it's really being used. > > > It also explains the odd results I was getting when I did import the > sets module. Thanks, I'll have a look at your module. You probably won't need it; PEP 328 is supposed to handle this issue properly: http://www.python.org/peps/pep-0328.html My __std__ package is a kludge, and I know it's a kludge. *grin* I noticed that someone else had run into limitations using it: http://www.gossamer-threads.com/lists/python/python/348985 so it's not as useful as I had first thought. Best of wishes to you! From maxnoel_fr at yahoo.fr Thu Feb 3 02:49:22 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 02:49:27 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> Message-ID: <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> On Feb 3, 2005, at 00:42, Liam Clarke wrote: >> I don't find it that bad. Ruby does it as well, and it's perfectly > readable. It's more or less equivalent as if condition: and > if(condition): both being valid in Python. > > Yeah, but you'd never call a function foo like this- > > x = foo > > in Python. It's just good to be able to say that a function always has > . > That improves readability (imao). Yes. That, and the fact that you can use function pointers very easily that way. For example, x = foo x() will call foo. Which is cool. I do prefer the Python style as well. Just like variable naming conventions should tell you something about their nature, function calls should have something that explicitly gives them away as such. MyClass MY_CONSTANT myVariable myFunctionCall() > @mod = (1,2,3) > $mod = 3 > $mod[0] = 1 > > Is inconsistent. Or at least, the logic behind this is not immediately > apparent to me. I'm always open to illumination on these things > however. Yeah. As with most things in Perl, there is no way to guess it. This is actually what I hate the most about that language, and what makes it write-only. >>> if ( not $d eq "a" && not $d eq "c") = False for $d = "b" >>> if ($d ne "a" && $d ne "c") = True > >> This probably has to do with operator precedence. It's been lifted > from C, so chances are that && has a higher precedence than eq. Use > parentheses. > > Ah... Ironic, I got misled by TMTOWTDI. I figured that if not x=="a" > and not x == "c" evaled as True in Python, and "if (not $d eq "a")" > evaled as True in Perl, that > if ( not $d eq "a" && not $d eq "c") would also eval as true. > Of course, what's even weirder to me is that > if ($d ne "a" && $d ne "c") does eval as True, as far as I can see, > > '$d ne "a"' is the same as d != "a" in Python, which is the same as > 'if not d == "a"', which, logically, would mean that $d ne "a" is the > same as 'if(not $d eq "a") in which case both tests should handle the > addition of an AND the same. Again, no, because IIRC (it's been a while since I last used Perl) eq and ne are the Perl operators with the lowest precedence. In effect, your last statement is evaluated as if((not $d) eq "a"). Use == and !=, they work on strings as well. Or (and?) use parens. Also, don't forget that Perl, like Python, uses lazy evaluation. > Once again, illumination is welcomed, as I have a finally that some > subtlety of Boolean logic is eluding me, and a 'x != a' test is > different to 'if not x == a' in a small but significant way. > > Max - the foo > std.txt thing explains it, but what about @dude = > , where do the brackets originate from? I have no idea. Somehow I think it makes sense. It's one of the few things that I think make sense in Perl. Couldn't tell you why I think so, though :p > This is another issue I'm having with Perl as opposed to Python - Perl > is very much written by *nix users for *nix users, it's implementation > of *nix conventions shows, including the > `` things. Whereas (correct me if I'm wrong), but Python was written > by *nix users for everyone. Python seems very non-OS-denominational in > it's current incarnation, it may have been very *nix orientated prior. Not really. The thing is, Python in itself does very little. You have to import modules whenever you want to do something that involves the system (aside from file operations). That's an advantage IMO, since the default modules are quite good and allow for some nice cross-platform capabilities. However, if the redirection operators and pipes are what make you think that way, you should know that MS-DOS (and WinNT's DOS shell) does handle pipes and redirection. Perhaps not as powerfully as *NIX, but it does. (however, I would appreciate it if the Python standard distribution came with a "real" XML parser, 'cause DOM and SAX just plain suck -- by the way, thanks guys, I tried dom4j on my Java project and it changed my life) > So here comes me, the guy who installed Linux once, failed to see the > big deal and uninstalled it. Up until 3 months ago, my comp was used > for gaming, pure and simple, me being a certified Day of Defeat freak, > and so Windows has always best served my purpose. > > Now, I want to programme, so I have to learn Unix conventions to use a > crossplatform language! It's like asking *nix users to sign a > Microsoft EULA!! (Well, not as bad, but still as anathemic.) Well, in Perl's defense, Windows does implement a fairly large part of the POSIX standard. And believe me. I'm a UNIX user (Mac OS X is my primary OS, but I also use Windows and Linux on a fairly regular basis). Perl doesn't make any more sense to me than when I was still a Windows-only guy. > How's Ruby? I bookmarked the homepage, but never got around to looking > at it. Very, very nice. Cleanest object-orientedness I ever saw in a language (not that I have that much experience -- people like Alan would probably be better judges than me on this). I find it more elegant than Python, however I end up using Python anyway because Ruby has a huge flaw: it's Japanese (AFAIK it's also the only "Made in Japan" programming language, apart from stuff like ASM 68K), and so is a large part of its community. As such, English language documentation is flaky at best. And as far as I know there is no tutor@ruby-lang.org. Which, as you will probably agree, sucks. > Oh, and I will say this - Perl > Java (and that's an inequality test, > not a redirection of output) I'll have to disagree with you there, unless vi/emacs is the only IDE you have access to (did I ever tell you about Eclipse?), and perhaps even then. From what I remember, if you're programming in an object-oriented style (which I now tend do by default unless there is a painfully obvious and optimal solution in procedural style), Perl is the ugliest thing ever created since Visual Basic. Last time I checked, its OOness was frighteningly ugly. Java was built as an OO language from the ground up, if you except the presence of the basic C types. As such, it is very clean, although it clearly lacks the elegance of Python (then again, what to say of Perl?). Java code always makes sense when you read it (and in the worst-case, when you have access to the API documentation, which is available as long as you have Internet access). Sure, it requires a lot of typing (in both meanings of the word), but it's rarely -- if ever -- ambiguous. Also, Java has the added advantage of being very easy to learn: I learned it in 1 week 4 months ago (doesn't beat Python's record, though: I was doing useful stuff with it within 24 hours of learning about its existence), and now feel confident enough with it to do just about anything. Of course, my C/C++ programming experience probably helped me a lot with this. In my opinion, Java has only 2 big flaws: 1) The Java Virtual Machine is a horrible resource hog. Sure, your program runs quite fast, but unless you've got multiple CPUs the responsiveness of your machine goes *down* (especially noticeable on machines with slow CPUs such as the G4 867 with which I'm typing this right now). 2) Sun didn't ever encourage anyone to write [insert language here]?compilers that compiled to JVM bytecode. The JVM was supposed to run Java code and nothing else. That's stupid. Microsoft got it right with .NET; Sun should have thought of it at least 5 years ago. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 03:19:26 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 03:19:29 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: Message-ID: On Thu, 3 Feb 2005, Liam Clarke wrote: > Had the *ahem* joy of learning Perl last night. Egad. Wrote the script > in Python to get it right, and then 'translated' it to Perl. Hi Liam, I strongly recommend sending the Perl code to that Perl-beginners mailing list referenced earlier. I'm sure that there are some Perl idioms that can simplify the code there. For example: ### Perl ### $wrkDir = "c:/python23/j/j2"; opendir( TGTDIR, $wrkDir); @dirList = readdir(TGTDIR); @moddirList=(); foreach $fileName (@dirList) { if ($fileName ne ".." && $fileName ne ".") { @moddirList = (@moddirList, $fileName); } } ###### can be greatly improved by Perl's globbing operator instead of readdir(): ###### $wrkDir = "c:/python23/j/j2"; @dirList = <$wrkDir/*>; ###### This has a fairly close Python equivalent in the glob.glob() function: ### wrkDir = "s:/toolkit/retain/sustainableEmployment" dirList = glob.glob(wrkDir + "/*") ### > @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) This is actually doing much more work than a list append. The list-adding code that you had earlier is equivalent to: ### Python ### someList = someList + [newValue] ###### which is just bad. *grin* More idiomatic Perl is: ### Perl ### push @someArray, $newValue; ###### which should have the same performance as a list append(). > Of course, the documentation I had didn't mention that. It just said to > open it and use print FILEHANDLE $value; to write. Perl's documentation system 'perldoc' command is one of the really nice things about Perl. In some cases, I think it might be even more comprehensive than 'pydoc', since perldoc also directly links to tutorial material. Try: ### $ perldoc perl ### I guess I'm trying to say: language idioms take time to learn, and unlike syntax errors, weird idioms aren't really detectable by the runtime system. *grin* If you continue to learn Perl, talk with the beginners's group there, so that the community there can help. And if the Perl programs that you're writing seem suboptimal, get it vetted by someone who knows Perl well; you may be pleasantly surprised. Best of wishes to you! From keridee at jayco.net Thu Feb 3 03:47:55 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 03:48:23 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> Message-ID: <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> Interesting topic. > Jacob, > > Writing library code is a difficult and unrewarding task > - I've been there so I sympathise, however... I wouldn't say that... >> So, how would one go about this in a non broken code way? Don't they > have >> something like what I'm requesting. > > Its not broken, its just different to what you want. > What you want is much simpler than what lstrip does > so you can easily code your requirements. > Try writing the code to do what lstrip actually does > - its much harder. So the library includes the more > difficult function and lets you code the easy ones. def lstrip(string,chars=' ') string = list(string) t = 0 for x in string: if x in chars: string.remove(t) else: break t = t+1 Okay, so it's not that difficult, but I get your point. Since all of these are not too hard to write, my library structure is probably what's flawed. I have so many miscellaneous functions that I am copying and pasting (oh no!) that I finally decided to move them to a different module. Unfortunately, they are quite random and I will have to find someway of seperating them. >> It seems to me that a few things are flawed in the standard > distribution. > > No library is perfect - you should try using C! > > But the Python library isually has good reasons for its > apparent limitations. > >> Little things like the overlooking of adding a method or function to > decimal >> for returning an instance with x places right of the decimal. > > But there is very little need to do that. Usually you only want > to do that in presentation - ie printing. Thus the mechanism > for doing that is in the string formatting code - where it > makes sense. Uck. True usually in printing. String formatting doesn't cut it for a type that's not a string. Especially something not builtin. >Why would limiting the precision of the internal > number representation be something you'd want to do? Very > occassionally maybe, but in those cases its easy to fake > (and it is a fake because the number is in binary and not > true decimal so its always an approximation - in any language!) > >> quantize, but that's junk and not simple. > > You mean it does a complex job and not the one youd like it to do? :-) It does precisely what I would like it to do. I guess I just looked at it and said, they are making it too difficult. quantize -- a method of class Decimal in module decimal arguments -- exp - a Decimal instance that has the required amount of places to the right of the decimal pt. So, it seems to me that one could possibly add to the decimal module. userprec = 10 ## A default def q(decinst): ## simple name -- unfortunately might conflict -- decinst stands for decimal instance return decinst.quantize(Decimal("0.%s" % ('0'*userprec))) ## Creates a Decimal instance w/userprec places right of #### decimal pt. then uses the given argument decinst method quantize to return decinst w/ userprec places right of the decimal. Which, of course, I did. >You can even subclass string and make it a method if you like. Ooooh! How do I do that? > I suspect your function should probably be: > > def mylstrip(str,stripstring): > if str.startswith(stripstring) and > len(stripstring) < len(str): > return str[len(stripstring):] > > But thats just my guess at what *you* really want... Well yeah. I didn't think it through that far. But that also contributes to my probably poor library structure. Where would I put such a function? > And finally remember that Python is built by volunteers mostly. > You should be pleased the *bothered* to write any of it! Excuse me... I didn't mean to offend those volunteers in any way. I'm beautifully happy with python! Just little quirks here and there... Maybe someday I'll become one of those volunteers. Jacob Schmidt From kent37 at tds.net Thu Feb 3 05:11:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 3 05:11:10 2005 Subject: [Tutor] Better structure? In-Reply-To: <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> Message-ID: <4201A45A.2060205@tds.net> Jacob S. wrote: >> Try writing the code to do what lstrip actually does >> - its much harder. So the library includes the more >> difficult function and lets you code the easy ones. > > > def lstrip(string,chars=' ') > string = list(string) > t = 0 > for x in string: > if x in chars: > string.remove(t) > else: > break > t = t+1 > > > Okay, so it's not that difficult, Well, after fixing the obvious syntax error I tried print lstrip('abcd', 'abcd') and got Traceback (most recent call last): File "D:\Personal\Tutor\LStrip.py", line 11, in ? print lstrip('abcd', 'abcd') File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip string.remove(t) ValueError: list.remove(x): x not in list so maybe it's not that easy either. Don't forget the unit tests! :-) Kent From singingxduck at gmail.com Thu Feb 3 05:23:03 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Feb 3 05:23:20 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201A45A.2060205@tds.net> References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> Message-ID: <4201A727.1040206@gmail.com> Kent Johnson wrote: > Jacob S. wrote: > >>> Try writing the code to do what lstrip actually does >>> - its much harder. So the library includes the more >>> difficult function and lets you code the easy ones. >> >> >> >> def lstrip(string,chars=' ') >> string = list(string) >> t = 0 >> for x in string: >> if x in chars: >> string.remove(t) >> else: >> break >> t = t+1 >> >> >> Okay, so it's not that difficult, > > > Well, after fixing the obvious syntax error I tried > print lstrip('abcd', 'abcd') > > and got > Traceback (most recent call last): > File "D:\Personal\Tutor\LStrip.py", line 11, in ? > print lstrip('abcd', 'abcd') > File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip > string.remove(t) > ValueError: list.remove(x): x not in list > > so maybe it's not that easy either. Don't forget the unit tests! :-) > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Actually, its not all that difficult. Instead of removing characters from the list, just replace them with an empty string and return ''.join(string): >>> def lstrip(string,chars=' '): string = list(string) i = 0 for x in string: if x in chars: string[i] = '' else: break i+=1 return ''.join(string) >>> lstrip('abcd','abcd') '' >>> 'abcd'.lstrip('abcd') '' >>> 'go on long log buddy'.lstrip('gonl ') 'buddy' >>> lstrip('go on long log buddy', 'gonl ') 'buddy' >>> 'go on long log buddy'.lstrip('gonl') ' on long log buddy' >>> lstrip('go on long log buddy', 'gonl') ' on long log buddy' So its not a brute force thing so much as a change in how you look at it that makes it difficult. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Thu Feb 3 05:28:04 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Feb 3 05:28:18 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201A727.1040206@gmail.com> References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> Message-ID: <4201A854.8000103@gmail.com> Orri Ganel wrote: > Kent Johnson wrote: > >> Jacob S. wrote: >> >>>> Try writing the code to do what lstrip actually does >>>> - its much harder. So the library includes the more >>>> difficult function and lets you code the easy ones. >>> >>> >>> >>> >>> def lstrip(string,chars=' ') >>> string = list(string) >>> t = 0 >>> for x in string: >>> if x in chars: >>> string.remove(t) >>> else: >>> break >>> t = t+1 >>> >>> >>> Okay, so it's not that difficult, >> >> >> >> Well, after fixing the obvious syntax error I tried >> print lstrip('abcd', 'abcd') >> >> and got >> Traceback (most recent call last): >> File "D:\Personal\Tutor\LStrip.py", line 11, in ? >> print lstrip('abcd', 'abcd') >> File "D:\Personal\Tutor\LStrip.py", line 6, in lstrip >> string.remove(t) >> ValueError: list.remove(x): x not in list >> >> so maybe it's not that easy either. Don't forget the unit tests! :-) >> >> Kent >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Actually, its not all that difficult. Instead of removing characters > from the list, just replace them with an empty string and return > ''.join(string): > > >>> def lstrip(string,chars=' '): > string = list(string) > i = 0 > for x in string: > if x in chars: > string[i] = '' > else: > break > i+=1 > return ''.join(string) > > >>> lstrip('abcd','abcd') > '' > >>> 'abcd'.lstrip('abcd') > '' > >>> 'go on long log buddy'.lstrip('gonl ') > 'buddy' > >>> lstrip('go on long log buddy', 'gonl ') > 'buddy' > >>> 'go on long log buddy'.lstrip('gonl') > ' on long log buddy' > >>> lstrip('go on long log buddy', 'gonl') > ' on long log buddy' > > So its not a brute force thing so much as a change in how you look at > it that makes it difficult. > By the same token, to do rstrip just [::-1] - ify string when you make it into a list and when you join it to be returned: >>> def rstrip(string,chars=' '): string = list(string)[::-1] i = 0 for x in string: if x in chars: string[i] = '' else: break i+=1 return ''.join(string)[::-1] >>> 'abcde'.rstrip('cde') 'ab' >>> 'abcde'.rstrip('ecd') 'ab' >>> rstrip('abcde','cde') 'ab' >>> rstrip('abcde','ecd') 'ab' -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From sandip at lug-delhi.org Thu Feb 3 05:51:50 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Thu Feb 3 05:52:12 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201A854.8000103@gmail.com> References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> Message-ID: <4201ADE6.1040908@lug-delhi.org> > for x in string: > if x in chars: > string[i] = '' I just have a hangover from other languages, but I really wanted to know how Python handles iteration over a variable which is being changed within the loop itself. Is the "for" condition evaluated in every loop? - Sandip From shaleh at speakeasy.net Thu Feb 3 06:01:09 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 06:01:29 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <4201B015.7030001@speakeasy.net> Liam Clarke wrote: > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! > > I'm not referring to the $ & @, I can see how they could be useful, > although with a list - > > @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], > not $d = $dude[1], that's counterintuitive also. > (I am an ex-perler gone clean. Been straight for 5 years now with only the occasional work forced binges.) Perl was designed by a linguist. He wanted it to act like human language -- which is not very consistent. That said, perhaps I can shed some light on the symbols. Ever learned a Romance language? latin, spanish, french, etc? The dollars and at signs can be thought of in relation to plural endings. $foo --> dog @dog --> a group of dogs $dog[0] --> a dog in the group So when you mean "the whole group" use the plural spelling and when you want to refer to a member use the singular spelling. Likewise with other parts of the language. Personally, the thing that keeps me away from Perl is nested datastructures. Python: my_list = [....] a_dict = {.....} b_dict = {.....} my_list.append(a_dict) my_list.append(b_dict) if my_list[0].has_key("foo"): print "Yes" easy. Try that in Perl. my @my_list; # remember those semicolons my %a_dict, %b_dict; push @my_list, %a_dict; push @my_list, %b_dict; if (exists $my_list->[0], "foo") print "Yes\n"; # yes, references required, in Perl ick. From singingxduck at gmail.com Thu Feb 3 06:05:24 2005 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Feb 3 06:05:58 2005 Subject: [Tutor] Better structure? In-Reply-To: <4201ADE6.1040908@lug-delhi.org> References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> Message-ID: <4201B114.7040108@gmail.com> Sandip Bhattacharya wrote: >> for x in string: >> if x in chars: >> string[i] = '' > > > I just have a hangover from other languages, but I really wanted to > know how Python handles iteration over a variable which is being > changed within the loop itself. Is the "for" condition evaluated in > every loop? > > - Sandip > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > AFAIK, the for condition in this case *is* evaluated at the beginning of every iteration, but this is misleading. For example: >>> string=list('banana') >>> for x in string: string.remove(x) print string Does not print ['a', 'n', 'a', 'n', 'a'] ['n', 'a', 'n', 'a'] ['a', 'n', 'a'] ['n', 'a'] ['a'] [] But rather: ['a', 'n', 'a', 'n', 'a'] ['a', 'a', 'n', 'a'] ['a', 'a', 'a'] Let's figure this out. First, string is ['b','a','n','a','n','a']. So x == 'b'. 'b' is removed, and string printed: ['a', 'n', 'a', 'n', 'a']. Then, the for loop grabs the second character in string (which has changed) because it has already used the first one. So x == 'n'. 'n' is removed and string printed, etc. In general, it is A Good Idea to not change the length of sequences as you loop over them. If you use a for i in range(len(string)): style, you will get an IndexError because in this case Python does *not* check len(string) every iteration. If you use a different style, you will just get weird results. HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From alan.gauld at freenet.co.uk Thu Feb 3 09:41:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 09:41:44 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> Message-ID: <01e601c509cc$240f2d80$68b78851@xp> > > Try writing the code to do what lstrip actually does > > - its much harder. So the library includes the more > > difficult function and lets you code the easy ones. > > def lstrip(string,chars=' ') > string = list(string) > t = 0 > for x in string: > if x in chars: > string.remove(t) > else: > break > t = t+1 > > > Okay, so it's not that difficult, but I get your point. I assume you didn't try testing that. It doesn't work. Its close but there are some extra wrinkles you need to consider. And its the wrinkles that makes writing library code hard! But even this is more complex than the simple front slicing that you were looking for. [As an aside, estimates vary, but it is reckoned to take between 5-10 times as much effort to write generic reusable code as it does to write specific code. One of the things proponents of the argument that "reuse is cheap" often forget! Its only cheap if someone else develops what you reuse!] > to a different module. Unfortunately, they are quite random and I will have > to find someway of seperating them. And another hard part of designing any library is figuring out the best logical structure, which module has which bits. > Uck. True usually in printing. String formatting doesn't cut it for a type > that's not a string. Especially something not builtin. It does if you override the __Str__ method of your newly defined type. Then you can print it using %s... Although you did trigger the interesting thought: I wonder if there is a way of hooking the formatting characters to tailor the representation, hmmm, some research required... > >You can even subclass string and make it a method if you like. > > Ooooh! How do I do that? class MyString(string): # your methods go here, and don't forget __init__... HTH, Alan G. From alan.gauld at freenet.co.uk Thu Feb 3 09:59:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 09:58:45 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <01f701c509ce$ab5933b0$68b78851@xp> > Just wondering if I should bite the bullet and code from scratch in > Perl, or if my Python - Perl is Ok. Its nearly always a bad idea to just translate code structures from one language to another. It will usually be sub optimal and non idiomatic - thus harder for the 'native' programmers to understand/debug. Bjarne Stroustrup made the same observation when C++ first came out and lots of Smalltalkers tried to use it like Smalltalk. He said "C++ is not Smalltalk, if you want to write Smalltalk use smalltalk" > 1) I'll use Perl for the regex stuff from now on, Perl is obviously > built for this. Yes, or PHP. Both have RE baked in. > 2 ) There's More Than One Way To Do It makes debugging hard - i.e. > close INFILE; & close (INFILE); are both valid. I like one syntax, cos > it's easier to remember. I can cope with that - BASIC does the same kind of thing - but its the zillion ways to handle errors that bug me! do thing until die do thing or die die unless do thing etc.... > 3) Some stuff is counter-intuitive - A huge understatement! :-) > Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to I don;t know but in cases like these I use parentheses like amaniac: if ( ((not $d) eq "a") && ((not $d) eq "c") ) Or did you mean if ( (not ($d eq "a")) && (not ($d eq "c")) ) Or was it if ( (not $d) eq ("a" && not ($d eq "c") ) # OK thats a bit unlikely... > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! Clever abbreviations apparently! I don't even like the $ and @... one reason I can never quite feel happy with Ruby. It has fewer of them but still more than I like. > In my opinion, there's only one place a > sign should be, in an > inequality test. Nope, I'm quite happy for it to be used in file indirection and even for right/left bit-shifting. But I don;t like it being part of the filename - I agree with that! > great for regexes > obviously based around *nix conventions. > Big hodge-podge, oozing with inconsistency. I'd hate to work > collaboratively on a Perl project. > Two steps up from Brainf**k in parts. > Obviously in need of a benevolent dictator a la Guido. Good summary! Perl reflects the fact that its inventor is a natural-language student not a computer scientist. It tries to incorporate the "richness of expression" of natural spech. But when dealing with machines that's a flaw IMHO! Alan G. From kraus at hagen-partner.de Thu Feb 3 10:09:26 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu Feb 3 10:10:53 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <01f701c509ce$ab5933b0$68b78851@xp> References: <01f701c509ce$ab5933b0$68b78851@xp> Message-ID: Alan Gauld wrote: [...] >>1) I'll use Perl for the regex stuff from now on, Perl is obviously >>built for this. > > > Yes, or PHP. Both have RE baked in. > Beware! Overcome the temptation! Try this: http://kodos.sourceforge.net/ HTH ;-) Wolfram From pathall at gmail.com Thu Feb 3 10:24:06 2005 From: pathall at gmail.com (Patrick Hall) Date: Thu Feb 3 10:24:09 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: <01f701c509ce$ab5933b0$68b78851@xp> Message-ID: <6465924d050203012479ff6970@mail.gmail.com> > Beware! Overcome the temptation! > Try this: http://kodos.sourceforge.net/ While I have no problem personally with Perl or PHP, I'll second the recommendation for kodos -- it's very useful for learning to use regexes in Python. From alan.gauld at freenet.co.uk Thu Feb 3 10:48:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 10:48:17 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> Message-ID: <021301c509d5$89daa960$68b78851@xp> > > How's Ruby? I bookmarked the homepage, but never got around to looking > > at it. > > Very, very nice. Cleanest object-orientedness I ever saw in a language > (not that I have that much experience -- people like Alan would > probably be better judges than me on this). You knew I couldn't resist! :-) Ruby OOP is OK although I don;t like the @ stuiff for members, theres simply no need for it! ONe thing I really like about Ruby is its implementation of iterators and generators - much better than Pythons IMHO. And their anonymous code blocks (aka lambdas) show how it can bve done. Pythons lambda feature is a bare minimum (and Guido wants to remove it!). > anyway because Ruby has a huge flaw: it's Japanese (AFAIK it's also the > only "Made in Japan" programming language, apart from stuff like ASM Yes the Japanese thing is an issue. THere are a few English books now, and the original one by Thomas and Hunt is free on the web. > And as far as I know there is no tutor@ruby-lang.org. No English one at least. > From what I remember, if you're programming in an object-oriented > style (which I now tend do by default unless there is a painfully > obvious and optimal solution in procedural style), Perl is the ugliest > thing ever created since Visual Basic. VB is a thing of beauty compared to Perl for OO! In fact I actually don't mind VB OOP at all, especially in its .NET variant which includes inheritance and polymorphism. But Perl OOP is a hideous bodge. > was frighteningly ugly. Java was built as an OO language from the > ground up, if you except the presence of the basic C types. But unfortunately built very badly as an OOP environment. Its more accurate to call it a class based language since its perfectly possible to build a Java program with no objecs but lots of classes! I'd go so far as to say that if you followed Java's lead on OOP you would pick up some very bad OO habits and write code that was not really very OOP at all! Thats not to say you can't write good OO code in Java just that Java does little to encourage it. You need to read a good OO book, like BRuce Eckels Thinking IN... series) to see how to do it properly! > ...Sure, it requires a lot of typing > (in both meanings of the word), :-) 1) The Java Virtual Machine is a horrible resource hog. Most virtual machines are, especially those that try to be the OS as opposed to simply wrap the OS... The old UCSD Pascal virtual machine was the same, it ran great on a mainframe but the little Mini computers we had in the labs were woeful! > 2) Sun didn't ever encourage anyone to write [insert language > here] compilers that compiled to JVM bytecode. I don't think they discouraged it, there are JVM compilers for Python, Smalltalk, Lisp, Tcl and Perl at least... And whats worse is that there are few native code compilers for Java. The JVM thing is a big hype factor IMHO. We've been writing C/C++ programs for years that ran on Windows/Unix and IBM boxes with only minor #ifdefs inserted. The performance (and hence costs for servers!) differences are huge! Its no coincidence that 2 of the biggest supporters of Java (IBM and Sun) are hardware vendors! A slightly cynical Alan G. From kent37 at tds.net Thu Feb 3 11:50:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 3 11:50:37 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <6465924d050203012479ff6970@mail.gmail.com> References: <01f701c509ce$ab5933b0$68b78851@xp> <6465924d050203012479ff6970@mail.gmail.com> Message-ID: <420201F8.1000408@tds.net> Patrick Hall wrote: >>Beware! Overcome the temptation! >>Try this: http://kodos.sourceforge.net/ > > > While I have no problem personally with Perl or PHP, I'll second the > recommendation for kodos -- it's very useful for learning to use > regexes in Python. Or, if you don't have Qt available, use the regular expression tester that comes with Python - it's at C:\Python24\Tools\Scripts\redemo.py (or whatever the *nix equivalent is). Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Thu Feb 3 14:00:02 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 14:00:10 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <021301c509d5$89daa960$68b78851@xp> References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> Message-ID: <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> On Feb 3, 2005, at 09:48, Alan Gauld wrote: > Pythons lambda feature is a bare minimum (and Guido wants to remove > it!). Does he? Damn, just when I was learning functional programming! (in Haskell, if you're curious ^^) > Yes the Japanese thing is an issue. > THere are a few English books now, and the original one by Thomas > and Hunt is free on the web. A little bit outdated, however. Ruby lacks a proper series of O'Reilly books; last time I checked the only one available was "Ruby in a Nutshell", which is a few years old and covers Ruby 1.6 (2 versions behind the current one). What Matz needs to do IMO is to gather a couple of the l33test Ruby hackers in the world in a nice house in the Japanese countryside, pick a cool-looking animal (what about an eastern dragon?), and sit down with them to write a thousand-page "Programming Ruby". > is a thing of beauty compared to Perl for OO! > In fact I actually don't mind VB OOP at all, especially in > its .NET variant which includes inheritance and polymorphism. > But Perl OOP is a hideous bodge. I haven't tried VB.NET (and don't intend to, I don't like BASIC-style languages), so I can't comment on this. > But unfortunately built very badly as an OOP environment. Its > more accurate to call it a class based language since its > perfectly possible to build a Java program with no objecs > but lots of classes! I'd go so far as to say that if you > followed Java's lead on OOP you would pick up some very > bad OO habits and write code that was not really very OOP > at all! > > Thats not to say you can't write good OO code in Java just > that Java does little to encourage it. You need to read a > good OO book, like BRuce Eckels Thinking IN... series) to > see how to do it properly! Well, of course, it all depends on how you're learning it. I'm sure there are some C tutorials out there that teach you (and encourage you) to use GOTO statements. :-D Me? I learnt Java by reading Eckel's "Thinking in Java" (and then followed with Wigglesworth/McMillan's "Java Programming: Advanced Topics"). I agree with you: it's an excellent book, that encourages good coding style and proper OOP. > And whats worse is that there are few native code compilers > for Java. The JVM thing is a big hype factor IMHO. We've been > writing C/C++ programs for years that ran on Windows/Unix and > IBM boxes with only minor #ifdefs inserted. The performance > (and hence costs for servers!) differences are huge! Its no > coincidence that 2 of the biggest supporters of Java > (IBM and Sun) are hardware vendors! Agreed. I'm no compiler programmer, but it seems to me that they could just have written a nice cross-platform API and then platform-specific compilers, while keeping the specification of the language intact (i.e. platform-independent endian-ness, type sizes, etc.). The reasoning behind the JVM is that you don't need to recompile your code to run it on a different platform. But most existing Java projects have platform-specific versions, if only to make the GUI (try to) look native. You can spot a Java app from a hundred meters away. (then again, the same critic could be made of Python's and Perl's "standard" GUI toolkits) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From amonroe at columbus.rr.com Thu Feb 3 14:29:41 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Feb 3 14:30:16 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> References: <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> Message-ID: <25317573686.20050203082941@columbus.rr.com> > code to run it on a different platform. But most existing Java projects > have platform-specific versions, if only to make the GUI (try to) look > native. You can spot a Java app from a hundred meters away. > (then again, the same critic could be made of Python's and Perl's > "standard" GUI toolkits) Amen. This drives me absolutely bonkers! Alan From Nicholas.Montpetit at deluxe.com Thu Feb 3 14:43:01 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 14:43:16 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. I'll try to speak to a few of the points below, from my limited experience: > Had the *ahem* joy of learning Perl last night. Egad. Wrote the script > in Python to get it right, and then 'translated' it to Perl. Does the > style of coding Python engenders suit the Perl environment in anyone's > experienc? AFAI can see there is no real 'style' to Perl, apart from > white noise of non alphanumeric characters. Actually, because there is "more than one way to do it", you can impose any style you want on your code, and (in my opinion) the onus _should_ be on the user to use "proper" style, however you want to define that. As Larry Wall says in the excellent "Natural Language Principals in Perl", "It's officially okay in the Perl realm to program in the subset of Perl corresponding to sed, or awk, or C, or shell, or BASIC, or Lisp or Python". > 1) I'll use Perl for the regex stuff from now on, Perl is obviously > built for this. No tool is better than Perl for that, IMO. > 2 ) There's More Than One Way To Do It makes debugging hard - i.e. > close INFILE; & close (INFILE); are both valid. I like one syntax, cos > it's easier to remember. Many people see "there's more than one way to do it" as a good thing. > 3) Some stuff is counter-intuitive - > $lenOfModList = @moddirList is the Perl equivalent of lenofModList = > len(moddirList) > @someArray = (@someArray, $newValue) is the same as someArray.append(newValue) It's only counter-intuitive if you don't know the language. Once you know the language, it's very intuitive. One could say that the theory of relativity is counter-intuitive, but to a physicist (or even anyone else who's thought about it for a while) it _is_ intuitive. It's all about context and perspective. Speaking of context, once you understand the concept of "context" in Perl, the statements above are very intuitive -- and elegant -- in my opinion. > Also, why doesn't if ( not $d eq "a" && not $d eq "c") evaluate to > true for $d = "b" when > if (not $d eq "a") evals to true and if ($d ne "a" && $d ne "c") evals > true also? What's with that? Must be an order-of-operations or logic thing, and I can assure you -- without even looking at it much -- that the problem isn't Perl's. > 4) WHAT IS WITH THE STUPID SYMBOLS EVERYWHERE LARRY??!! > > I'm not referring to the $ & @, I can see how they could be useful, > although with a list - > > @dude = (1, 2, 3), to obtain the 2nd value I would expect $d = @dude[1], > not $d = $dude[1], that's counterintuitive also. The definition of "counterintuitive" is based on context. That stuff is very intuitive when you understand the language. > Oh, no, what I'm referring to is stuff like @_, and @!, and @indexFile > = to read a whole file, and this - I hate Perl for this - > open OUTFILE, ">c:/python23/j/index.htm" > What's the difference between > open OUTFILE, "c:/python23/j/index.htm" and > open OUTFILE, ">c:/python23/j/index.htm" ? > > The first will open index.htm with the handle OUTFILE, to read... > The second will open index.htm with the handle OUTFILE to write!. So? That's the syntax of the language. I don't know why that would be bothersome... > Of course, the documentation I had didn't mention that. It just said > to open it and use > print FILEHANDLE $value; to write. Oh no, I had to find a CGI Perl > tutorial, which mentioned using &lst; to open and &gst; to write (or > something), which I guessed as lesser/greater than. > > Why is the read/write modifier part of the filename??? Why is it a > ? > In my opinion, there's only one place a > sign should be, in an > inequality test. Nicholas Montpetit Deluxe Business Services 651-787-1008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/b4e44d35/attachment.htm From scilamed at yahoo.com Thu Feb 3 14:53:31 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 14:53:36 2005 Subject: [Tutor] i have a question??? Message-ID: <20050203135332.67940.qmail@web41007.mail.yahoo.com> This is from a tutorial "EXERCISE 3.9 Use the math library to write a program to print out the sin and cos of numbers from 0 to 2pi in intervals of pi/6. You will need to use the range() function." Range won't let me use pi/6 as an incremator is there some other way i can accomplish this task im new to programming so all the help i can get is greatly appreciated. NI! alex __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From Nicholas.Montpetit at deluxe.com Thu Feb 3 15:03:27 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 15:03:33 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <4201B015.7030001@speakeasy.net> Message-ID: > (I am an ex-perler gone clean. Been straight for 5 years now with only > the occasional work forced binges.) > > Perl was designed by a linguist. He wanted it to act like human language > -- which is not very consistent. And from what I gather, quite effective. :-) > Personally, the thing that keeps me away from Perl is nested datastructures. > > Python: > > my_list = [....] > a_dict = {.....} > b_dict = {.....} > my_list.append(a_dict) > my_list.append(b_dict) > > if my_list[0].has_key("foo"): print "Yes" > > easy. Try that in Perl. OK, sounds like fun: my %a_dict = (...); my %b_dict = (...); my @my_list = (\%a_dict, \%b_dict); if (exists $my_list->[0]{foo}) print "Yes\n"; And if you want to do it another way: my @my_list = ( (...), (...) ); #define hashes in the (...)'s print "Yes\n" if (exists $my_list->[0]{foo}); Btw, I'm skeptical that the code below does what you want it to do. :-) > my @my_list; # remember those semicolons > my %a_dict, %b_dict; > push @my_list, %a_dict; > push @my_list, %b_dict; > if (exists $my_list->[0], "foo") print "Yes\n"; > # yes, references required, in Perl ick. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/a3f24801/attachment.html From mi.janssen at gmail.com Thu Feb 3 15:26:31 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Thu Feb 3 15:26:34 2005 Subject: [Tutor] i have a question??? In-Reply-To: <20050203135332.67940.qmail@web41007.mail.yahoo.com> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> Message-ID: <1ff2dfbf0502030626f78d954@mail.gmail.com> On Thu, 3 Feb 2005 05:53:31 -0800 (PST), alieks laouhe wrote: > This is from a tutorial > > "EXERCISE 3.9 > Use the math library to write a program to print out > the sin and cos of numbers from 0 to 2pi in intervals > of pi/6. You will need to use the range() function." > > Range won't let me use pi/6 as an incremator correct. The range is for integers only. You _can_ do the exercise with the range function but it would be easier without (eg. with a while-loop). Hint-no-solution: You will need a certain number of intervals, which (the number of intervalls) is plain integer. Then translate from current-intervall-number to pi'ish (sorry for that, my english ;-) value. regards Michael From pierre.barbier at cirad.fr Thu Feb 3 15:32:38 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu Feb 3 15:30:34 2005 Subject: [Tutor] i have a question??? In-Reply-To: <1ff2dfbf0502030626f78d954@mail.gmail.com> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> <1ff2dfbf0502030626f78d954@mail.gmail.com> Message-ID: <42023606.9000200@cirad.fr> Michael Janssen a ?crit : > On Thu, 3 Feb 2005 05:53:31 -0800 (PST), alieks laouhe > wrote: > >>This is from a tutorial >> >>"EXERCISE 3.9 >>Use the math library to write a program to print out >>the sin and cos of numbers from 0 to 2pi in intervals >>of pi/6. You will need to use the range() function." >> >> Range won't let me use pi/6 as an incremator > > > correct. The range is for integers only. You _can_ do the exercise > with the range function but it would be easier without (eg. with a > while-loop). I disagree ... :P And your next remark makes it clear range (or even better : xrange) is exactly what's needed for that problem ! > > Hint-no-solution: You will need a certain number of intervals, which > (the number of intervalls) is plain integer. Then translate from > current-intervall-number to pi'ish (sorry for that, my english ;-) > value. > > regards > Michael -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From jsmith at medplus.com Thu Feb 3 15:45:30 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 15:45:34 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Nicholas, Well put. I come from a physics FORTRAN background and when I decided to learn C and start using it I heard the same arguments: it's too hard to read. It's a silly argument to use against a language. It's like an English-only speaker claiming he won't learn Greek because he doesn't understand it :-) I've been programming Perl for about 10 years and Python about 6 months. Most of what Python programmers find counter-intuitive about Perl seem perfectly reasonable to me and I find something in Python quite counter-intuitive although I understand the rationale. For the non-Perl people here, let me defend Perl by saying it is VERY good at what it was built for and not so good (but passable) at what it was not built for. What it is good at: Very rapid development of small scripts Replacing sed/awk/ksh/etc for scripting Manipulating strings System administration tasks What it is only passable at Large scale team development OOP Most of what Python developmers complain about in Perl are aimed at the rapid development thing. Perl is very terse which allows you do quickly script up small filters and data miners. I still use Perl for this and don't think that will ever change. Someone also complained about the "many way to exit" issue. Personally, I love that and use it to clarify my code. On a normal if statement I will put the test first: (test) && (stuff-to-do); whereas if the test will affect code flow in a more major way I use the inversion, as with: return if (test); It allows me to quickly re-read my older scripts and understand the code flow faster. Having said all that, I'm also a big fan of Python which I can see will be very good at the two things Perl isn't so good at. However (and I know most here will disagree) there's still things I don't like about Python. My top two are: 1. Lack of closure on flow statements. I've already been bitten by: if test: do this do that where "do that" should have been out-dented. For a non-Python programmer, this "feature" can lead to some very non-intuitive coding should someone be so perverse as to write it :-) 2. Lack of "use strict" semantics. I know that pychecker can supposedly do this but I still believe it belongs in the language. Don't try to defend them. I've read all the arguments but I just don't agree with the design choice. Jeff -----Original Message----- From: Nicholas.Montpetit@deluxe.com [mailto:Nicholas.Montpetit@deluxe.com] Sent: Thursday, February 03, 2005 8:43 AM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. >... Nicholas Montpetit Deluxe Business Services 651-787-1008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/9c911ecf/attachment.html From Nicholas.Montpetit at deluxe.com Thu Feb 3 16:11:47 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 16:11:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: Message-ID: Hi Jeff, > Well put. I come from a physics FORTRAN background and when I > decided to learn C and start using it I heard the same arguments: > it's too hard to read. > > It's a silly argument to use against a language. It's like an > English-only speaker claiming he won't learn Greek because he > doesn't understand it :-) Now that's well put. > I've been programming Perl for about 10 years and Python about 6 > months. Most of what Python programmers find counter-intuitive > about Perl seem perfectly reasonable to me and I find something in > Python quite counter-intuitive although I understand the rationale. > > For the non-Perl people here, let me defend Perl by saying it is > VERY good at what it was built for and not so good (but passable) at > what it was not built for. > > What it is good at: > Very rapid development of small scripts > Replacing sed/awk/ksh/etc for scripting > Manipulating strings > System administration tasks > > What it is only passable at > Large scale team development > OOP I'll second your thoughts on Perl's shortcomings. What brought me to Python was the shortcomings in Perl that you've mentioned, along with Python's better numerical computation and GUI creation capabilities. If people on the list are to criticize Perl, I wish they would stick to the things that are Perl shortcomings for people who understand Perl. I'm OK with that, but I can't stand by and let people criticize something just because they don't understand it. I don't know anything about Python, so I'll reserve judgement until I do. I am confident that I will learn to like Python as much (or maybe even more :-) ) than I like Perl, and then I'll be able to choose the best tool for the task at hand. > Most of what Python developmers complain about in Perl are aimed at > the rapid development thing. Perl is very terse which allows you do > quickly script up small filters and data miners. I still use Perl > for this and don't think that will ever change. > > Someone also complained about the "many way to exit" issue. > Personally, I love that and use it to clarify my code. On a normal > if statement I will put the test first: I like the "there's more than one way to do it" thing as well. Your example below is very illustrative of that concept. > (test) && (stuff-to-do); > > whereas if the test will affect code flow in a more major way I use > the inversion, as with: > > return if (test); > > It allows me to quickly re-read my older scripts and understand the > code flow faster. One thing I really like about Python is the community: you folks are very friendly and helpful. I look forward to learning as much as I can about Python from this list! Thanks, -Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/27cc5a1f/attachment.htm From mi.janssen at gmail.com Thu Feb 3 16:49:13 2005 From: mi.janssen at gmail.com (Michael Janssen) Date: Thu Feb 3 16:49:17 2005 Subject: [Tutor] i have a question??? In-Reply-To: <42023606.9000200@cirad.fr> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> <1ff2dfbf0502030626f78d954@mail.gmail.com> <42023606.9000200@cirad.fr> Message-ID: <1ff2dfbf05020307494d7a11a3@mail.gmail.com> [the problem provided by alieks] > >>"EXERCISE 3.9 > >>Use the math library to write a program to print out > >>the sin and cos of numbers from 0 to 2pi in intervals > >>of pi/6. You will need to use the range() function." [Michael] > > You _can_ do the exercise > > with the range function but it would be easier without (eg. with a > > while-loop). [Pierre] > I disagree ... :P And your next remark makes it clear range (or even > better : xrange) is exactly what's needed for that problem ! [Michael's next remark] > > Hint-no-solution: You will need a certain number of intervals, which > > (the number of intervalls) is plain integer. Then translate from > > current-intervall-number to pi'ish (sorry for that, my english ;-) > > value. You're right, I've described the range-solution. But what makes you think, that the range-solution is actually the best/ simplest/ easiest? Within a while-loop you would increment your variable each time by pi/6 and test if still lower-equal than 2*pi (need care for float comparision) . With range you need to compute the "certain number of intervals", then for-loop through the range-generated list and compute the "pi'ish" value. There's a loop one way or another ;-) Unless one want to add some extra exercises like list comprehension and the map function. With the while-loop, you don't need to know certainly which number of intervals are needed, you just check if the upper boundary is reached. Don't know, perhaps I should post examples but alieks might still be working on the exercise and I don't want to spoil anybodies joy for my own one ;-) So, please alieks, post your results to us! regards Michael From marilyn at deliberate.com Thu Feb 3 18:33:06 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 3 18:37:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <01f701c509ce$ab5933b0$68b78851@xp> Message-ID: I once heard that Larry Wall said, "Perl is worse than Python because people needed it worse". And I've heard it said that "Perl is the Write-Only language" Marilyn From scilamed at yahoo.com Thu Feb 3 19:17:55 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 19:17:59 2005 Subject: [Tutor] got it In-Reply-To: <20050203154947.52E491E4004@bag.python.org> Message-ID: <20050203181755.10592.qmail@web41015.mail.yahoo.com> i came up with z=0 while z<= 2*pi: z=z+pi/6 print z z=z+pi/6 "while" makes alot more sense than using range i still don't know if its the most efficient way to do it this is day two with python, im pushing 30hrs straight lots of coffee and ciggarettes! So far I really like python...alot. it's so intuitive I started trying to learn c but it's lack of intuitive string handling made me shudder... so, i tried perl and it was a breath of fresh air after c. then i stumbled upon python. it's the most intuitive yet. anybody here have any experiance writing scripts for processing audio data? so, im glad python has alot of learning resources. thanks for your help alex __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From kent37 at tds.net Thu Feb 3 19:24:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 3 19:24:56 2005 Subject: [Tutor] got it In-Reply-To: <20050203181755.10592.qmail@web41015.mail.yahoo.com> References: <20050203181755.10592.qmail@web41015.mail.yahoo.com> Message-ID: <42026C75.3000309@tds.net> alieks laouhe wrote: > i came up with > > z=0 > while z<= 2*pi: > z=z+pi/6 > print z > z=z+pi/6 I don't think you're quite there. You are incrementing by pi/6 twice in the loop, so the printed values will differ by pi/3. And the first value printed will be pi/6, not 0. Where are you getting the value of pi? You can import it from the math module with from math import pi Kent > > "while" makes alot more sense than using range > i still don't know if its the most efficient way > to do it this is day two with python, im pushing 30hrs > straight lots of coffee and ciggarettes! > So far I really like python...alot. it's so intuitive > I started trying to learn c but it's lack of intuitive > string handling made me shudder... so, i tried perl > and it was a breath of fresh air after c. > then i stumbled upon python. it's the most intuitive > yet. > anybody here have any experiance writing scripts for > processing audio data? > so, im glad python has alot of learning resources. > thanks for your help > alex > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - What will yours do? > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From scilamed at yahoo.com Thu Feb 3 19:26:02 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 19:26:06 2005 Subject: [Tutor] oops. Message-ID: <20050203182603.40505.qmail@web41008.mail.yahoo.com> sorry way off heh... i think i'll sleep and try later. __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From alan.gauld at freenet.co.uk Thu Feb 3 19:36:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 19:35:38 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> Message-ID: <024e01c50a1f$4a4ab0c0$68b78851@xp> > > for x in string: > > if x in chars: > > string[i] = '' > > I just have a hangover from other languages, but I really wanted to know > how Python handles iteration over a variable which is being changed > within the loop itself. Is the "for" condition evaluated in every loop? Its bad practice to delete a member in the collection being iterated but Python copes OK if you just change the current item. Alan G. From scilamed at yahoo.com Thu Feb 3 19:37:20 2005 From: scilamed at yahoo.com (alieks laouhe) Date: Thu Feb 3 19:37:36 2005 Subject: [Tutor] v.00001 Message-ID: <20050203183721.32772.qmail@web41011.mail.yahoo.com> from math import * z=0 while z<=2*pi: print cos(z) z=z+(pi/6) ok i think this is right... __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From maxnoel_fr at yahoo.fr Thu Feb 3 19:40:53 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 19:40:56 2005 Subject: [Tutor] got it In-Reply-To: <20050203181755.10592.qmail@web41015.mail.yahoo.com> References: <20050203181755.10592.qmail@web41015.mail.yahoo.com> Message-ID: On Feb 3, 2005, at 18:17, alieks laouhe wrote: > So far I really like python...alot. it's so intuitive > I started trying to learn c but it's lack of intuitive > string handling made me shudder... so, i tried perl > and it was a breath of fresh air after c. > then i stumbled upon python. it's the most intuitive > yet. C is very good for a number of things (chief among those: speed). But string manipulation is definitely not one of them. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 19:52:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 19:52:22 2005 Subject: [Tutor] In-place changes on loops In-Reply-To: <4201ADE6.1040908@lug-delhi.org> Message-ID: On Thu, 3 Feb 2005, Sandip Bhattacharya wrote: > > for x in string: > > if x in chars: > > string[i] = '' > > I just have a hangover from other languages, but I really wanted to know > how Python handles iteration over a variable which is being changed > within the loop itself. Is the "for" condition evaluated in every loop? Hi Sandip, Strings are immutable, so the above code won't work. *grin* But let's change it to what I think you were thinking of: ### def lstrip(string, chars): scratchspace = list(string) ## get a mutable list of characters for x in scratchspace: if x in chars: scratchspace[i] = '' return ''.join(scratchspace) ### This works fine. In-place list changes that don't modify list structure will do ok. When we do structural changes to a list that we're iterating across, then we do have to be careful. The Reference Manual does mention caution near the bottom of: http://www.python.org/doc/ref/for.html When we have an statement of the form: ### Pseudocode ### for in : ###### then Python does evaluate just once. However, what it gets back is an "iterator", an object that marches across a sequence. For example: ### >>> message = list("this is a test") >>> iterator = iter(message) >>> iterator.next() 't' >>> iterator.next() 'h' >>> iterator.next() 'i' >>> iterator.next() 's' ### In effect, the for loop repeatedly calls next() on an iterator until it exhausts itself. The iterator doesn't try to be smart, so if we start mutating the list that backs the iterator, we do risk skipping elements. Let's try an experiment: ### >>> message = list("testing") >>> iterator = iter(message) >>> iterator.next() 't' >>> iterator.next() 'e' >>> message.insert(0, "x") >>> iterator.next() 'e' >>> iterator.next() 's' ### The 'insert()' shoves all the elements one place right. But, blissfully ignorant, the iterator doesn't shift itself, but instead stays in place. So the next call to next() revisits that 'e' character. Does this make sense? Please feel free to ask more questions about this. From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 20:18:36 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 20:18:41 2005 Subject: [Tutor] In-place changes on loops In-Reply-To: Message-ID: > But let's change it to what I think you were thinking of: > > ### > def lstrip(string, chars): > scratchspace = list(string) ## get a mutable list of characters > for x in scratchspace: > if x in chars: > scratchspace[i] = '' > return ''.join(scratchspace) > ### > > This works fine. Hi Sandip, Doh. I hate people who make blanket assertions like that without even doing a minimal test. Even if it is myself. *grin* The code above is just broken, since there is no index 'i'. Let me try to fix it. ### def lstrip(string, chars): scratchspace = list(string) ## get a mutable list of characters for (i, x) in enumerate(scratchspace): if x in chars: scratchspace[i] = '' return ''.join(scratchspace) ### I'm not going to make the same mistake twice: we're going to test this sucker. *grin* ### >>> lstrip("hello world", "he") 'llo world' >>> lstrip("hello world", "eh") 'llo world' ### Everything looks peachy... except: ### >>> lstrip("hello world", "aeiou") 'hll wrld' ### Ah! That's not right either! Ok, one more time: ### def lstrip(string, chars): scratchspace = list(string) ## get a mutable list of characters for (i, x) in enumerate(scratchspace): if x in chars: scratchspace[i] = '' else: break return ''.join(scratchspace) ### Quick sanity check: ### >>> lstrip("hello world", "eh") 'llo world' >>> lstrip("hello world", "he") 'llo world' >>> lstrip("hello world", "aeiou") 'hello world' ### Finally. *grin* Anyway, I wanted to apologize; I should have tested my code. From dyoo at hkn.eecs.berkeley.edu Thu Feb 3 20:29:56 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 3 20:30:00 2005 Subject: [Tutor] v.00001 In-Reply-To: <20050203183721.32772.qmail@web41011.mail.yahoo.com> Message-ID: On Thu, 3 Feb 2005, alieks laouhe wrote: > from math import * > z=0 > while z<=2*pi: > print cos(z) > z=z+(pi/6) > > ok i think this is right... Hi Alieks, This looks ok, and is probably the most straightforward way to do this. For safety's sake, you may want to modify the top import statement from: ### from math import * ### to something a little more limited: ### from math import pi, cos ### The reason is because the other form, the one with the '*', pulls everything into the current namespace, and that can be problematic in larger programs. There's a note about it here: http://www.python.org/doc/tut/node8.html#SECTION008410000000000000000 There are some cute things we can do with some advanced Python. You don't have to understand this yet, but here's a variation of your program: ### >>> def stepper(start, end, step): ... i = start ... while i <= end: ... yield i ... i = i + step ... >>> from math import pi, cos >>> for z in stepper(0, 2*pi, pi/6): ... print z, cos(z) ... 0 1.0 0.523598775598 0.866025403784 1.0471975512 0.5 1.57079632679 6.12303176911e-17 2.09439510239 -0.5 2.61799387799 -0.866025403784 3.14159265359 -1.0 3.66519142919 -0.866025403784 4.18879020479 -0.5 4.71238898038 -1.83690953073e-16 5.23598775598 0.5 5.75958653158 0.866025403784 ### stepper() acts like the range() function, but it can work on floating point numbers. range (and xrange) only work on integers: http://www.python.org/doc/lib/built-in-funcs.html#l2h-56 If we want to do some stepping across a range with floats, we can use the stepper() definition above. Best of wishes to you! From shaleh at speakeasy.net Thu Feb 3 20:42:32 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 20:42:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <42027EA8.4020603@speakeasy.net> Nicholas.Montpetit@deluxe.com wrote: > > > Btw, I'm skeptical that the code below does what you want it to do. :-) > that was kind of my point. In python I just type the obvious and it works. In Perl I have to muck with references, slashes, arrows and the like. Every time I have had to write a nested datastructure I have spent my time debugging that structure. From bill.mill at gmail.com Thu Feb 3 21:27:32 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 3 21:28:24 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <6465924d050203012479ff6970@mail.gmail.com> References: <01f701c509ce$ab5933b0$68b78851@xp> <6465924d050203012479ff6970@mail.gmail.com> Message-ID: <797fe3d40502031227485be921@mail.gmail.com> On Thu, 3 Feb 2005 04:24:06 -0500, Patrick Hall wrote: > > Beware! Overcome the temptation! > > Try this: http://kodos.sourceforge.net/ > > While I have no problem personally with Perl or PHP, I'll second the > recommendation for kodos -- it's very useful for learning to use > regexes in Python. Ok, I have to ask: why? Whenever I write and debug regexes (as I had to do this morning for the first time in a while - I try to avoid them) I always create a function in the interpreter that looks like: def test(regex, line): print re.compile(regex).match(line).groups() and then test my regexes incrementally: >>>l = '8 this is my line to test' >>> test('^\s*(\d)+', l) until I have it right. How is using this tool easier than that? Peace Bill Mill bill.mill at gmail.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Nicholas.Montpetit at deluxe.com Thu Feb 3 21:30:53 2005 From: Nicholas.Montpetit at deluxe.com (Nicholas.Montpetit@deluxe.com) Date: Thu Feb 3 21:30:59 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <42027EA8.4020603@speakeasy.net> Message-ID: > Nicholas.Montpetit@deluxe.com wrote: > > > > > > Btw, I'm skeptical that the code below does what you want it to do. :-) > > > > that was kind of my point. In python I just type the obvious and it > works. In Perl I have to muck with references, slashes, arrows and the > like. Every time I have had to write a nested datastructure I have spent > my time debugging that structure. Same here, Sean: whenever I work with nested data structures, I end up doing some debugging. However, I think that has more to do with my less-than-perfect understanding of references than with any Perl shortcomings. -Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050203/96d02212/attachment.html From keridee at jayco.net Thu Feb 3 22:04:25 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:05:34 2005 Subject: [Tutor] i have a question??? References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> Message-ID: <001601c50a34$2b196970$3d5328cf@JSLAPTOP> >From what I understand, range() no longer allows you to use floats as arguments. (Or it gives you a deprication warning) This tutorial must be old. Not the only way, but. import math num = 0 while num <= 2*math.pi: ## Do stuff to figure pi/6 things num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer result. print ## Result thingy Another way is to use Numarry (Numeric) arange() but that takes extra work. ;-) Jacob > This is from a tutorial > > "EXERCISE 3.9 > Use the math library to write a program to print out > the sin and cos of numbers from 0 to 2pi in intervals > of pi/6. You will need to use the range() function." > > Range won't let me use pi/6 as an incremator > is there some other way i can accomplish this task > im new to programming so all the help i can get is > greatly appreciated. > NI! > alex > > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - What will yours do? > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Thu Feb 3 22:07:04 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:06:59 2005 Subject: [Tutor] Better structure? References: <41FF6082.70005@tds.net><000001c508cb$5a67e9f0$3b5428cf@JSLAPTOP><42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com><4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> Message-ID: <001901c50a34$5b58f1a0$3d5328cf@JSLAPTOP> You can also iterate over a copy of the list and change the original. i.e. a = range(10) for x in a[:]: if x % 2 == 0: a.remove(x) print a And yes, I did test it this time. Jacob > >> > for x in string: >> > if x in chars: >> > string[i] = '' >> >> I just have a hangover from other languages, but I really wanted to > know >> how Python handles iteration over a variable which is being changed >> within the loop itself. Is the "for" condition evaluated in every > loop? > > Its bad practice to delete a member in the collection being iterated > but Python copes OK if you just change the current item. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Thu Feb 3 22:11:39 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:11:59 2005 Subject: [Tutor] v.00001 References: Message-ID: <002901c50a34$f9e5a0c0$3d5328cf@JSLAPTOP> I should have thought of that! Here I looked at the concept of generators, what they can do, and totally overlooked a user defined range type function that allows floats. Any reason why range doesn't? Is it for speed, or to keep the arguments pure (without floating point errors)? Jacob > There are some cute things we can do with some advanced Python. You don't > have to understand this yet, but here's a variation of your program: > > ### >>>> def stepper(start, end, step): > ... i = start > ... while i <= end: > ... yield i > ... i = i + step > ... >>>> from math import pi, cos >>>> for z in stepper(0, 2*pi, pi/6): > ... print z, cos(z) > ... > 0 1.0 > 0.523598775598 0.866025403784 > 1.0471975512 0.5 > 1.57079632679 6.12303176911e-17 > 2.09439510239 -0.5 > 2.61799387799 -0.866025403784 > 3.14159265359 -1.0 > 3.66519142919 -0.866025403784 > 4.18879020479 -0.5 > 4.71238898038 -1.83690953073e-16 > 5.23598775598 0.5 > 5.75958653158 0.866025403784 > ### > > > stepper() acts like the range() function, but it can work on floating > point numbers. range (and xrange) only work on integers: > > http://www.python.org/doc/lib/built-in-funcs.html#l2h-56 > > If we want to do some stepping across a range with floats, we can use the > stepper() definition above. > > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From miles at mstevenson.org Thu Feb 3 22:13:45 2005 From: miles at mstevenson.org (Miles Stevenson) Date: Thu Feb 3 22:12:14 2005 Subject: [Tutor] Ogg Tag Module recommendations Message-ID: <200502031613.48146.miles@mstevenson.org> Can anyone recommend to me a Python module to work with ID3v2 tags in Ogg Vorbis files? I tried using the EyeD3 module, but it only supports mp3 right now, and I couldn't get the pyid3tag module to work reliably, or I'm just not understanding the documentation. I just need to retrieve all of the ID3v2 tag info from a collection of ogg files, store them in a file, and then insert them back into different ogg files. Anyone have a module/library they recommend? Thanks. -- Miles Stevenson miles@mstevenson.org PGP FP: 035F 7D40 44A9 28FA 7453 BDF4 329F 889D 767D 2F63 -------------- 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/20050203/aca7aa4b/attachment.pgp From ternary at gmail.com Thu Feb 3 22:30:42 2005 From: ternary at gmail.com (Mike Bell) Date: Thu Feb 3 22:30:46 2005 Subject: [Tutor] i have a question??? In-Reply-To: <001601c50a34$2b196970$3d5328cf@JSLAPTOP> References: <20050203135332.67940.qmail@web41007.mail.yahoo.com> <001601c50a34$2b196970$3d5328cf@JSLAPTOP> Message-ID: <82975b0c050203133067f1d002@mail.gmail.com> > num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer the division operator returns a float when either of the operands are floats -- in this case math.pi is, so you don't have to worry about passing it 6.0 instead of 6 >>> import math >>> math.pi 3.1415926535897931 >>> math.pi / 6 0.52359877559829882 >>> type(math.pi) >>> type(6) >>> type(6.0) mike On Thu, 3 Feb 2005 16:04:25 -0500, Jacob S. wrote: > >From what I understand, range() no longer allows you to use floats as > arguments. (Or it gives you a deprication warning) > This tutorial must be old. > > Not the only way, but. > > import math > num = 0 > while num <= 2*math.pi: > ## Do stuff to figure pi/6 things > > num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer > result. > print ## Result thingy > > Another way is to use Numarry (Numeric) arange() but that takes extra work. > ;-) > Jacob > > > > This is from a tutorial > > > > "EXERCISE 3.9 > > Use the math library to write a program to print out > > the sin and cos of numbers from 0 to 2pi in intervals > > of pi/6. You will need to use the range() function." > > > > Range won't let me use pi/6 as an incremator > > is there some other way i can accomplish this task > > im new to programming so all the help i can get is > > greatly appreciated. > > NI! > > alex > > > > > > > > > > __________________________________ > > Do you Yahoo!? > > The all-new My Yahoo! - What will yours do? > > http://my.yahoo.com > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From shaleh at speakeasy.net Thu Feb 3 22:34:10 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 22:34:31 2005 Subject: [Tutor] Ogg Tag Module recommendations In-Reply-To: <200502031613.48146.miles@mstevenson.org> References: <200502031613.48146.miles@mstevenson.org> Message-ID: <420298D2.9060607@speakeasy.net> Miles Stevenson wrote: > Can anyone recommend to me a Python module to work with ID3v2 tags in Ogg > Vorbis files? I tried using the EyeD3 module, but it only supports mp3 right > now, and I couldn't get the pyid3tag module to work reliably, or I'm just not > understanding the documentation. > > I just need to retrieve all of the ID3v2 tag info from a collection of ogg > files, store them in a file, and then insert them back into different ogg > files. Anyone have a module/library they recommend? > The Ogg guys actually made a wrapper for Python, pyvorbis I think it is called. From keridee at jayco.net Thu Feb 3 22:40:24 2005 From: keridee at jayco.net (Jacob S.) Date: Thu Feb 3 22:40:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <007c01c50a38$fecfba40$3d5328cf@JSLAPTOP> MessageI hate to be a spoiled sport and do exactly what you said to not do. But I present two counter examples 1. The indentation IS the closure on flow statements. Indenting starts a flow, then removing indentation on next line closes the flow. Again its all about the language. If your English then don't look at Greek words and not want to learn them because you don't understand them. 2. The lack of "use strict semantics" is just one python's ways of using the term "There is more than one way to do it" Sorry, Jacob 1. Lack of closure on flow statements. I've already been bitten by: if test: do this do that where "do that" should have been out-dented. For a non-Python programmer, this "feature" can lead to some very non-intuitive coding should someone be so perverse as to write it :-) 2. Lack of "use strict" semantics. I know that pychecker can supposedly do this but I still believe it belongs in the language. Don't try to defend them. I've read all the arguments but I just don't agree with the design choice. Jeff -----Original Message----- From: Nicholas.Montpetit@deluxe.com [mailto:Nicholas.Montpetit@deluxe.com] Sent: Thursday, February 03, 2005 8:43 AM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. >... Nicholas Montpetit Deluxe Business Services 651-787-1008 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jeff at ccvcorp.com Thu Feb 3 22:59:38 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Feb 3 22:58:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> Message-ID: <42029ECA.2070305@ccvcorp.com> Max Noel wrote: > On Feb 3, 2005, at 09:48, Alan Gauld wrote: > >> Pythons lambda feature is a bare minimum (and Guido wants to remove >> it!). > > Does he? Damn, just when I was learning functional programming! (in > Haskell, if you're curious ^^) However, Python doesn't need lambdas to be able to write in a functional style. Functions are first-class objects and can be passed around quite easily, and IIRC Python's list comprehensions were borrowed (though probably with notable modification) from Haskell. Keep in mind that both lambdas and named functions are created at runtime, so the creation of both is fully dynamic. Indeed, there are only a few differences between lambdas and named functions in Python: - Anonymous vs named - Single expression vs suite of statements - Inline vs. pre-created Note that the second of these is a consequence of the third -- given Python's block-indentation-based structure, there's no good way to inline a multi-statement suite (how many of those statements belong to that 'if' suite?). Statements need to have a clear indentation level, and while one can sometimes fudge that for a single statement, it gets exponentially messier as the number of statements goes up. I'd also argue that the inline nature is the *true* differentiating feature of lambdas -- the fact that they're anonymous is relatively minor. Consider, also, that if they weren't inline then you'd need a name to refer to them by... and at that point, you *have* a 'normal' function. So, while there are some advantages to having single-use callables be defined inline (i.e. lambdas), their removal from Python (which wouldn't happen before the mythical Python 3k anyhow) isn't likely to be as devastating as some might lead you to believe. ;) It certainly won't prevent you from using Python for functional programming... (And personally, I suspect that if lambdas *are* removed, they will be replaced with a different construct that will fill the same needs in a more Pythonic way...) Jeff Shannon Technician/Programmer Credit International From shaleh at speakeasy.net Thu Feb 3 23:10:07 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Thu Feb 3 23:10:28 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <42029ECA.2070305@ccvcorp.com> References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> Message-ID: <4202A13F.70109@speakeasy.net> Jeff Shannon wrote: > > However, Python doesn't need lambdas to be able to write in a functional > style. Functions are first-class objects and can be passed around quite > easily, and IIRC Python's list comprehensions were borrowed (though > probably with notable modification) from Haskell. > Note, it is haskell convention to name a list of objects with a plural. So xs -> list of x. haskell: [ x | x <- xs ] [ foo x | x <- xs, x > 2 ] python [ x for x in xs ] [ foo(x) for x in xs if x > 2 ] shaleh still mastering haskell, but loving it. Like python for functional languages. From alan.gauld at freenet.co.uk Thu Feb 3 23:13:52 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 23:12:57 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <02b101c50a3d$a5574550$68b78851@xp> > > For the non-Perl people here, let me defend Perl by saying it is > > VERY good at what it was built for and not so good (but passable) at > > what it was not built for. > > > > What it is good at: > > Very rapid development of small scripts > > Replacing sed/awk/ksh/etc for scripting > > Manipulating strings > > System administration tasks Absolutely true and the reason I used Perl for several years before I used Python - even though I was aware of Python and had even fired up the interpreter a couple of times. But then I had the advantage of using C and C++ and Pascal(Delphi) and Lisp and Smalltalk for more complex programs. And I still used awk because Perl makes a lousy awk replacement! But as a shell replacement its great, and for string manipulation only Snoball beats it. The only reason I initially took Python seriously was as a teaching language for my tutorial, but once I got into it I realised it was a lot more powerful than I had originally thought. > > What it is only passable at > > Large scale team development > > OOP Passable is optimistic, I used Perl with a team of only 6 programmers and it was a disaster! > > Most of what Python developmers complain about in Perl are aimed at > > the rapid development thing. Perl is very terse which allows you do > > quickly script up small filters and data miners. I still use Perl > > for this and don't think that will ever change. Absolutely and I agree. The things I don't like are not the rapid development things, the $,@ symbology is completely unnecessary and is extremely counter intuitive even for experienced Perl coders. We still have arguments about references versus scalars etc yet after 10 years of using Perl in prodsuction code... It was a side effct of shell programming that should never have happened (although I will grant it yields a marginal speed increase by improving optimisation in the compiler!) > > Someone also complained about the "many way to exit" issue. > > Personally, I love that and use it to clarify my code. On a normal > > if statement I will put the test first: And for one person projects, where a consistent style is used its fine, but the minute you get beyond small projects its another complication waiting to bite. But again thats Perls background showing through. Python was never intended just for quick n dirty scripting it was from the outset designed as a general purpose language so embodied "best practice" - or Guidos take on that - as discovered by computer science research. Larry Wall simply created a language to do a job, it turned out to be powerful and got used a lot more than he expected! There is no perfect language, and very few truly bad languages - they never get out of the lab - they all have something that they are good at and from which we can learn! Alan G. From jsmith at medplus.com Thu Feb 3 23:21:51 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 23:21:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Jacob, As I said I'm well aware of the defense of these peculiarities of Python but I still disagree with them from a language design choice. That doesn't stop me from learning and using and enjoying Python but I feel that both of them introduce some instability to the langauge. In only 6 months of programming, I've already seen one case where if test: this that Was accidentally coded if test: this that (In fact, I suspect variations on this this may be the reason for the line spacing suggestions in PEP-8.) I've also seen several cases where an unbound variable caused an exception at runtime. True, these could be caught by extensive unit testing but know the reality of that happening :-) Perl and Python both resist the introduction of a switch statement which I (and many others) feel is the most elegant way to express what it does. I also wish Python would take up the C ternary operator which is also quite clear and elegant. Of course, there are things I disklike about every other language I've used. To paraphrase the famous quote: There are no good programming languages, just some that aren't as bad in some situations. Jeff -----Original Message----- From: Jacob S. [mailto:keridee@jayco.net] Sent: Thursday, February 03, 2005 4:40 PM To: Smith, Jeff; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] MessageI hate to be a spoiled sport and do exactly what you said to not do. But I present two counter examples 1. The indentation IS the closure on flow statements. Indenting starts a flow, then removing indentation on next line closes the flow. Again its all about the language. If your English then don't look at Greek words and not want to learn them because you don't understand them. 2. The lack of "use strict semantics" is just one python's ways of using the term "There is more than one way to do it" Sorry, Jacob 1. Lack of closure on flow statements. I've already been bitten by: if test: do this do that where "do that" should have been out-dented. For a non-Python programmer, this "feature" can lead to some very non-intuitive coding should someone be so perverse as to write it :-) 2. Lack of "use strict" semantics. I know that pychecker can supposedly do this but I still believe it belongs in the language. Don't try to defend them. I've read all the arguments but I just don't agree with the design choice. Jeff -----Original Message----- From: Nicholas.Montpetit@deluxe.com [mailto:Nicholas.Montpetit@deluxe.com] Sent: Thursday, February 03, 2005 8:43 AM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Well, here's my $0.02. I would recommend caution regarding the trashing of Perl. One thing I've been very impressed with on this list (and other segments of the Python community) is the _fairly_ cordial relationship between the supporters of the two languages. Contrast that to a lot of PHP literature I've seen, which doesn't even acknowledge that Perl exists. My theory is that many who use PHP got kicked around by trying to learn Perl, and bitterness set in. But that's a digression... Anyway, I'm on the fence as to whether I want to learn Python (not exactly a "core competency" for statisticians, but I do line the numerical computation capabilities which look _much_ better than those of Perl), and I wouldn't want this negativity to push me (or others) away. >... Nicholas Montpetit Deluxe Business Services 651-787-1008 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jsmith at medplus.com Thu Feb 3 23:27:26 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 23:27:31 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Alan, We'll just have to have to disagree about awk. I starting learning Perl to avoid learning awk :-) I also disagree about the symbology. I am never confused by it. In fact, I find it clarifies the language although I agree its ugly. When I see a random variable in Perl I can tell at a glance whether it's a scalar, list, or hash. That isn't true in Python (or most other languages). I realize that doesn't mean much in large OOP programs but in medium to large single-purpose scripts it does simplify debugging and maintenance. Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 5:14 PM To: Nicholas.Montpetit@deluxe.com; Smith, Jeff Cc: tutor@python.org; tutor-bounces@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > For the non-Perl people here, let me defend Perl by saying it is > > VERY good at what it was built for and not so good (but passable) at > > what it was not built for. > > > > What it is good at: > > Very rapid development of small scripts > > Replacing sed/awk/ksh/etc for scripting > > Manipulating strings > > System administration tasks Absolutely true and the reason I used Perl for several years before I used Python - even though I was aware of Python and had even fired up the interpreter a couple of times. But then I had the advantage of using C and C++ and Pascal(Delphi) and Lisp and Smalltalk for more complex programs. And I still used awk because Perl makes a lousy awk replacement! But as a shell replacement its great, and for string manipulation only Snoball beats it. The only reason I initially took Python seriously was as a teaching language for my tutorial, but once I got into it I realised it was a lot more powerful than I had originally thought. > > What it is only passable at > > Large scale team development > > OOP Passable is optimistic, I used Perl with a team of only 6 programmers and it was a disaster! > > Most of what Python developmers complain about in Perl are aimed at > > the rapid development thing. Perl is very terse which allows you do > > quickly script up small filters and data miners. I still use Perl > > for this and don't think that will ever change. Absolutely and I agree. The things I don't like are not the rapid development things, the $,@ symbology is completely unnecessary and is extremely counter intuitive even for experienced Perl coders. We still have arguments about references versus scalars etc yet after 10 years of using Perl in prodsuction code... It was a side effct of shell programming that should never have happened (although I will grant it yields a marginal speed increase by improving optimisation in the compiler!) > > Someone also complained about the "many way to exit" issue. > > Personally, I love that and use it to clarify my code. On a normal > > if statement I will put the test first: And for one person projects, where a consistent style is used its fine, but the minute you get beyond small projects its another complication waiting to bite. But again thats Perls background showing through. Python was never intended just for quick n dirty scripting it was from the outset designed as a general purpose language so embodied "best practice" - or Guidos take on that - as discovered by computer science research. Larry Wall simply created a language to do a job, it turned out to be powerful and got used a lot more than he expected! There is no perfect language, and very few truly bad languages - they never get out of the lab - they all have something that they are good at and from which we can learn! Alan G. From maxnoel_fr at yahoo.fr Thu Feb 3 23:39:54 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 3 23:40:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <03069c6c3fc10b69ddf897e517d944e6@yahoo.fr> On Feb 3, 2005, at 22:21, Smith, Jeff wrote: > Perl and Python both resist the introduction of a switch statement > which > I (and many others) feel is the most elegant way to express what it > does. I echo that. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Thu Feb 3 23:47:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 3 23:46:25 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <02ee01c50a42$52f6ea40$68b78851@xp> > I also disagree about the symbology. I am never confused by it. I'll believe you, but its interesting that computer scientists have done lots of studies to test people's comprehension of programs and in every single case there has been clear evidence that additional prefixes/characters etc obscure undestanding. Even by those who thought they were fluent in the language concerned. Check the book Code Complete for some references, or try searching the Software Engineering Institute stuff at CMU. Its like the old argument in C over whether int f(){ blah() } or int f() { blah() } was clearer. Many people claim to prefer the second but objective testing repeatedly shows that the first form produces measurably better results. In both of these cases its not about style its about what works. I suspect Guido was aware of that research and applied it to Python's design. Larry wasn't and didn't... (although he sure is now! :-) Alan G. From jsmith at medplus.com Thu Feb 3 23:49:20 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 3 23:49:31 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: I think the point is that different people are...different. It probably won't surprise you to find out that I am in the C camp that prefers your second example. I'm sure what those studies show is what the "majority" find easier not what "everyone" finds easier. Who knows, maybe it's a left-brain, right-brain thing. And it wouldn't be the first time I was told my brain was "wired differently" from the general public. Just ask my wife :-) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 5:47 PM To: Smith, Jeff; Nicholas.Montpetit@deluxe.com Cc: tutor@python.org; tutor-bounces@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > I also disagree about the symbology. I am never confused by it. I'll believe you, but its interesting that computer scientists have done lots of studies to test people's comprehension of programs and in every single case there has been clear evidence that additional prefixes/characters etc obscure undestanding. Even by those who thought they were fluent in the language concerned. Check the book Code Complete for some references, or try searching the Software Engineering Institute stuff at CMU. Its like the old argument in C over whether int f(){ blah() } or int f() { blah() } was clearer. Many people claim to prefer the second but objective testing repeatedly shows that the first form produces measurably better results. In both of these cases its not about style its about what works. I suspect Guido was aware of that research and applied it to Python's design. Larry wasn't and didn't... (although he sure is now! :-) Alan G. From lumbricus at gmx.net Fri Feb 4 00:10:32 2005 From: lumbricus at gmx.net (lumbricus@gmx.net) Date: Fri Feb 4 00:10:34 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <24692.1107472232@www13.gmx.net> > Alan, > > We'll just have to have to disagree about awk. I starting learning Perl > to avoid learning awk :-) But awk is smaller and simpler than perl. So it should be faster (esp. at startup) for small and simple tasks. As usual: Right tool for right task. > Jeff _______________ Greetings, J"o! (being glad to have a choice) -- Wir sind jetzt ein Imperium und wir schaffen uns unsere eigene Realitaet. Wir sind die Akteure der Geschichte, und Ihnen, Ihnen allen bleibt nichts, als die Realitaet zu studieren, die wir geschaffen haben. -- Karl Rove zu Ron Suskind (NYT) DSL Komplett von GMX +++ Supergünstig und stressfrei einsteigen! AKTION "Kein Einrichtungspreis" nutzen: http://www.gmx.net/de/go/dsl From alan.gauld at freenet.co.uk Fri Feb 4 00:17:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:16:19 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> Message-ID: <02ff01c50a46$7d75d570$68b78851@xp> > >> Pythons lambda feature is a bare minimum (and Guido wants to remove > >> it!). > However, Python doesn't need lambdas to be able to write in a > functional style. I disagree Jeff. It does need lambdas to do FP properly, and better lambdas than we have currently. What it doesn't need is the lambda keyword and syntax - although pesonally I like lambda since it is descriptive! > Functions are first-class objects and can be passed > around quite easily, Yes, but lambdas are more than first class functions, they are anonymous functions! In fact really just callable code blocks, not necessarily functions in the strictest sense (except that every callable in FP is a function...! ;-) Having to define every function before using it would be a big hassle and make code less readable IMHO. > borrowed (though probably with notable modification) from Haskell. Conceptually not much modification, but the two syntaxes are poles apart! > only a few differences between lambdas and named functions in Python: > > - Anonymous vs named the key feature > - Single expression vs suite of statements A python restriction. > - Inline vs. pre-created A key usage point > Note that the second of these is a consequence of the third Again a Python restriction. And hard to see how you avoid given Pythons structure. > I'd also argue that the inline nature is the *true* differentiating > feature of lambdas -- the fact that they're anonymous is relatively > minor. I agree, if I had an inline mechanism that forced me to provide a name I could just use 'f' over and over and not feel too cheated, but its nicer not to have an artificial name when theres no need. > So, while there are some advantages to having single-use callables be > defined inline The other advantage is the huge conceptial advantage that real lambdas confer. The breakthrough idea of def f(x): return x+x being the same as f = lambda x: x+x is only possible to demonstrate if you have lambda to start with. And yet that concept of a function name being just another variable and the callable code being an object in its own right becomes much more obvious in my opinion. lambda is a learning tool which shows what is really happening whereas def is just syntactic sugar. > (And personally, I suspect that if lambdas *are* removed, they will be > replaced with a different construct that will fill the same needs in a > more Pythonic way...) I believe (and hope) this too. Certainly the stink it has created on c.l.p should hopefully convince Guido that there is a groundswell of demand for the facility if not the name... Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 00:19:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:21:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <4202A13F.70109@speakeasy.net> Message-ID: <030401c50a46$c7d41280$68b78851@xp> > haskell: > > [ x | x <- xs ] > [ foo x | x <- xs, x > 2 ] > > python > > [ x for x in xs ] > [ foo(x) for x in xs if x > 2 ] > Sean, what book/tutor are you using for Haskell? I learned it from "The Haskell School of Expression" which was OK but very graphics focused, I'd be interested in recommended second source on Haskell. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 00:28:36 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:27:35 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <030b01c50a48$15e2df00$68b78851@xp> > Perl and Python both resist the introduction of a switch statement > which I (and many others) feel is the most elegant way to express > what it does. Interesting. What do you feel is the problem with elif? Its not even much more typing and allows for much more expressive test conditions. Switch is really only useful for a single subset of tests. And of course switch statements are notorious bug factories and maintenance nightmares - the reason why OOP tries to eliminate them wherever possible. > I also wish Python would take up the C ternary operator > which is also quite clear and elegant. :-) You joke I assume? ':?' is clear? Its succinct but also prone to abuse. I don't think the Python equivalent foo = x and y or z is much less elegant than foo = x ? y : z > ... To paraphrase the famous quote: There are no good programming languages, just some that aren't as bad in some situations. Absolutely true. I still use assembler occasionally, and I even like bits of COBOL (although not much, its my least favourite language!). And probably my favourite language of all is Logo even though I've never used it for any serious projects. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 00:30:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:31:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <031001c50a48$5e1cb570$68b78851@xp> > We'll just have to have to disagree about awk. > I starting learning Perl to avoid learning awk :-) Really? Why for? awk is far easier to learn than Perl - and far less generally capable! - but it makes Perl seem positively verbose! Alan G. From jeff at ccvcorp.com Fri Feb 4 00:41:25 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 00:40:42 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <02b101c50a3d$a5574550$68b78851@xp> References: <02b101c50a3d$a5574550$68b78851@xp> Message-ID: <4202B6A5.3030805@ccvcorp.com> Alan Gauld wrote: > There is no perfect language, and very few truly bad > languages - they never get out of the lab - they all > have something that they are good at and from which > we can learn! Heh, I'd look at that a bit differently -- I think that there's a *lot* of bad languages, it's just that we're spared ever hearing about the majority of them because they don't ever get very far. ;) (But then, at my job I'm stuck using a horrible Frankenstein's monster of a proprietary language on a daily basis, so I can't help but believe that there's plenty more awful languages around that didn't happen to be "rescued" from oblivion by an accident of history...) Jeff Shannon Technician/Programmer Credit International From alan.gauld at freenet.co.uk Fri Feb 4 00:41:33 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 00:41:08 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <031901c50a49$e5142440$68b78851@xp> > second example. I'm sure what those studies show is what the "majority" > find easier not what "everyone" finds easier. They are statistical its true, but they were based on the folks who actually used the second style indent and they actually got worse scores in the tests using their own style than when they used the style they were less used too. The tests have been repeated many times using multiple languages and thousands of subjects ranging from students through to professionals with years of experience. The reasons for the K&R style of brace winning is to do with the way the brain process structure and despite the subjects stated preference for the 'Pascal' style they still had lower perception scores. As I said its not a style issue its to do with how the brain works and the outcome of a lot of studies over at least 30 years produces a pretty solid case. > left-brain, right-brain thing. Nope they tried that too, comparing creative types with science types etc. Same result. > told my brain was "wired differently" from the general > public. Just ask my wife :-) And they tried mixing up the sexes too, no difference. There may be a few individuals for whom it doesn't apply but in the vast majority of cases its a fact. In fact the best style of all is neither of the two I showed, its actually this - which early everyone hates when they see it! inf f(x) { bah() } After reading the studies I changed my C style to the above, it certainly hasn't made my code harder to debug and I don't see any increase in bug count, but I can't honestly say I notice a reduction either, but it helps to know that I'm increasing the chances of my code being understood by someone else... Alan G. From maxnoel_fr at yahoo.fr Fri Feb 4 00:47:47 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 00:47:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <030401c50a46$c7d41280$68b78851@xp> References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <4202A13F.70109@speakeasy.net> <030401c50a46$c7d41280$68b78851@xp> Message-ID: On Feb 3, 2005, at 23:19, Alan Gauld wrote: > Sean, what book/tutor are you using for Haskell? > I learned it from "The Haskell School of Expression" which > was OK but very graphics focused, I'd be interested in > recommended second source on Haskell. I'm not Sean, but I'm using Simon Thompson's "Haskell: The Craft of Functional Programming", which I find quite good. However, it's a bit odd, in that it almost reads like a mathematics book, which is something you may or may not like. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri Feb 4 00:51:41 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 00:51:53 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <4202B6A5.3030805@ccvcorp.com> References: <02b101c50a3d$a5574550$68b78851@xp> <4202B6A5.3030805@ccvcorp.com> Message-ID: <56c97b3bed48eeaf1d13a6e97311cd9a@yahoo.fr> On Feb 3, 2005, at 23:41, Jeff Shannon wrote: > (But then, at my job I'm stuck using a horrible Frankenstein's monster > of a proprietary language on a daily basis, so I can't help but > believe that there's plenty more awful languages around that didn't > happen to be "rescued" from oblivion by an accident of history...) Yeah. Sometimes I read a little bit of Wikipedia's "Esoteric Programming Languages" page, and some of them just leave me in awe. Brainfuck (and its variant Ook!) and INTERCAL ("GOTO is considered harmful, so we removed it -- INTERCAL uses COME FROM instead") are already quite impressive, but the very idea of Befunge makes my brain want to explode. Especially that extension to the language that allows one to write N-dimensional programs. :D -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Fri Feb 4 00:57:16 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 00:57:22 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <031901c50a49$e5142440$68b78851@xp> References: <031901c50a49$e5142440$68b78851@xp> Message-ID: <6b97374ce906150985bb042f036797ba@yahoo.fr> On Feb 3, 2005, at 23:41, Alan Gauld wrote: > The reasons for the K&R style of brace winning is to do > with the way the brain process structure and despite > the subjects stated preference for the 'Pascal' style > they still had lower perception scores. Little nit-picking here: if(foo) { bar(); } Is not K&R style, but Allman style. K&R style (also known as One True Brace Style or 1TBS) is this: if(foo) { bar; } -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From jeff at ccvcorp.com Fri Feb 4 01:06:55 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 01:06:12 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <02ff01c50a46$7d75d570$68b78851@xp> References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> <02ff01c50a46$7d75d570$68b78851@xp> Message-ID: <4202BC9F.8080800@ccvcorp.com> Alan Gauld wrote: > >>However, Python doesn't need lambdas to be able to write in a >>functional style. > > I disagree Jeff. It does need lambdas to do FP properly, and > better lambdas than we have currently. What it doesn't need > is the lambda keyword and syntax - although pesonally I like > lambda since it is descriptive! Well, we'll have to continue to disagree on that. ;) Personally, I can't help but think that 'lambda' is descriptive only to people who've experienced it elsewhere, and that that does *not* include the majority of the programming community, but I could be mistaken. :) >>Functions are first-class objects and can be passed >>around quite easily, > > Yes, but lambdas are more than first class functions, they > are anonymous functions! In fact really just callable code > blocks, not necessarily functions in the strictest sense > (except that every callable in FP is a function...! ;-) Well, given that in Python a function is just a callable code block that's bound to a name... ;) Personally, I fail to see why having an anonymous function is such a huge conceptual advantage, no matter how many times this is proclaimed as truth by lambda-users, but again this is just my own impression. > Having to define every function before using it would > be a big hassle and make code less readable IMHO. Here, ISTM that you're emphasizing the in-line nature of lambdas as being their key usage point... And personally, I prefer to have a glossary of terms rather than having to decipher jargon by context. ;) >>only a few differences between lambdas and named functions in >> Python: >> >> - Anonymous vs named > > the key feature Again, I fail to see why this is such an advantage -- I've seen assertions that it is, over and over again, but never any convincing evidence.... >> - Single expression vs suite of statements > > A python restriction. Well, I *did* specify that I was talking about 'in Python'... ;) >>I'd also argue that the inline nature is the *true* differentiating >>feature of lambdas -- the fact that they're anonymous is relatively >>minor. > > I agree, if I had an inline mechanism that forced me to > provide a name I could just use 'f' over and over and > not feel too cheated, but its nicer not to have an artificial > name when theres no need. Personally, I prefer to have the opportunity to provide a meaningful name, and don't see where a generic name is any more restrictive than having no name, but again, maybe that's just me. >>So, while there are some advantages to having single-use callables >>be defined inline > > The other advantage is the huge conceptial advantage that > real lambdas confer. The breakthrough idea of > > def f(x): return x+x > > being the same as > > f = lambda x: x+x > > is only possible to demonstrate if you have lambda to start with. > And yet that concept of a function name being just another variable > and the callable code being an object in its own right becomes > much more obvious in my opinion. lambda is a learning tool which > shows what is really happening whereas def is just syntactic sugar. Hm, I understood the idea of functions being just code objects that were bound to a name, and could be passed around, stored in collections, and effectively renamed, well before I really got a hold on lambdas as anything more than some confusing bit of magic. Of course, I started in C, where I was fairly comfortable with the idea of function pointers; function objects are a pretty simple step up, abstraction-wise, from that. I suppose that one might argue that I *still* just don't really get lambdas (and I wouldn't argue with that). I can see some advantages to small inline functions, though I suspect that a more-explicit currying mechanism (such as the proposed partial() higher-order function) could easily replace such uses. I'm sorry to say, though, that the supposed advantages of anonymity come across as little more than handwaving assertions to me, no matter how sincerely they're intended. (I've just started to read through SICP, to pick up some lisp/scheme, in hopes of understanding the appeal a bit better, so maybe there's hope for me yet. ;) ) Jeff Shannon Technician/Programmer Credit International From keridee at jayco.net Fri Feb 4 01:23:25 2005 From: keridee at jayco.net (Jacob S.) Date: Fri Feb 4 01:23:45 2005 Subject: [Tutor] i have a question??? References: <20050203135332.67940.qmail@web41007.mail.yahoo.com><001601c50a34$2b196970$3d5328cf@JSLAPTOP> <82975b0c050203133067f1d002@mail.gmail.com> Message-ID: <008001c50a4f$d76aec10$3d5328cf@JSLAPTOP> Sorry, over paranoid. ;-) Jacob >> num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer > > the division operator returns a float when either of the operands are > floats -- in this case math.pi is, so you don't have to worry about > passing it 6.0 instead of 6 > >>>> import math >>>> math.pi > 3.1415926535897931 >>>> math.pi / 6 > 0.52359877559829882 > >>>> type(math.pi) > >>>> type(6) > >>>> type(6.0) > > > > mike > > > > On Thu, 3 Feb 2005 16:04:25 -0500, Jacob S. wrote: >> >From what I understand, range() no longer allows you to use floats as >> arguments. (Or it gives you a deprication warning) >> This tutorial must be old. >> >> Not the only way, but. >> >> import math >> num = 0 >> while num <= 2*math.pi: >> ## Do stuff to figure pi/6 things >> >> num = num + math.pi/6.0 ## Don't forget .0 or you'll get an integer >> result. >> print ## Result thingy >> >> Another way is to use Numarry (Numeric) arange() but that takes extra >> work. >> ;-) >> Jacob >> >> >> > This is from a tutorial >> > >> > "EXERCISE 3.9 >> > Use the math library to write a program to print out >> > the sin and cos of numbers from 0 to 2pi in intervals >> > of pi/6. You will need to use the range() function." >> > >> > Range won't let me use pi/6 as an incremator >> > is there some other way i can accomplish this task >> > im new to programming so all the help i can get is >> > greatly appreciated. >> > NI! >> > alex >> > >> > >> > >> > >> > __________________________________ >> > Do you Yahoo!? >> > The all-new My Yahoo! - What will yours do? >> > http://my.yahoo.com >> > _______________________________________________ >> > Tutor maillist - Tutor@python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From cyresse at gmail.com Fri Feb 4 01:25:31 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 4 01:25:36 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <4202BC9F.8080800@ccvcorp.com> References: <86626245450c1bfcf3190400baffe178@yahoo.fr> <9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com> <02ff01c50a46$7d75d570$68b78851@xp> <4202BC9F.8080800@ccvcorp.com> Message-ID: >I suppose that one might argue that I *still* just don't really get >lambdas (and I wouldn't argue with that). I can see some advantages >to small inline functions, though I suspect that a more-explicit >currying mechanism (such as the proposed partial() higher-order >function) could easily replace such uses. I'm sorry to say, though, >that the supposed advantages of anonymity come across as little more >than handwaving assertions to me, no matter how sincerely they're >intended. I'm with Jeff on this one - I've yet to see the light regarding lambda's. I understand they're used through-out Tkinter GUI stuff, can anyone put up an example of why a lambda is better? I would like to 'get' the concepts. Is this one of those conceptual things like OOP? Or is it a subtlety that a Masters in COSC is necessary to appreciate? On Thu, 03 Feb 2005 16:06:55 -0800, Jeff Shannon wrote: > Alan Gauld wrote: > > > > >>However, Python doesn't need lambdas to be able to write in a > >>functional style. > > > > I disagree Jeff. It does need lambdas to do FP properly, and > > better lambdas than we have currently. What it doesn't need > > is the lambda keyword and syntax - although pesonally I like > > lambda since it is descriptive! > > Well, we'll have to continue to disagree on that. ;) Personally, I > can't help but think that 'lambda' is descriptive only to people > who've experienced it elsewhere, and that that does *not* include the > majority of the programming community, but I could be mistaken. :) > > >>Functions are first-class objects and can be passed > >>around quite easily, > > > > Yes, but lambdas are more than first class functions, they > > are anonymous functions! In fact really just callable code > > blocks, not necessarily functions in the strictest sense > > (except that every callable in FP is a function...! ;-) > > Well, given that in Python a function is just a callable code block > that's bound to a name... ;) Personally, I fail to see why having an > anonymous function is such a huge conceptual advantage, no matter how > many times this is proclaimed as truth by lambda-users, but again this > is just my own impression. > > > Having to define every function before using it would > > be a big hassle and make code less readable IMHO. > > Here, ISTM that you're emphasizing the in-line nature of lambdas as > being their key usage point... And personally, I prefer to have a > glossary of terms rather than having to decipher jargon by context. ;) > > >>only a few differences between lambdas and named functions in > >> Python: > >> > >> - Anonymous vs named > > > > the key feature > > Again, I fail to see why this is such an advantage -- I've seen > assertions that it is, over and over again, but never any convincing > evidence.... > > >> - Single expression vs suite of statements > > > > A python restriction. > > Well, I *did* specify that I was talking about 'in Python'... ;) > > > >>I'd also argue that the inline nature is the *true* differentiating > >>feature of lambdas -- the fact that they're anonymous is relatively > >>minor. > > > > I agree, if I had an inline mechanism that forced me to > > provide a name I could just use 'f' over and over and > > not feel too cheated, but its nicer not to have an artificial > > name when theres no need. > > Personally, I prefer to have the opportunity to provide a meaningful > name, and don't see where a generic name is any more restrictive than > having no name, but again, maybe that's just me. > > >>So, while there are some advantages to having single-use callables > >>be defined inline > > > > The other advantage is the huge conceptial advantage that > > real lambdas confer. The breakthrough idea of > > > > def f(x): return x+x > > > > being the same as > > > > f = lambda x: x+x > > > > is only possible to demonstrate if you have lambda to start with. > > And yet that concept of a function name being just another variable > > and the callable code being an object in its own right becomes > > much more obvious in my opinion. lambda is a learning tool which > > shows what is really happening whereas def is just syntactic sugar. > > Hm, I understood the idea of functions being just code objects that > were bound to a name, and could be passed around, stored in > collections, and effectively renamed, well before I really got a hold > on lambdas as anything more than some confusing bit of magic. Of > course, I started in C, where I was fairly comfortable with the idea > of function pointers; function objects are a pretty simple step up, > abstraction-wise, from that. > > I suppose that one might argue that I *still* just don't really get > lambdas (and I wouldn't argue with that). I can see some advantages > to small inline functions, though I suspect that a more-explicit > currying mechanism (such as the proposed partial() higher-order > function) could easily replace such uses. I'm sorry to say, though, > that the supposed advantages of anonymity come across as little more > than handwaving assertions to me, no matter how sincerely they're > intended. (I've just started to read through SICP, to pick up some > lisp/scheme, in hopes of understanding the appeal a bit better, so > maybe there's hope for me yet. ;) ) > > Jeff Shannon > Technician/Programmer > Credit International > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Fri Feb 4 01:33:30 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 4 01:33:33 2005 Subject: [Tutor] Better structure? In-Reply-To: <024e01c50a1f$4a4ab0c0$68b78851@xp> References: <42003772.4010808@ccvcorp.com> <002501c508ce$294e4e10$3b5428cf@JSLAPTOP> <016a01c50904$81e75db0$68b78851@xp> <001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net> <4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com> <4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> Message-ID: Alan said - > Its bad practice to delete a member in the collection being iterated > but Python copes OK if you just change the current item. Yeah, that's very bad. Makes for all sorts of subtle errors. I usually do the iteration as a for i in range(len(someList) type thing, and collect the indexes - like so j=[1, 2,3,4, 5,6,7,8] delIndexes=[] for index in range(len(j)): if not j[index] % 2: delIndexes.append(index) delIndexes.reverse() for item in delIndexes: del(j[item]) print j [1, 3, 5, 7] Although, (and this will be rough) a list comprehension would be probably do the same thing j=[1, 2,3,4, 5,6,7,8] q = [if not item % 2 for item in j] I really think I've got that 'if not item % 2' wrong, as I can't test it, but I'd be hoping for print q [1, 3, 5, 7] -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From budr at netride.net Fri Feb 4 01:43:36 2005 From: budr at netride.net (Bud Rogers) Date: Fri Feb 4 01:44:02 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <031901c50a49$e5142440$68b78851@xp> References: <031901c50a49$e5142440$68b78851@xp> Message-ID: <200502031843.37545.budr@netride.net> On Thursday 03 February 2005 17:41, Alan Gauld wrote: > In fact the best style of all is neither of the two I showed, > its actually this - which early everyone hates when they see it! > > inf f(x) > ? ? { > ? ? bah() > ? ? } Ugh. Alan, I won't even try to dispute the study. But if I have to write code like that, I'll just take up gardening instead. :} -- Bud Rogers KD5SZ From keridee at jayco.net Fri Feb 4 02:26:05 2005 From: keridee at jayco.net (Jacob S.) Date: Fri Feb 4 02:25:51 2005 Subject: [Tutor] Better structure? References: <42003772.4010808@ccvcorp.com><002501c508ce$294e4e10$3b5428cf@JSLAPTOP><016a01c50904$81e75db0$68b78851@xp><001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com><4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> Message-ID: <00d801c50a58$83f68c20$3d5328cf@JSLAPTOP> > Although, (and this will be rough) a list comprehension would be > probably do the same thing > j=[1, 2,3,4, 5,6,7,8] > > q = [if not item % 2 for item in j] > > I really think I've got that 'if not item % 2' wrong, as I can't test > it, but I'd be hoping for > print q > [1, 3, 5, 7] Backwards. ;-) q = [item for item in j if not item % 2 == 0] A word of warning. You want odd numbers, so even if the syntax was correct for your list comprehension, you would have gotten even numbers -- item % 2 would register False if item %2 == 0, then not False would be True so you would get all of the items that were even. Does that make sense? You could also do q = [item for item in j if item % 2] Which says if item % 2 is True (not equal to False, 0) then append item to q. Okay, so that's not exactly what it says HTH, Jacob From jeff at ccvcorp.com Fri Feb 4 03:22:01 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 03:21:18 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <56c97b3bed48eeaf1d13a6e97311cd9a@yahoo.fr> References: <02b101c50a3d$a5574550$68b78851@xp> <4202B6A5.3030805@ccvcorp.com> <56c97b3bed48eeaf1d13a6e97311cd9a@yahoo.fr> Message-ID: <4202DC49.3050105@ccvcorp.com> Max Noel wrote: > On Feb 3, 2005, at 23:41, Jeff Shannon wrote: > >> (But then, at my job I'm stuck using a horrible Frankenstein's monster >> of a proprietary language on a daily basis, so I can't help but >> believe that there's plenty more awful languages around that didn't >> happen to be "rescued" from oblivion by an accident of history...) > > Yeah. Sometimes I read a little bit of Wikipedia's "Esoteric > Programming Languages" page, and some of them just leave me in awe. > Brainfuck (and its variant Ook!) and INTERCAL ("GOTO is considered > harmful, so we removed it -- INTERCAL uses COME FROM instead") are > already quite impressive, but the very idea of Befunge makes my brain > want to explode. Especially that extension to the language that allows > one to write N-dimensional programs. :D The difference here is that those are languages that were *intended* to be brain-melting. The language I'm talking about (Pick Proc, aka UHL) was intended to do real work with -- though at times I think it was designed by a brain-damaged lemur that was huffing paint fumes. For example, every line (except flow-control statements i.e. 'if' and 'go' (there's a few other exceptions as well, but anyhow...)) must begin with a single character that denotes what the line does - 'c' for comment, 'o' for output (print to terminal), 'h' to build a command, 'p' to execute that command... empty lines are forbidden. Note also that the position *after* the final newline character is considered a line, and therefore a file cannot end with a newline. Especially when combined with several of the utilities that it's commonly used to script for, it begins to approach Perl in indecipherability, without even having the excuse of being largely non-alpha characters. I'd consider writing a Python extension that would interact with the system such that I wouldn't need to use this awful little scripting language, but that would require more effort and thought than I'm willing to invest in learning the details of this system. Jeff Shannon Technician/Programmer Credit International From flaxeater at yahoo.com Fri Feb 4 03:54:18 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 03:54:21 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050204025418.49854.qmail@web54307.mail.yahoo.com> How about a concrete example where lambda is more elegant than a named block of code aList=['a','bb','ccc','dddd','ee'] bList=aList[:] #deep copy assert not bList is aList def sortByLength(item1,item2): return cmp(len(item1),len(item2)) bList.sort(sortByLength) assert bList==['a', 'bb', 'ee', 'ccc', 'dddd'] aList.sort(lambda x,y:cmp(len(x),len(y))) assert aList==['a', 'bb', 'ee', 'ccc', 'dddd'] Now this is a concrete example of how lambda simplifies code, at least for me because it does not clutter my mental name space. Also it is much shorter. However it should be said that this is very much a question of taste. However I must say that lambda's are very useful even necessary for using Tkinter. Here's something else, while not exactly the same but an illustration. aFuncList=[] def x(): print "one" aFuncList.append(x) def x(): print "two" aFuncList.append(x) def x(): print "three" aFuncList.append(x) for item in aFuncList: item() In summary there has been a great deal of argument about lambda's, even on this mostly sanguine mailing list. I feel that it's one of those strange things about python true. Guido purposely made it very limited because it could get hairy very fast with more powerful lambda's, the functional people would make code that would break newcomers heads. God knows I had a hard enough time with them at first. __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From flaxeater at yahoo.com Fri Feb 4 07:39:43 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 07:39:49 2005 Subject: [Tutor] This Deletes All my Files Message-ID: <20050204063943.83241.qmail@web54308.mail.yahoo.com> I've tried this and I cannot figure out why this does not work. I figure this has something to do with order of operations. I figured someone would know exactly why it doesn't work. Wouldn't this start inside parens then from left to right? open(item,'w').write(open(item,'r').read().replace(' ','')) I tried this on the shell just trying to do some quick text replacement because I could figure out how to get awk to do it, and I didn't want to spend 5 hours RTFM. I got it to work by breaking it up to several statements, but I would like to know. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From pierre.barbier at cirad.fr Fri Feb 4 09:07:26 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri Feb 4 09:05:22 2005 Subject: [Tutor] This Deletes All my Files In-Reply-To: <20050204063943.83241.qmail@web54308.mail.yahoo.com> References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <42032D3E.5040904@cirad.fr> Ok, so in Python, arguments are evaluated first, left to right ! The outer-most function used in your sample is : file.write(self, filename, mode) So the first argument evaluated is "self" ... and in your case "self" is "open(item, 'w')" so the first thing your line does is opening for writing the file named by "item" and as "w" empty the file ... you can read it afterward, it will be empty ! Pierre PS: general in programs: do NEVER rely on arguments evaluation order, unless you have no other choices and you are damn sure of what you're doing. In any case, do NEVER do that if you're no expert in the programming language used. Chad Crabtree a ?crit : > I've tried this and I cannot figure out why this does not work. I > figure this has something to do with order of operations. I figured > someone would know exactly why it doesn't work. Wouldn't this start > inside parens then from left to right? > > open(item,'w').write(open(item,'r').read().replace(' ','')) > > I tried this on the shell just trying to do some quick text > replacement > because I could figure out how to get awk to do it, and I didn't want > to > spend 5 hours RTFM. I got it to work by breaking it up to several > statements, but I would like to know. > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From shaleh at speakeasy.net Fri Feb 4 09:13:29 2005 From: shaleh at speakeasy.net (Sean Perry) Date: Fri Feb 4 09:14:06 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <030401c50a46$c7d41280$68b78851@xp> References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <4202A13F.70109@speakeasy.net> <030401c50a46$c7d41280$68b78851@xp> Message-ID: <42032EA9.1000600@speakeasy.net> Alan Gauld wrote: > > Sean, what book/tutor are you using for Haskell? > I learned it from "The Haskell School of Expression" which > was OK but very graphics focused, I'd be interested in > recommended second source on Haskell. > as with Max I am reading Haskell: Craft of Functional Programming. I am about half way through it (have not got to Monads yet which are the mind benders). So far I really like it. Thought provoking examples and exercises. However there are no answers to the exercises. Which for a relative newbie to functional programming would have been nice. From maxnoel_fr at yahoo.fr Fri Feb 4 09:15:04 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 09:15:10 2005 Subject: [Tutor] This Deletes All my Files In-Reply-To: <20050204063943.83241.qmail@web54308.mail.yahoo.com> References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <66f660b9e70d3a96f9e0fc4dc7fae398@yahoo.fr> On Feb 4, 2005, at 06:39, Chad Crabtree wrote: > I've tried this and I cannot figure out why this does not work. I > figure this has something to do with order of operations. I figured > someone would know exactly why it doesn't work. Wouldn't this start > inside parens then from left to right? > > open(item,'w').write(open(item,'r').read().replace(' ','')) > > I tried this on the shell just trying to do some quick text > replacement > because I could figure out how to get awk to do it, and I didn't want > to > spend 5 hours RTFM. I got it to work by breaking it up to several > statements, but I would like to know. It's quite easy: evaluation starts from left to right. The program opens item for writing (thus deleting it), creating a file object, then executes its write method on the argument in the parens. However, since at that point item is now empty, there is nothing to read from. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From project5 at redrival.net Fri Feb 4 09:51:57 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 4 09:52:59 2005 Subject: [Tutor] Re: This Deletes All my Files References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: Chad Crabtree yahoo.com> writes: > I've tried this and I cannot figure out why this does not work. I > figure this has something to do with order of operations. I figured > someone would know exactly why it doesn't work. Wouldn't this start > inside parens then from left to right? > > open(item,'w').write(open(item,'r').read().replace(' ','')) Well, what your code says is this: 1. open item for writing and return a file object 2. call on that file object the write method (at this point its contents are wiped out) 3. open that same file for reading (but it's empty now) 4. read everything from it (nothing) 5. write nothing back to the file. You can test it by implementing a dummy open method and a dummy file class which log what happens to them: >>> s = "d:/tests/test.txt" >>> class dummyfile(object): ... def open(self, *args): ... print "dummyfile.open:", args ... def write(self, *args): ... print "dummyfile.write:", args ... def read(self, *args): ... print "dummyfile.read:", args ... return "" >>> def dummyopen(filename, type): ... print "dummyopen:", filename, type ... d = dummyfile() ... d.open(filename, type) ... return d >>> dummyopen(s, 'w').write(dummyopen(s, 'r').read()) dummyopen: d:/tests/test.txt w dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for writing dummyopen: d:/tests/test.txt r dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading dummyfile.read: () dummyfile.write: ('',) > spend 5 hours RTFM. I got it to work by breaking it up to several > statements, but I would like to know. And that's the way you *should* write it - code like this doesn't deserve to work anyway :). Yours, Andrei From alan.gauld at freenet.co.uk Fri Feb 4 09:58:41 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 09:57:41 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <24692.1107472232@www13.gmx.net> Message-ID: <034301c50a97$b9b7b110$68b78851@xp> > > We'll just have to have to disagree about awk. I starting learning Perl > > to avoid learning awk :-) > > But awk is smaller and simpler than perl. So it should be faster > (esp. at startup) for small and simple tasks. > As usual: Right tool for right task. awk starts faster but perl is more efficient because it compiles the code prior to execution. So for any long files or big programs Perl is significantly faster than awk. But awk is just so elegant and quick to write that I use it for everything except huge files. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:05:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:04:19 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp> <93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com><4202A13F.70109@speakeasy.net> <030401c50a46$c7d41280$68b78851@xp> Message-ID: <035401c50a98$9e54ee00$68b78851@xp> > > Sean, what book/tutor are you using for Haskell? > > I'm not Sean, Oops, sorry, I picked the name from the post I was replying to, apologies! > but I'm using Simon Thompson's "Haskell: The Craft of > Functional Programming", which I find quite good. However, it's a bit > odd, in that it almost reads like a mathematics book, which is > something you may or may not like. FP generally is math oriented, all the Haskell books I've seen are the same. In fact the reason I chose mine was because it seemed the least math oriented, but in practice, because I'm not much into graphics, I spent a lot of time trying to think how to apply the principles elsewhere... I'll have a look for your one. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:09:11 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:08:15 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <031901c50a49$e5142440$68b78851@xp> <6b97374ce906150985bb042f036797ba@yahoo.fr> Message-ID: <035b01c50a99$31229070$68b78851@xp> > > The reasons for the K&R style of brace winning is to do > > with the way the brain process structure and despite > > the subjects stated preference for the 'Pascal' style > > they still had lower perception scores. > > Little nit-picking here: > > if(foo) > { > bar(); > } > > Is not K&R style, but Allman style. K&R style (also known as One True > Brace Style or 1TBS) is this: Correct. The style you show (which I called Pascal style) is the one that doesn't work. K&R style > if(foo) { > bar; > } Is the one that won the shootout. With the outsider(which I dont know a name for!) beating both... if (foo) { bar; } Which is the one that Python uses... Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:28:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:27:22 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr> <56abcbca5acfdc78d0b13c480c1af850@yahoo.fr> <021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr> <42029ECA.2070305@ccvcorp.com><02ff01c50a46$7d75d570$68b78851@xp> <4202BC9F.8080800@ccvcorp.com> Message-ID: <036001c50a9b$e0a33c50$68b78851@xp> > > I disagree Jeff. It does need lambdas to do FP properly, and > > Well, we'll have to continue to disagree on that. ;) Personally, I > can't help but think that 'lambda' is descriptive only to people > who've experienced it elsewhere, and that that does *not* include the > majority of the programming community, but I could be mistaken. :) I would agree, in the same way that complex numbers only make sense to those who've used them. But lambda calculus is the foundation of all programming and all formally trained programmers *should* have had a grounding in Lambda calculus. Unfortunately the nature of the industry is such that many programmers have no theoretical understanding of programming, they just know some languages and get on with it. That's OK, and most programmers can quite happily ignore lambdas - and do! [The analogy is that you don't need to understand electron mechanics to be an electrician, but a electronic component designer probably should!] But lambda is just as much a valid mathematical term as "function" or "set" or "complex number", its not a *construct* from another language, its a mathematical concept with whole books written about it. > Well, given that in Python a function is just a callable code block > that's bound to a name... ;) Personally, I fail to see why having an > anonymous function is such a huge conceptual advantage, Because often you just want to pass in a bit of code that doesn't have a very meaningful function, typically as a parameter to a control structure. In fact, thinking about it, I'd guess the most common case for anonymous functions is when defining new control structures. Now you can give arbitrary names "codeBlock" or similar def codeBlock(): blah blah blah repeat(codeBlock,test) But its more appropriate to the task to do: repeat( blah blah blah, test) It keeps the code block at the execution point. > Here, ISTM that you're emphasizing the in-line nature of lambdas as > being their key usage point... And personally, I prefer to have a > glossary of terms rather than having to decipher jargon by context. ;) But a glossary of terms is only useful if it means something. Its especially useful for things that hang around and get reused, but for something you use once and throw away labelling it is a lot of work! > collections, and effectively renamed, well before I really got a hold > on lambdas as anything more than some confusing bit of magic. Of > course, I started in C, where I was fairly comfortable with the idea > of function pointers; function objects are a pretty simple step up, > abstraction-wise, from that. I started wth C then moved to Lisp. When I saw Lambdas in Lisp C function pointers suddenly took on a new lease of life and that was what started me reading up on lambda calculus. Like most programmers I don't use lambda a lot, but its really nice to have it there for the few occasions I want it... > intended. (I've just started to read through SICP, to pick up some > lisp/scheme, in hopes of understanding the appeal a bit better, so > maybe there's hope for me yet. ;) ) Maybe. It'll be interesting to hear what you make of it. Keep us posted. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:37:03 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:36:45 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><56abcbca5acfdc78d0b13c480c1af850@yahoo.fr><021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com> <02ff01c50a46$7d75d570$68b78851@xp><4202BC9F.8080800@ccvcorp.com> Message-ID: <037301c50a9d$15b40630$68b78851@xp> > I'm with Jeff on this one - I've yet to see the light regarding > lambda's. I understand they're used through-out Tkinter GUI stuff They often are in practice although they are rarely (never) necessary(*). But they are a convenient way of defining a one liner function without the overhead of certing lots of defined functions. (*)Except that all function definitions are really lambdas, they just don't use the keyword lambda anywhere.... > anyone put up an example of why a lambda is better? I would like to > 'get' the concepts. I gave a pseudo coe example in my reply to Jeff. Also in my Functional Programming page there are some examples. > Is this one of those conceptual things like OOP? Yes, but its a bit more fundamental than OOP Its about how programming languages are constructed and function. Its like the theory behind how elictricity flows in a circuit - you can change a fuse without knowing that stuff but its more important if you have to design the fuse! Lambdas really start to work when you start building new language constructs and the like. > Or is it a subtlety that a Masters in COSC is necessary to appreciate? Certainly a Masters in CS should teach you about Lambdas but you don't need that to appreciate them. They really aren't that hard, its just the fancy Greek name puts folks off I suspect :-) From alan.gauld at freenet.co.uk Fri Feb 4 10:39:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:38:40 2005 Subject: [Tutor] Better structure? References: <42003772.4010808@ccvcorp.com><002501c508ce$294e4e10$3b5428cf@JSLAPTOP><016a01c50904$81e75db0$68b78851@xp><001301c5099a$df6c7dd0$145428cf@JSLAPTOP> <4201A45A.2060205@tds.net><4201A727.1040206@gmail.com> <4201A854.8000103@gmail.com><4201ADE6.1040908@lug-delhi.org> <024e01c50a1f$4a4ab0c0$68b78851@xp> Message-ID: <037801c50a9d$7333b940$68b78851@xp> > Although, (and this will be rough) a list comprehension would be > probably do the same thing > j=[1, 2,3,4, 5,6,7,8] > > q = [if not item % 2 for item in j] I think you mean: q = [ item for item in j if item % 2] item % 2 will return zero = false on even numbers, so your test is true for odd numbers. No need for 'not'. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 10:42:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 10:41:35 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net> Message-ID: <037d01c50a9d$e01d0a70$68b78851@xp> On Thursday 03 February 2005 17:41, Alan Gauld wrote: >> In fact the best style of all is neither of the two I showed, >> its actually this - which early everyone hates when they see it! >> >> inf f(x) >> { >> bah() >> } > >Ugh. Alan, I won't even try to dispute the study. But if I have to >write code like that, I'll just take up gardening instead. :} Look at it conceptually: XXXXXXXXXXXX XXXXX XXXXX XXXXX Thats Python! Since you are on this list I suspect you do write "code like that" Its just Guido removed the now extraneous {}... :-) Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 11:11:50 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 11:12:46 2005 Subject: [Tutor] This Deletes All my Files References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> Message-ID: <038801c50aa1$f233a350$68b78851@xp> > I've tried this and I cannot figure out why this does not work. So what happens? And how are you closing the file? > open(item,'w').write(open(item,'r').read().replace(' ','')) I can't see the obvious flaw, but using anonymous files(*) is not a good idea IMHO. (*)Unlike anonymous functions ;-) Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 11:14:37 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 11:13:29 2005 Subject: [Tutor] This Deletes All my Files References: <20050204063943.83241.qmail@web54308.mail.yahoo.com> <42032D3E.5040904@cirad.fr> Message-ID: <039a01c50aa2$55715e80$68b78851@xp> > So the first argument evaluated is "self" ... and in your case "self" is > "open(item, 'w')" so the first thing your line does is opening for > writing the file named by "item" and as "w" empty the file ... you can > read it afterward, it will be empty ! Ah! well spotted Pierre, I hadn't noticed that both input and output files were the same file! Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 11:20:38 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 11:19:53 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <86626245450c1bfcf3190400baffe178@yahoo.fr><9bb26ab5f9c3d8166f27d39464b9c750@yahoo.fr><56abcbca5acfdc78d0b13c480c1af850@yahoo.fr><021301c509d5$89daa960$68b78851@xp><93fef199885ae5cf5b466c6e0e724ae5@yahoo.fr><42029ECA.2070305@ccvcorp.com><02ff01c50a46$7d75d570$68b78851@xp><4202BC9F.8080800@ccvcorp.com> <037301c50a9d$15b40630$68b78851@xp> Message-ID: <03ad01c50aa3$36f41500$68b78851@xp> > and function. Its like the theory behind how elictricity Yikes! Did I really manage to type elictricity And I can't blame finger trouble, e and i are miles apart on the keyboard! Blush.... Alan G. From maxnoel_fr at yahoo.fr Fri Feb 4 11:47:08 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Feb 4 11:47:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <035b01c50a99$31229070$68b78851@xp> References: <031901c50a49$e5142440$68b78851@xp> <6b97374ce906150985bb042f036797ba@yahoo.fr> <035b01c50a99$31229070$68b78851@xp> Message-ID: <3f7e4a2ab102617eb48349ae27a6171b@yahoo.fr> On Feb 4, 2005, at 09:09, Alan Gauld wrote: > Correct. The style you show (which I called Pascal style) is > the one that doesn't work. K&R style > >> if(foo) { >> bar; >> } > > > Is the one that won the shootout. > > With the outsider(which I dont know a name for!) beating both... > > if (foo) > { > bar; > } According to the Jargon file, this one is called Whitesmiths style. I tend to use Allman style myself, but given the code completion, spellchecking, etc. in modern IDEs, I suspect it's become more a question of personal preference than anything else. A bit like if(foo) versus if (foo), and whether or not to use braces for single-line blocks. (the latter issue being why I think The Whitespace Thing is an instance of Best Thing Ever(TM)) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:14:43 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:15:16 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <030b01c50a48$15e2df00$68b78851@xp> References: <030b01c50a48$15e2df00$68b78851@xp> Message-ID: Alan Gauld wrote: >>I also wish Python would take up the C ternary operator >>which is also quite clear and elegant. > > > :-) > You joke I assume? ':?' is clear? Its succinct but also > prone to abuse. I don't think the Python equivalent > > foo = x and y or z > > > is much less elegant than > > foo = x ? y : z You must be joking too... You think that x and y or z is as clear as x ? y : z even though the former is just a hack that was not meant to be used as such, while the latter is a well-documented feature that is designed to do what it does? Ugly as I think it is, I could live with that. But it's worse: x and y or z doesn't even work if y evaluates to False. That alone makes me never want to use the construct: whether the expression evaluates to y or z should depend on the value of x, not the value of y or z. As far as I'm concerned, the lack of a proper ternary if/then/else operator is a wart in the otherwise very clean design of Python. The lack of a switch statement too, but to a much lesser degree. -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:26:17 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:26:40 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <031901c50a49$e5142440$68b78851@xp> References: <031901c50a49$e5142440$68b78851@xp> Message-ID: Alan Gauld wrote: > In fact the best style of all is neither of the two I showed, > its actually this - which early everyone hates when they see it! > > inf f(x) > { > bah() > } Yikes. We use that style at work. At first I found it ugly, but I thought I'd get used to it after a while. Well, 3 years later I still find it ugly and, more importantly, much harder to understand the structure. Do you have a link to these studies? I'm always skeptical about the methodology in those studies, but I'm willing to be proven wrong. -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:31:48 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:32:02 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <037d01c50a9d$e01d0a70$68b78851@xp> References: <031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net> <037d01c50a9d$e01d0a70$68b78851@xp> Message-ID: Alan Gauld wrote: > Look at it conceptually: > > XXXXXXXXXXXX > XXXXX > XXXXX > XXXXX > > Thats Python! Since you are on this list I suspect you do write > "code like that" Its just Guido removed the now extraneous {}... My favorite, Allman style, is also Python if you remove the {} ! BTW, Steve McConnell recommends your favorite too in Code Complete. But he also didn't manage to convince me. -- "Codito ergo sum" Roel Schroeven From melnyk at gmail.com Fri Feb 4 12:38:51 2005 From: melnyk at gmail.com (Scott Melnyk) Date: Fri Feb 4 12:38:54 2005 Subject: [Tutor] variation of Unique items question Message-ID: Hello once more. I am stuck on how best to tie the finding Unique Items in Lists ideas to my file I am stuck at level below: What I have here taken from the unique items thread does not work as I need to separate each grouping to the hg chain it is in (see below for examples) import sys WFILE=open(sys.argv[1], 'w') def get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2): a_list=open(fname, 'r') #print "beginning get_list_dup" items_dict, dup_dict = {}, {} for i in a_list: items_dict[i] = items_dict.get(i, 0) + 1 for k, v in items_dict.iteritems(): if v==threshold: dup_dict[k] = v return dup_dict def print_list_dup_report(fname='Z:/datasets/fooyoo.txt', threshold=2): #print "Beginning report generation" dup_dict = get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2) for k, v in sorted(dup_dict.iteritems()): print WFILE,'%s occurred %s times' %(k, v) if __name__ == '__main__': print_list_dup_report() My issue is that my file is as follows: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST00000339563.1 ENST00000342196.1 ENST00000339563.1 ENST00000344055.1 hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST00000279800.3 ENST00000309556.3 hg17_chainMm5_chr6 range=chr1:155548627-155549517 ENST00000321157.3 ENST00000256324.4 I need a print out that would give the line hg17.... and then any instances of the ENST that occur more than once only for that chain section. Even better it only prints the hg17 line if it is followed by an instance of ENST that occurs more than once I am hoping for something that gives me an out file roughly like: hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST00000339563.1 occurs 2 times hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST00000279800.3 occurs 2 times All help and ideas appreciated, I am trying to get this finished as soon as possible, the output file will be used to go back to my 2 gb file and pull out the rest of the data I need. Thanks, Scott From rschroev_nospam_ml at fastmail.fm Fri Feb 4 12:38:14 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 12:40:16 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <20050204025418.49854.qmail@web54307.mail.yahoo.com> References: <20050204025418.49854.qmail@web54307.mail.yahoo.com> Message-ID: Chad Crabtree wrote: > How about a concrete example where lambda is more elegant than a > named > block of code > > aList=['a','bb','ccc','dddd','ee'] > bList=aList[:] #deep copy > assert not bList is aList > > def sortByLength(item1,item2): > return cmp(len(item1),len(item2)) > > bList.sort(sortByLength) > assert bList==['a', 'bb', 'ee', 'ccc', 'dddd'] > > aList.sort(lambda x,y:cmp(len(x),len(y))) > assert aList==['a', 'bb', 'ee', 'ccc', 'dddd'] > > Now this is a concrete example of how lambda simplifies code, at > least for me because it does not clutter my mental name space. Also > it is much shorter. However it should be said that this is very much > a question of taste. Indeed. In this case, I like the version without lambda. Naming the function serves as documentation, so I don't even need to read an interpret the body of the function to know what it does. Assuming that the name correctly describes the behavior of course, but I need to check that only once. From then on, sort(sortByLength) instantly explains what it does, while sort(lambda x,y: cmp(len(x),len(y)) needs much more parsing. But I agree that there are cases where lambda is more useful and/or clearer. -- "Codito ergo sum" Roel Schroeven From kent37 at tds.net Fri Feb 4 13:22:17 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 13:22:23 2005 Subject: [Tutor] variation of Unique items question In-Reply-To: References: Message-ID: <420368F9.3060705@tds.net> You need to reset your items_dict when you see an hg17 line. Here is one way to do it. I used a class to make it easier to break the problem into functions. Putting the functions in a class makes it easy to share the header and counts. class Grouper: ''' Process a sequence of strings of the form Header Data Data Header ... Look for repeated Data items under a single Header. When found, print the Header and the repeated item. Possible usage: out = open('outfile.txt', 'w') Grouper().process(open('infile.txt'), 'hg17', out) out.close() ''' def reset(self, header='No header'): ''' Reset the current header and counts ''' self.currHeader = header self.counts = {} def process(self, data, headerStart, out): ''' Find duplicates within groups of lines of data ''' self.reset() for line in data: line = line.strip() # get rid of newlines from file input if line.startswith(headerStart): # Found a new header line, show the current group and restart self.showDups(out) self.reset(line) elif line: # Found a data line, count it self.counts[line] = self.counts.get(line, 0) + 1 # Show the last group self.showDups(out) def showDups(self, out): # Get list of items with count > 1 items = [ (k, cnt) for k, cnt in self.counts.items() if cnt > 1 ] # Show the items if items: items.sort() print >> out, self.currHeader for k, cnt in sorted(items): print >> out, '%s occurs %d times' % (k, cnt) print >> out if __name__ == '__main__': import sys data = '''hg17_chainMm5_chr15 range=chr7:148238502-148239073 ENST00000339563.1 ENST00000342196.1 ENST00000339563.1 ENST00000344055.1 hg17_chainMm5_chr13 range=chr5:42927967-42928726 ENST00000279800.3 ENST00000309556.3 ENST00000279800.3 hg17_chainMm5_chr6 range=chr1:155548627-155549517 ENST00000321157.3 ENST00000256324.4'''.split('\n') Grouper().process(data, 'hg17', sys.stdout) Kent Scott Melnyk wrote: > Hello once more. > > I am stuck on how best to tie the finding Unique Items in Lists ideas to my file > > I am stuck at level below: What I have here taken from the unique > items thread does not work as I need to separate each grouping to the > hg chain it is in (see below for examples) > > import sys > WFILE=open(sys.argv[1], 'w') > def get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2): > a_list=open(fname, 'r') > #print "beginning get_list_dup" > items_dict, dup_dict = {}, {} > > for i in a_list: > items_dict[i] = items_dict.get(i, 0) + 1 > > for k, v in items_dict.iteritems(): > if v==threshold: > dup_dict[k] = v > > return dup_dict > > def print_list_dup_report(fname='Z:/datasets/fooyoo.txt', threshold=2): > #print "Beginning report generation" > dup_dict = get_list_dup_dict(fname='Z:/datasets/fooyoo.txt', threshold=2) > for k, v in sorted(dup_dict.iteritems()): > print WFILE,'%s occurred %s times' %(k, v) > > if __name__ == '__main__': > print_list_dup_report() > > > My issue is that my file is as follows: > hg17_chainMm5_chr15 range=chr7:148238502-148239073 > ENST00000339563.1 > ENST00000342196.1 > ENST00000339563.1 > ENST00000344055.1 > > hg17_chainMm5_chr13 range=chr5:42927967-42928726 > ENST00000279800.3 > ENST00000309556.3 > > hg17_chainMm5_chr6 range=chr1:155548627-155549517 > ENST00000321157.3 > ENST00000256324.4 > > I need a print out that would give the line hg17.... and then any > instances of the ENST that occur more than once only for that chain > section. Even better it only prints the hg17 line if it is followed > by an instance of ENST that occurs more than once > > I am hoping for something that gives me an out file roughly like: > > hg17_chainMm5_chr15 range=chr7:148238502-148239073 > ENST00000339563.1 occurs 2 times > > hg17_chainMm5_chr13 range=chr5:42927967-42928726 > ENST00000279800.3 occurs 2 times > > > All help and ideas appreciated, I am trying to get this finished as > soon as possible, the output file will be used to go back to my 2 gb > file and pull out the rest of the data I need. > > Thanks, > Scott > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From h-tamm at ti.com Fri Feb 4 14:18:28 2005 From: h-tamm at ti.com (Tamm, Heiko) Date: Fri Feb 4 14:18:32 2005 Subject: [Tutor] Hex to Str Message-ID: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Hello, I like to know, if it's possible to convert a Hex number into String or other formats? How can it be done? Kind regards Heiko -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050204/1b144def/attachment.htm From pierre.barbier at cirad.fr Fri Feb 4 14:34:32 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri Feb 4 14:32:29 2005 Subject: [Tutor] Hex to Str In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <420379E8.8010804@cirad.fr> Given you have a number in 'a' : hex(a) returns the hexadecimal representation of 'a' as a string ! You can also try : "%x" % a After that, I don't know if there is some builtin to print a number in any base you want ! Pierre Tamm, Heiko a ?crit : > Hello, > > I like to know, if it's possible to convert a Hex number into String or > other formats? > > How can it be done? > > > Kind regards > > Heiko > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Fri Feb 4 14:36:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 14:36:56 2005 Subject: [Tutor] Hex to Str In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <42037A72.2040207@tds.net> Use the hex() function to convert an integer to a hex string representation: >>> hex(54) '0x36' >>> hex(0x54) '0x54' or for more control use %x string formatting: >>> '%x' % 54 '36' >>> '%04X' % 0xab '00AB' etc. Kent Tamm, Heiko wrote: > Hello, > > I like to know, if it's possible to convert a Hex number into String or > other formats? > > How can it be done? > > > Kind regards > > Heiko > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From h-tamm at ti.com Fri Feb 4 14:36:54 2005 From: h-tamm at ti.com (Tamm, Heiko) Date: Fri Feb 4 14:37:17 2005 Subject: [Tutor] Hex to Str - still an open issue Message-ID: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> Thank you, Pierre, But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. E.g.: What is the the binary value of the hex number 1F4. Is there a function available, or how can it be done? Kind regards and a nice weekend Heiko -----Original Message----- From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] Sent: Friday, February 04, 2005 2:35 PM To: Tamm, Heiko Cc: tutor@python.org Subject: Re: [Tutor] Hex to Str Given you have a number in 'a' : hex(a) returns the hexadecimal representation of 'a' as a string ! You can also try : "%x" % a After that, I don't know if there is some builtin to print a number in any base you want ! Pierre Tamm, Heiko a ?crit : > Hello, > > I like to know, if it's possible to convert a Hex number into String > or other formats? > > How can it be done? > > > Kind regards > > Heiko > > > > ---------------------------------------------------------------------- > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From ewald.ertl at hartter.com Fri Feb 4 14:37:37 2005 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Fri Feb 4 14:37:41 2005 Subject: [Tutor] Hex to Str In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <20050204143737.00006e81@sunray1> Hello Heiko, I do not really know what you like to get, but the hex-number's in Python are usedd in a numeric representation. As far as I have seen in the interpreter, this depends on the value: >>> a=0xaaaaabbbbbccccccddddddd >>> type(a) >>> a=0xaabb >>> type(a) If you like to see the number as a hex-String you can use >>> hex(a) '0xaabb' the representation as an octal number >>> oct(a) '0125273' HTH Ewald on Fri, 4 Feb 2005 14:18:28 +0100 "Tamm, Heiko" wrote : --------------------------------------------------------------------------------------------- Tamm, Heiko > Hello, Tamm, Heiko > Tamm, Heiko > I like to know, if it's possible to convert a Hex number into String or Tamm, Heiko > other formats? Tamm, Heiko > Tamm, Heiko > How can it be done? Tamm, Heiko > Tamm, Heiko > Tamm, Heiko > Kind regards Tamm, Heiko > Tamm, Heiko > Heiko ------------------- end ---------------------- From kent37 at tds.net Fri Feb 4 14:50:42 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 14:50:46 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> Message-ID: <42037DB2.8060207@tds.net> You might be interested in these: http://groups-beta.google.com/group/comp.lang.python/msg/c2cb941ea70dcdad http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 Kent Tamm, Heiko wrote: > Thank you, Pierre, > > But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. > > E.g.: > > What is the the binary value of the hex number 1F4. > > Is there a function available, or how can it be done? > > > > Kind regards and a nice weekend > > Heiko > > > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:35 PM > To: Tamm, Heiko > Cc: tutor@python.org > Subject: Re: [Tutor] Hex to Str > > Given you have a number in 'a' : > > hex(a) > > returns the hexadecimal representation of 'a' as a string ! > You can also try : > > "%x" % a > > After that, I don't know if there is some builtin to print a number in any base you want ! > > Pierre > > Tamm, Heiko a ?crit : > >>Hello, >> >>I like to know, if it's possible to convert a Hex number into String >>or other formats? >> >>How can it be done? >> >> >>Kind regards >> >> Heiko >> >> >> >>---------------------------------------------------------------------- >>-- >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From melnyk at gmail.com Fri Feb 4 14:57:00 2005 From: melnyk at gmail.com (Scott Melnyk) Date: Fri Feb 4 14:57:03 2005 Subject: [Tutor] Re: variation of Unique items question Message-ID: Hello. Kent once again you have responded incredibly quickly in a most helpful manor. I sometimes wonder if the old reference to a "Kent-bot" has some truth to it. Thanks again, I will play with it and keep on going. Scott From h-tamm at ti.com Fri Feb 4 15:11:00 2005 From: h-tamm at ti.com (Tamm, Heiko) Date: Fri Feb 4 15:11:08 2005 Subject: [Tutor] Hex to Str - still an open issue Message-ID: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Ok, thank you. Does anybody know how to convert a HEX into a BINARY? Best regards Heiko -----Original Message----- From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] Sent: Friday, February 04, 2005 2:55 PM To: Tamm, Heiko Subject: Re: [Tutor] Hex to Str - still an open issue Oh ! You meant the other way around ? If you have a string with an Hex number in it it's very easy : a = int("F04", 16) you can replace "16" with every base you want :) After that, to get an octal representation : "%o" % a But I don't know for binary representation ... nor for any other base :( That's somthing missing I think ! Pierre Tamm, Heiko a ?crit : > Thank you, Pierre, > > But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. > > E.g.: > > What is the the binary value of the hex number 1F4. > > Is there a function available, or how can it be done? > > > > Kind regards and a nice weekend > > Heiko > > > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:35 PM > To: Tamm, Heiko > Cc: tutor@python.org > Subject: Re: [Tutor] Hex to Str > > Given you have a number in 'a' : > > hex(a) > > returns the hexadecimal representation of 'a' as a string ! > You can also try : > > "%x" % a > > After that, I don't know if there is some builtin to print a number in any base you want ! > > Pierre > > Tamm, Heiko a ?crit : > >>Hello, >> >>I like to know, if it's possible to convert a Hex number into String >>or other formats? >> >>How can it be done? >> >> >>Kind regards >> >> Heiko >> >> >> >>---------------------------------------------------------------------- >>-- >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et > Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de > la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From jsmith at medplus.com Fri Feb 4 15:11:35 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 15:11:44 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: The problem with if/elif is that it doesn't express what is actually gong on. What you are try to do is "execute a block of code based on the value of a single statement." if/elif doesn't do that and thereby introduces the possibility of errors. switch on-this: case 'a': do something case 'b': do something else case 'c': do yet something else Is much clearer and more maintatinable than if on-this == 'a': do something elif on-this == 'b': do something else elif on-this == 'c': do yet something else Note that the logic intended is that "on-this." So why force the programmer to rewrite it N times and thereby introduce the possibility of N-1 typographical errors...particularly if the "on-this" is sufficiently complex. Note that I've left out break. I'm not convinced that fall-through is an important feature in switch and is usually the culpit in the cases of abuse. Of course, abuse has nothing to do with it. Someone somewhere will abuse any syntax you give them. Just because it *can* be abused doesn't mean it doesn't have value when used properly. This is also true for the ternary operator. The desired logic is to assign the value of a variable based on the value of some other variable. The assignment is the primary action and therefore should be the primary feature in the statement. Using if/else makes the decision point the primary action and leads to people stuffing other things in the clauses which don't belong there. IMHO, if/elif/else statements are far more abused than either switch or ternary but I certainly wouldn't argue they should be removed from the language. I also like Perl's unless statement but really prefer VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of expression. Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 6:29 PM To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > Perl and Python both resist the introduction of a switch statement > which I (and many others) feel is the most elegant way to express > what it does. Interesting. What do you feel is the problem with elif? Its not even much more typing and allows for much more expressive test conditions. Switch is really only useful for a single subset of tests. And of course switch statements are notorious bug factories and maintenance nightmares - the reason why OOP tries to eliminate them wherever possible. > I also wish Python would take up the C ternary operator > which is also quite clear and elegant. :-) You joke I assume? ':?' is clear? Its succinct but also prone to abuse. I don't think the Python equivalent foo = x and y or z is much less elegant than foo = x ? y : z > ... To paraphrase the famous quote: There are no good programming languages, just some that aren't as bad in some situations. Absolutely true. I still use assembler occasionally, and I even like bits of COBOL (although not much, its my least favourite language!). And probably my favourite language of all is Logo even though I've never used it for any serious projects. Alan G. From jsmith at medplus.com Fri Feb 4 15:17:46 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 15:17:54 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Disagree to disagree again. I certainly don't think Perl is less capable than awk. And awk is only easier to learn because there's less to it. If someone only wanted to use Perl for exactly what awk does I suspect they would find Perl easier. And awk's terseness is part of what I don't like about it. Unwrapping those statement's and puzzling out what they do can be hellish. Of course, I do understand that if you use it every day, you get use to it like any other language...then again, that was the whole theory behinf APL :-) For what it's worth, I'm a big fan of LISP and Prolog but can't find any reason to really use them any more. And for whoever complained about the proprietary language they have to use daily, I suggest you take a look at ADA. It was intended to be self documenting and was designed by committee. They started with Pascal and decided it was too terse :-) PROCEDURE myfun Became PROCEDURE myfun BODY IS (or something similar, it's been years...err, decades) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Thursday, February 03, 2005 6:31 PM To: Smith, Jeff; Nicholas.Montpetit@deluxe.com Cc: tutor@python.org; tutor-bounces@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > We'll just have to have to disagree about awk. > I starting learning Perl to avoid learning awk :-) Really? Why for? awk is far easier to learn than Perl - and far less generally capable! - but it makes Perl seem positively verbose! Alan G. From kent37 at tds.net Fri Feb 4 15:58:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 15:58:22 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <42038D8C.9020503@tds.net> Please give us an example of what you would like to do since we don't seem to understand. Imagine there is a function that does exactly what you want and show how you would use it and what results you would get. Repeating the same question is not likely to get a better answer, just more guesses. Kent Tamm, Heiko wrote: > > > Ok, thank you. > > > Does anybody know how to convert a HEX into a BINARY? > > > Best regards > > > Heiko > > > > > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:55 PM > To: Tamm, Heiko > Subject: Re: [Tutor] Hex to Str - still an open issue > > Oh ! You meant the other way around ? > > If you have a string with an Hex number in it it's very easy : > > a = int("F04", 16) > > you can replace "16" with every base you want :) > > After that, to get an octal representation : > > "%o" % a > > But I don't know for binary representation ... nor for any other base :( That's somthing missing I think ! > > Pierre > > Tamm, Heiko a ?crit : > >>Thank you, Pierre, >> >>But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. >> >>E.g.: >> >>What is the the binary value of the hex number 1F4. >> >>Is there a function available, or how can it be done? >> >> >> >>Kind regards and a nice weekend >> >> Heiko >> >> >> >>-----Original Message----- >>From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] >>Sent: Friday, February 04, 2005 2:35 PM >>To: Tamm, Heiko >>Cc: tutor@python.org >>Subject: Re: [Tutor] Hex to Str >> >>Given you have a number in 'a' : >> >>hex(a) >> >>returns the hexadecimal representation of 'a' as a string ! >>You can also try : >> >>"%x" % a >> >>After that, I don't know if there is some builtin to print a number in any base you want ! >> >>Pierre >> >>Tamm, Heiko a ?crit : >> >> >>>Hello, >>> >>>I like to know, if it's possible to convert a Hex number into String >>>or other formats? >>> >>>How can it be done? >>> >>> >>>Kind regards >>> >>> Heiko >>> >>> >>> >>>---------------------------------------------------------------------- >>>-- >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >> >>-- >>Pierre Barbier de Reuille >> >>INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et >>Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de >>la Lironde >>34398 MONTPELLIER CEDEX 5, France >> >>tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 >> > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Feb 4 16:02:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 4 16:02:27 2005 Subject: [Tutor] Re: variation of Unique items question In-Reply-To: References: Message-ID: <42038E81.4020906@tds.net> I will give some credit to you for asking a clear question. You included - a clear description of what you want to do - sample data - desired results - code that attempts to solve the problem When all of these are present I am much more likely to respond. The first three elements especially make a big difference. Kent Scott Melnyk wrote: > Hello. > > Kent once again you have responded incredibly quickly in a most > helpful manor. I sometimes wonder if the old reference to a > "Kent-bot" has some truth to it. > > Thanks again, I will play with it and keep on going. > > Scott > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Fri Feb 4 17:46:23 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 4 17:46:27 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <797fe3d4050204084621c71f06@mail.gmail.com> Tamm, Try searching before you get snippy on a group where people are helping you for free. This question gets asked a lot, and the answer can be found all over the place. A particularly comprehensive thread discussing the issue can be found at http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/bdd85f1d1298a191 . Peace Bill Mill bill.mill at gmail.com On Fri, 4 Feb 2005 15:11:00 +0100, Tamm, Heiko wrote: > > > Ok, thank you. > > Does anybody know how to convert a HEX into a BINARY? > > Best regards > > > Heiko > > -----Original Message----- > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > Sent: Friday, February 04, 2005 2:55 PM > To: Tamm, Heiko > Subject: Re: [Tutor] Hex to Str - still an open issue > > Oh ! You meant the other way around ? > > If you have a string with an Hex number in it it's very easy : > > a = int("F04", 16) > > you can replace "16" with every base you want :) > > After that, to get an octal representation : > > "%o" % a > > But I don't know for binary representation ... nor for any other base :( That's somthing missing I think ! > > Pierre > > Tamm, Heiko a ?crit : > > Thank you, Pierre, > > > > But I'm looking for a solution to convert a Hex number into binary, decimal, interger numbers. > > > > E.g.: > > > > What is the the binary value of the hex number 1F4. > > > > Is there a function available, or how can it be done? > > > > > > > > Kind regards and a nice weekend > > > > Heiko > > > > > > > > -----Original Message----- > > From: Pierre Barbier de Reuille [mailto:pierre.barbier@cirad.fr] > > Sent: Friday, February 04, 2005 2:35 PM > > To: Tamm, Heiko > > Cc: tutor@python.org > > Subject: Re: [Tutor] Hex to Str > > > > Given you have a number in 'a' : > > > > hex(a) > > > > returns the hexadecimal representation of 'a' as a string ! > > You can also try : > > > > "%x" % a > > > > After that, I don't know if there is some builtin to print a number in any base you want ! > > > > Pierre > > > > Tamm, Heiko a ?crit : > > > >>Hello, > >> > >>I like to know, if it's possible to convert a Hex number into String > >>or other formats? > >> > >>How can it be done? > >> > >> > >>Kind regards > >> > >> Heiko > >> > >> > >> > >>---------------------------------------------------------------------- > >>-- > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > > Pierre Barbier de Reuille > > > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et > > Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de > > la Lironde > > 34398 MONTPELLIER CEDEX 5, France > > > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > > > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Feb 4 19:13:31 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:13:24 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <03b901c50ae5$3c94cb20$68b78851@xp> > What you are try to do is "execute a block of code based on the value of > a single statement." if/elif doesn't do that and thereby introduces the > possibility of errors. In that case the best solution is a dictionary jump table. That is more maintainable than either and much faster too. And its also shorter to write. [Especially with lambdas :-)] > Note that the logic intended is that "on-this." So why force the > programmer to rewrite it N times and thereby introduce the possibility > of N-1 typographical errors... Thats a fair point although the dictionary solution avoids that. OTOH such switches tend to proliferate thropugh code and become a big source of maintenance headaches in their own right - multiple update syndrome across multiple files potentially. > Note that I've left out break. I'm not convinced that > fall-through is an important feature in switch and is > usually the culpit in the cases of abuse. The problem is its so hard to tell when fall though is happening intentionally or by accident because someone forgot a break sytatement. But when it comes to abuuse the fall through mechanism is one of the worst offenders in C, its just too tempting to be "clever" with it. > This is also true for the ternary operator. The desired logic is to > assign the value of a variable based on the value of some other > variable. But its not its based on the value of an *expression*. If the test could be limited to a single valiable value it might be justified but its an arbitrary expression. That makes it a conditional statement, which is most clearly represented by an if/else... Well I think so :-) > I also like Perl's unless statement but really prefer > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for > clarity of expression. I won't argue on either point, Python's minimalist approach - there's only one way to do it - means a paucity of looping constructs - something I point out in my tutorial. But I can live with it for the other niceties it brings. Alan G. From flaxeater at yahoo.com Fri Feb 4 19:22:14 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 19:22:19 2005 Subject: [Tutor] Re: This Deletes All my Files Message-ID: <20050204182214.28143.qmail@web54310.mail.yahoo.com> Thank you all for answering my question. I thought it would be some misunderstanding on my part. The example Andrei made was very telling. Andrei wrote: >>>>s = "d:/tests/test.txt" >>>>class dummyfile(object): >>>> >>>> >... def open(self, *args): >... print "dummyfile.open:", args >... def write(self, *args): >... print "dummyfile.write:", args >... def read(self, *args): >... print "dummyfile.read:", args >... return "" > > >>>>def dummyopen(filename, type): >>>> >>>> >... print "dummyopen:", filename, type >... d = dummyfile() >... d.open(filename, type) >... return d > > > >>>>dummyopen(s, 'w').write(dummyopen(s, 'r').read()) >>>> >>>> >dummyopen: d:/tests/test.txt w >dummyfile.open: ('d:/tests/test.txt', 'w') <--- first open for writing >dummyopen: d:/tests/test.txt r >dummyfile.open: ('d:/tests/test.txt', 'r') <--- then for reading >dummyfile.read: () >dummyfile.write: ('',) > > > >>spend 5 hours RTFM. I got it to work by breaking it up to several >>statements, but I would like to know. >> >> > >And that's the way you *should* write it - code like this doesn't deserve to >work anyway :). > >Yours, > >Andrei > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From alan.gauld at freenet.co.uk Fri Feb 4 19:23:09 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:25:13 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <030b01c50a48$15e2df00$68b78851@xp> Message-ID: <03e001c50ae6$94dd15c0$68b78851@xp> > > foo = x and y or z > > > > is much less elegant than > > > > foo = x ? y : z > > You must be joking too... You think that > > x and y or z > > is as clear as > > x ? y : z I think its clearer! It says that the first two things happen or else the last thing. Plain English. '?:' means absolutely nothing without somebody to explain it. > Ugly as I think it is, I could live with that. But it's worse: > > x and y or z > > doesn't even work if y evaluates to False. Sure I wasn't recommending that and/or is a good idea I just meant that ugly as it was it was clearer than the meaningless ?: > As far as I'm concerned, the lack of a proper ternary if/then/else > operator is a wart in the otherwise very clean design of Python. The > lack of a switch statement too, but to a much lesser degree. Interesting, obviously a lot of support for both, yet they are features I try to avoid in C(*) and never miss in Python. If given the choice I'd much rather have decent lambdas or even a repeat/until loop! (*)And most software houses I've worked with have ternary operators on their "do not use" list along with switch fall-throughs. BTW I do confess that if switch exists I will use it where I can't use OOP or a dictionary to avoid it - like in vanilla C...! Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:29:57 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:29:44 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <031901c50a49$e5142440$68b78851@xp> Message-ID: <03e501c50ae7$882e0e50$68b78851@xp> > Do you have a link to these studies? I'm always skeptical about the > methodology in those studies, but I'm willing to be proven wrong. Check "Code Complete" by Steve McConnel, he gives the explanation and also several references. One that I found from a quick glance is "Hansen & Yim, 1987". Also a bibliography(!) on the subject of code style is cited: "Edward & Oman in Sigplan Notices Feb 1990". McConnell has a new version of his book out it may have more recent references too, I only have the 1993 edition at hand. Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:32:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:32:23 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net><037d01c50a9d$e01d0a70$68b78851@xp> Message-ID: <03ea01c50ae7$e2ffb860$68b78851@xp> > > XXXXXXXXXXXX > > XXXXX > > XXXXX > > XXXXX > > > > Thats Python! Since you are on this list I suspect you do write > > "code like that" Its just Guido removed the now extraneous {}... > > My favorite, Allman style, is also Python if you remove the {} ! Yep but the braces in Allman completely wreck the block structure XXXXXXXXXXXXXXXXX XXX XXXXXX XXX > BTW, Steve McConnell recommends your favorite too in Code Complete. But > he also didn't manage to convince me. Thats where I first found it, I looked up a couple of references and the message was consistent, so I changed my style. (And my emacs settings :-) Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:37:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:37:33 2005 Subject: [Tutor] Hex to Str References: <812D33B03107804389D6F4247B69EFAC3A2927@dfre2k03.itg.ti.com> Message-ID: <03fe01c50ae8$9f5d4ef0$68b78851@xp> > I like to know, if it's possible to convert a Hex number into > String or other formats? Use the string format operator: >>> print "%X" % 0xB5 B5 >>> print "%X" % 181 B5 Lowercase '%x' uses lowercase letters on output... Or use the int() function with a base argument to go the other way: >>> print int('0xB5',16) 181 string to integer - which is of course stored in binary format in the computer! Alan G. From alan.gauld at freenet.co.uk Fri Feb 4 19:43:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:43:15 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> Message-ID: <041401c50ae9$63c21a50$68b78851@xp> > But I'm looking for a solution to convert a Hex number > into binary, decimal, interger numbers. WE need to be very specific about our terminology here. All numbers in the computer are stored in binary. Only the string representation on the screen is in decimal, octal, hex etc. > What is the the binary value of the hex number 1F4. The binary value is the same as the hex value. The binary representation is 000111110100, but unfortunately Python doesn't support binary in its string formatting(although it does in int()! It does support decimal(%d) and octal(%o) though. And if you search the list archives you will find several functions that you can use to generate binary strings. Alan G. From flaxeater at yahoo.com Fri Feb 4 19:44:20 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Feb 4 19:44:25 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050204184421.16624.qmail@web54301.mail.yahoo.com> Max Noel wrote: > > According to the Jargon file, this one is called Whitesmiths > style. I tend to use Allman style myself, but given the code > completion, spellchecking, etc. in modern IDEs, I suspect it's become > more a question of personal preference than anything else. > > A bit like if(foo) versus if (foo), and whether or not to use > braces for single-line blocks. (the latter issue being why I think The > Whitespace Thing is an instance of Best Thing Ever(TM)) Bracing single line expressions is something I constantly agonize over. I'm always thinking may as well brace it because I may want to add more to this if clause. That's one of the reasons I like python is because it's relatively painless to make sure that your blocks are closed properly, especially when you aren't using a decent IDE. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Fri Feb 4 19:51:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:51:56 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <042001c50aea$9d0e1ce0$68b78851@xp> > Does anybody know how to convert a HEX into a BINARY? The easiest way I know is to use a lookup table on the octal representation. def bin(n): bins = ['000','001','010,'011',....'111'] result = '' for c in oct(n): result += bins[int(c,8)] return result HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Feb 4 19:54:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 4 19:54:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <042601c50aea$e6edb410$68b78851@xp> > Disagree to disagree again. I certainly don't think Perl is less > capable than awk. Neither do I... >> Really? Why for? awk is far easier to learn than Perl >> - and far less generally capable! - but it makes Perl seem >> positively verbose! I said awk was easier to learn but less capable than Perl. Perl is capable of things that awk can only dream of! Alan G. From rschroev_nospam_ml at fastmail.fm Fri Feb 4 20:00:15 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 20:01:36 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <03e001c50ae6$94dd15c0$68b78851@xp> References: <030b01c50a48$15e2df00$68b78851@xp> <03e001c50ae6$94dd15c0$68b78851@xp> Message-ID: Alan Gauld wrote: >>>foo = x and y or z >>> >>>is much less elegant than >>> >>>foo = x ? y : z >> >>You must be joking too... You think that >> >>x and y or z >> >>is as clear as >> >>x ? y : z > > > I think its clearer! It says that the first two things happen > or else the last thing. Plain English. That's apparently subjective then. I know what it means because I've read about it, but I still have trouble really grokking it. I don't have any problem with 'x and y' or with 'x or y', but somehow the combination of the two is one step too many for me. > '?:' means absolutely nothing without somebody to explain it. But ever since it was explained to me, I can parse it in the blink of an eye. (x**2 for x in range(10)) didn't mean anything to me either, the first time I saw it. > Interesting, obviously a lot of support for both, yet they are > features I try to avoid in C(*) and never miss in Python. If > given the choice I'd much rather have decent lambdas or > even a repeat/until loop! I don't really try to avoid them; I just use them when appropriate, which is not very often. But in those rare cases, I'm glad I don't have to resort to other, less appropriate constructs. And yes, a decent lambda would be nice indeed. Repeat/until too: I used it quite a lot in my Pascal days. But I don't know if it's worth cluttering the language up for. > (*)And most software houses I've worked with have ternary > operators on their "do not use" list along with switch fall-throughs. In my experience, such lists often go too far in that respect. I agree that fall-trough should mostly be avoided (except when multiple values should leed to the same branch). Ternary operators can certainly be abused (as demonstrated by much of the IOCCC entries), but can absolutely be useful when judisciously used. Many such lists seem to assume that developers can't judge such things for themselves. I think that if you have developers that can't do that, you have worse problems than a ternary operator here and there. -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Fri Feb 4 20:02:46 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri Feb 4 20:11:41 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In-Reply-To: <03ea01c50ae7$e2ffb860$68b78851@xp> References: <031901c50a49$e5142440$68b78851@xp> <200502031843.37545.budr@netride.net><037d01c50a9d$e01d0a70$68b78851@xp> <03ea01c50ae7$e2ffb860$68b78851@xp> Message-ID: Alan Gauld wrote: >>BTW, Steve McConnell recommends your favorite too in Code Complete. > > But > >>he also didn't manage to convince me. > > > Thats where I first found it, I looked up a couple of references and > the > message was consistent, so I changed my style. (And my emacs settings > :-) I'll have to read that part of the book again. But I don't have my hopes up since three years of using it at work didn't change my feelings about it (and not for a lack of trying). -- "Codito ergo sum" Roel Schroeven From dyoo at hkn.eecs.berkeley.edu Fri Feb 4 20:15:51 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 4 20:15:56 2005 Subject: [Tutor] switch vs table dispatch In-Reply-To: Message-ID: On Fri, 4 Feb 2005, Smith, Jeff wrote: > What you are try to do is "execute a block of code based on the value of > a single statement." if/elif doesn't do that and thereby introduces the > possibility of errors. > > switch on-this: > case 'a': > do something > case 'b': > do something else > case 'c': > do yet something else > > Is much clearer and more maintatinable than > > if on-this == 'a': > do something > elif on-this == 'b': > do something else > elif on-this == 'c': > do yet something else Hi Jeff, if/elif chains like this can be improved by using a table-dispatch technique: ### Python Pseudocode ### def doActionA(): ... def doActionB(): ... def doActionC(): ... dispatchTable = { 'a' : doActionA, 'b' : doActionB, 'c' : doActionC } dispatchTable[on_this]() ###### We perfectly agree with you about the hideousness of using if/elif/elif to do a 'switch'-style control flow. But that's not the only tool in our arsenal. *grin* switch() in other languages like C or Java have other limitations that are hard to explain to beginners. As one concrete example: we can't use a string as the dispatch value in Java's switch. We're restricted to use chars, bytes, shorts, or ints, due to the low-level implementation nature of 'switch': http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#35518 (I believe the expression is used as an index into a jump table, which limits it to something small and numeric.) Ultimately, this restricts the use of 'switch' to simple dispatch tasks, and we can already handle those nicely with a dictionary lookup. Hope this helps! From jeff at ccvcorp.com Fri Feb 4 22:23:06 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Feb 4 22:22:25 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <4203E7BA.30109@ccvcorp.com> Smith, Jeff wrote: > IMHO, if/elif/else statements are far more abused than either switch or > ternary but I certainly wouldn't argue they should be removed from the > language. IMHO, if it's true that if/elif/else statements are more abused than ternaries, then it's only because they're *used* far more often than ternaries. I'd say that the percentage of uses which could count as abuse is *far* higher for ternary than for if/elif/else. And I avoid (and recommend against) Python's "a and b or c" trick for similar reasons -- it *is* a trick. A 'real' ternary operator is confusing enough; this trick is more readable (words instead of opaque symbols) but more difficult to write correctly given the constraints on 'a'... Maybe I'm just weird, but I just don't find so much benefit to putting *everything* in-line. Occassionally it improves readability, but more often it obscures and obfuscates. Jeff Shannon Technician/Programmer Credit International From jsmith at medplus.com Fri Feb 4 22:36:44 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 22:36:50 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] Message-ID: Roel, That was well put. Too many people complain about certain language features because of the way they are abused independent of whether or not they have any value when used properly. In that case it's throwing the baby out with the bath-water...and won't achieve anything since bad programmers will be bad programmers no matter how much you try and constrain them. And in doing so you manage to prevent good programmers from creating clear conscise statements that exactly express the logic that they are trying to impliment. Jeff -----Original Message----- From: Roel Schroeven [mailto:rschroev_nospam_ml@fastmail.fm] Sent: Friday, February 04, 2005 2:00 PM To: tutor@python.org Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] In my experience, such lists often go too far in that respect. I agree that fall-trough should mostly be avoided (except when multiple values should leed to the same branch). Ternary operators can certainly be abused (as demonstrated by much of the IOCCC entries), but can absolutely be useful when judisciously used. Many such lists seem to assume that developers can't judge such things for themselves. I think that if you have developers that can't do that, you have worse problems than a ternary operator here and there. From patrick at kirks.net Fri Feb 4 22:47:58 2005 From: patrick at kirks.net (Patrick Kirk) Date: Fri Feb 4 22:48:00 2005 Subject: [Tutor] Small GUI toolkit and executable creators Message-ID: <4203ED8E.9090407@kirks.net> Hi all, I'm writing an application that will distributed by download and want it to be as small as possible. The target platform is Windows. For the GUI toolkit, I am looking at wxPython and tkinter. For a small application with only 4 working forms, which can be expected to produce the smaller programs? To create executables, I'm looking at using py2exe - http://starship.python.net/crew/theller/py2exe/ or Installer - http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html Has anyone any comments on which produces smaller executables and and if either is qualitively better than the other. Thanks in advance. Patrick From jsmith at medplus.com Fri Feb 4 22:55:53 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 22:56:00 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Now who's joking? Are you saying that switch var: case 'a': print 'a' case 'b' or 'c': print 'b or c' case 'd': pass default: print 'default case' Is less clear and maintainable than def do_this_function(): print 'a' def do_that_function(): print 'b or c' def do_pass_function(): pass def do_default_function(): print 'default case' ftable = { 'a' : do_this_function, 'b' : do_that_function, 'c' : do_that_function, 'd' : do_pass_function } ftable.get(var, do_default_function)() Ugh! -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Friday, February 04, 2005 1:14 PM To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > What you are try to do is "execute a block of code based on the value of > a single statement." if/elif doesn't do that and thereby introduces the > possibility of errors. In that case the best solution is a dictionary jump table. That is more maintainable than either and much faster too. And its also shorter to write. [Especially with lambdas :-)] > Note that the logic intended is that "on-this." So why force the > programmer to rewrite it N times and thereby introduce the possibility > of N-1 typographical errors... Thats a fair point although the dictionary solution avoids that. OTOH such switches tend to proliferate thropugh code and become a big source of maintenance headaches in their own right - multiple update syndrome across multiple files potentially. > Note that I've left out break. I'm not convinced that fall-through is > an important feature in switch and is usually the culpit in the cases > of abuse. The problem is its so hard to tell when fall though is happening intentionally or by accident because someone forgot a break sytatement. But when it comes to abuuse the fall through mechanism is one of the worst offenders in C, its just too tempting to be "clever" with it. > This is also true for the ternary operator. The desired logic is to > assign the value of a variable based on the value of some other > variable. But its not its based on the value of an *expression*. If the test could be limited to a single valiable value it might be justified but its an arbitrary expression. That makes it a conditional statement, which is most clearly represented by an if/else... Well I think so :-) > I also like Perl's unless statement but really prefer > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > expression. I won't argue on either point, Python's minimalist approach - there's only one way to do it - means a paucity of looping constructs - something I point out in my tutorial. But I can live with it for the other niceties it brings. Alan G. From marilyn at deliberate.com Fri Feb 4 23:07:14 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Feb 4 23:12:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: Message-ID: I think Danny was saying that if you don't like: if var == 'a': print 'a' elif var == 'b' or var == 'c': print 'b or c' elif var == 'd': pass else: print 'default case' you might like his dispatch scheme. And it has been mighty nice and handy for me since he taught me, in some special cases. I'll whisper that I'm a tiny bit disappointed to see the vaguely demeaning 'are you joking' theme that has emerged in here. It's unusual for us to be anything but generous and kind with each other. I guess this is a hot topic. :^) Marilyn On Fri, 4 Feb 2005, Smith, Jeff wrote: > Now who's joking? Are you saying that > > switch var: > case 'a': > print 'a' > case 'b' or 'c': > print 'b or c' > case 'd': > pass > default: > print 'default case' > > Is less clear and maintainable than > > def do_this_function(): > print 'a' > > def do_that_function(): > print 'b or c' > > def do_pass_function(): > pass > > def do_default_function(): > print 'default case' > > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() > > Ugh! > > > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Friday, February 04, 2005 1:14 PM > To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; > tutor@python.org > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > > > What you are try to do is "execute a block of code based on the > value of > > a single statement." if/elif doesn't do that and thereby introduces > the > > possibility of errors. > > In that case the best solution is a dictionary jump table. > That is more maintainable than either and much faster too. > And its also shorter to write. > [Especially with lambdas :-)] > > > Note that the logic intended is that "on-this." So why force the > > programmer to rewrite it N times and thereby introduce the > possibility > > of N-1 typographical errors... > > Thats a fair point although the dictionary solution avoids that. OTOH > such switches tend to proliferate thropugh code and become a big source > of maintenance headaches in their own right - multiple update syndrome > across multiple files potentially. > > > Note that I've left out break. I'm not convinced that fall-through is > > > an important feature in switch and is usually the culpit in the cases > > of abuse. > > The problem is its so hard to tell when fall though is happening > intentionally or by accident because someone forgot a break sytatement. > > But when it comes to abuuse the fall through mechanism is one of the > worst offenders in C, its just too tempting to be "clever" with it. > > > This is also true for the ternary operator. The desired logic is to > > assign the value of a variable based on the value of some other > > variable. > > But its not its based on the value of an *expression*. If the test could > be limited to a single valiable value it might be justified but its an > arbitrary expression. That makes it a conditional statement, which is > most clearly represented by an if/else... Well I think so :-) > > > I also like Perl's unless statement but really prefer > > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > > expression. > > I won't argue on either point, Python's minimalist > approach - there's only one way to do it - means a > paucity of looping constructs - something I point > out in my tutorial. But I can live with it for the > other niceties it brings. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From project5 at redrival.net Fri Feb 4 23:16:12 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 4 23:16:42 2005 Subject: [Tutor] Re: Small GUI toolkit and executable creators References: <4203ED8E.9090407@kirks.net> Message-ID: <1fjuzrb22jpfw.18mlutwc2tokg$.dlg@40tude.net> Patrick Kirk wrote on Fri, 04 Feb 2005 21:47:58 +0000: > I'm writing an application that will distributed by download and want it > to be as small as possible. The target platform is Windows. Python isn't the right choice if your aim is minimum "executable" size. I wouldn't worry too much about it though, people are perfectly used to downloading multi-megabyte applications and service packs which run into the hundreds of megabytes. > For the GUI toolkit, I am looking at wxPython and tkinter. For a small > application with only 4 working forms, which can be expected to produce > the smaller programs? I have no idea. The number of forms is not relevant, since it's the toolkit that takes up all the space, not the forms. I can tell you that a packaged wxPython app is roughly 4 MB, don't know about Tkinter. wxPython looks better (more native) though. > Has anyone any comments on which produces smaller executables and and if > either is qualitively better than the other. You shouldn't expect much difference in that respect, since they all do pretty much the same thing: pack up the junk and put an exe stub on it, and there's only so much compressing you can do. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jsmith at medplus.com Fri Feb 4 23:18:49 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 4 23:19:24 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Please don't take offense. I should have included the smiley. To reiterate an earlier statement: I like Python...a lot. But as with all langauges there are some things I don't like and I believe they were left out for the wrong reasons. On the indentation topic. I would be curious to know if anyone has had an experience where a rogue process or editor has trashed the indentation in your Python and how you recovered from it. Jeff -----Original Message----- From: Marilyn Davis [mailto:marilyn@deliberate.com] Sent: Friday, February 04, 2005 5:07 PM To: tutor@python.org Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] I think Danny was saying that if you don't like: if var == 'a': print 'a' elif var == 'b' or var == 'c': print 'b or c' elif var == 'd': pass else: print 'default case' you might like his dispatch scheme. And it has been mighty nice and handy for me since he taught me, in some special cases. I'll whisper that I'm a tiny bit disappointed to see the vaguely demeaning 'are you joking' theme that has emerged in here. It's unusual for us to be anything but generous and kind with each other. I guess this is a hot topic. :^) Marilyn On Fri, 4 Feb 2005, Smith, Jeff wrote: > Now who's joking? Are you saying that > > switch var: > case 'a': > print 'a' > case 'b' or 'c': > print 'b or c' > case 'd': > pass > default: > print 'default case' > > Is less clear and maintainable than > > def do_this_function(): > print 'a' > > def do_that_function(): > print 'b or c' > > def do_pass_function(): > pass > > def do_default_function(): > print 'default case' > > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() > > Ugh! > > > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Friday, February 04, 2005 1:14 PM > To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; > tutor@python.org > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > > > What you are try to do is "execute a block of code based on the > value of > > a single statement." if/elif doesn't do that and thereby introduces > the > > possibility of errors. > > In that case the best solution is a dictionary jump table. That is > more maintainable than either and much faster too. And its also > shorter to write. [Especially with lambdas :-)] > > > Note that the logic intended is that "on-this." So why force the > > programmer to rewrite it N times and thereby introduce the > possibility > > of N-1 typographical errors... > > Thats a fair point although the dictionary solution avoids that. OTOH > such switches tend to proliferate thropugh code and become a big > source of maintenance headaches in their own right - multiple update > syndrome across multiple files potentially. > > > Note that I've left out break. I'm not convinced that fall-through > > is > > > an important feature in switch and is usually the culpit in the > > cases > > of abuse. > > The problem is its so hard to tell when fall though is happening > intentionally or by accident because someone forgot a break > sytatement. > > But when it comes to abuuse the fall through mechanism is one of the > worst offenders in C, its just too tempting to be "clever" with it. > > > This is also true for the ternary operator. The desired logic is to > > assign the value of a variable based on the value of some other > > variable. > > But its not its based on the value of an *expression*. If the test > could be limited to a single valiable value it might be justified but > its an arbitrary expression. That makes it a conditional statement, > which is most clearly represented by an if/else... Well I think so :-) > > > I also like Perl's unless statement but really prefer > > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > > expression. > > I won't argue on either point, Python's minimalist > approach - there's only one way to do it - means a > paucity of looping constructs - something I point > out in my tutorial. But I can live with it for the > other niceties it brings. > > Alan G. > > _______________________________________________ > 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 budr at netride.net Fri Feb 4 23:28:58 2005 From: budr at netride.net (Bud Rogers) Date: Fri Feb 4 23:30:20 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <037d01c50a9d$e01d0a70$68b78851@xp> References: <200502031843.37545.budr@netride.net> <037d01c50a9d$e01d0a70$68b78851@xp> Message-ID: <200502041628.59359.budr@netride.net> On Friday 04 February 2005 03:42, Alan Gauld wrote: > On Thursday 03 February 2005 17:41, Alan Gauld wrote: > >> In fact the best style of all is neither of the two I showed, > >> its actually this - which early everyone hates when they see it! > >> > >> inf f(x) > >> { > >> bah() > >> } > > > >Ugh. Alan, I won't even try to dispute the study. But if I have to > >write code like that, I'll just take up gardening instead. :} > > Look at it conceptually: > > XXXXXXXXXXXX > XXXXX > XXXXX > XXXXX > > Thats Python! Since you are on this list I suspect you do write > "code like that" Its just Guido removed the now extraneous {}... Oh yes, you are absolutely right. If you remove the braces, all three (four?) styles of indentation are conceptually identical AFAICS. My objection is purely personal and aesthetic. The style above is just plain ugly to me. I'm not clear on which style is which, but I think the Allman style(?): if (foo) { bar; } is also ugly but slightly less so. The K&R style(?): if (foo) { bar; } is what I use in perl. I wouldn't go so far as to say it's pretty, it's just the least ugly of the styles I know about. And of course from a personal aesthetic perspective, I think python style is much prettier. Well written python reads like pseudocode. It's actually pleasant to read. If a routine is well written, with good variable names, etc, you don't even have to know much about python to understand what it does. That's one of the things that attracted me to python in the first place. -- Bud Rogers KD5SZ From cyresse at gmail.com Fri Feb 4 23:36:58 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 4 23:37:01 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: I had a problem with nested while 1: ... . ... ... break blocks. So, I got some sleep, fixed it, and now do everything in my power to not nest while 1 - break blocks. Not that it's really relevant. On Fri, 4 Feb 2005 17:18:49 -0500, Smith, Jeff wrote: > Please don't take offense. I should have included the smiley. To > reiterate an earlier statement: I like Python...a lot. But as with all > langauges there are some things I don't like and I believe they were > left out for the wrong reasons. > > On the indentation topic. I would be curious to know if anyone has had > an experience where a rogue process or editor has trashed the > indentation in your Python and how you recovered from it. > > Jeff > > -----Original Message----- > From: Marilyn Davis [mailto:marilyn@deliberate.com] > Sent: Friday, February 04, 2005 5:07 PM > To: tutor@python.org > Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] > > I think Danny was saying that if you don't like: > > if var == 'a': > print 'a' > elif var == 'b' or var == 'c': > print 'b or c' > elif var == 'd': > pass > else: > print 'default case' > > you might like his dispatch scheme. And it has been mighty nice and > handy for me since he taught me, in some special cases. > > I'll whisper that I'm a tiny bit disappointed to see the vaguely > demeaning 'are you joking' theme that has emerged in here. It's unusual > for us to be anything but generous and kind with each other. I guess > this is a hot topic. :^) > > Marilyn > > On Fri, 4 Feb 2005, Smith, Jeff wrote: > > > Now who's joking? Are you saying that > > > > switch var: > > case 'a': > > print 'a' > > case 'b' or 'c': > > print 'b or c' > > case 'd': > > pass > > default: > > print 'default case' > > > > Is less clear and maintainable than > > > > def do_this_function(): > > print 'a' > > > > def do_that_function(): > > print 'b or c' > > > > def do_pass_function(): > > pass > > > > def do_default_function(): > > print 'default case' > > > > ftable = { 'a' : do_this_function, > > 'b' : do_that_function, > > 'c' : do_that_function, > > 'd' : do_pass_function } > > ftable.get(var, do_default_function)() > > > > Ugh! > > > > > > -----Original Message----- > > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > > Sent: Friday, February 04, 2005 1:14 PM > > To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; > > tutor@python.org > > Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > > > > > > > What you are try to do is "execute a block of code based on the > > value of > > > a single statement." if/elif doesn't do that and thereby introduces > > the > > > possibility of errors. > > > > In that case the best solution is a dictionary jump table. That is > > more maintainable than either and much faster too. And its also > > shorter to write. [Especially with lambdas :-)] > > > > > Note that the logic intended is that "on-this." So why force the > > > programmer to rewrite it N times and thereby introduce the > > possibility > > > of N-1 typographical errors... > > > > Thats a fair point although the dictionary solution avoids that. OTOH > > such switches tend to proliferate thropugh code and become a big > > source of maintenance headaches in their own right - multiple update > > syndrome across multiple files potentially. > > > > > Note that I've left out break. I'm not convinced that fall-through > > > is > > > > > an important feature in switch and is usually the culpit in the > > > cases > > > of abuse. > > > > The problem is its so hard to tell when fall though is happening > > intentionally or by accident because someone forgot a break > > sytatement. > > > > But when it comes to abuuse the fall through mechanism is one of the > > worst offenders in C, its just too tempting to be "clever" with it. > > > > > This is also true for the ternary operator. The desired logic is to > > > assign the value of a variable based on the value of some other > > > variable. > > > > But its not its based on the value of an *expression*. If the test > > could be limited to a single valiable value it might be justified but > > its an arbitrary expression. That makes it a conditional statement, > > which is most clearly represented by an if/else... Well I think so :-) > > > > > I also like Perl's unless statement but really prefer > > > VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of > > > expression. > > > > I won't argue on either point, Python's minimalist > > approach - there's only one way to do it - means a > > paucity of looping constructs - something I point > > out in my tutorial. But I can live with it for the > > other niceties it brings. > > > > Alan G. > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only ba sic human duty, to take the consequences. From pythontutor at yahoo.com Fri Feb 4 23:48:55 2005 From: pythontutor at yahoo.com (alieks lao) Date: Fri Feb 4 23:48:59 2005 Subject: [Tutor] arrays Message-ID: <20050204224855.33514.qmail@web61306.mail.yahoo.com> in this tutorial it's telling me to "from Numeric import *" to load array functions but it doesn't work is there a replacement for "Numeric" or are arrays built in functions? thanks alex __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 00:03:05 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 00:03:08 2005 Subject: [Tutor] arrays In-Reply-To: <20050204224855.33514.qmail@web61306.mail.yahoo.com> Message-ID: On Fri, 4 Feb 2005, alieks lao wrote: > in this tutorial it's telling me to > > "from Numeric import *" > > to load array functions > but it doesn't work is there a replacement for > "Numeric" or are arrays built in functions? Hi Alieks, Just out of curiosity, which tutorial are you reading? The 'Numeric' library isn't built-in: it is a third party library that's available here: http://www.pfdubois.com/numpy/ You'll need to install Numpy first; this should make the Numeric library available, and hopefully the error message should go away. *grin* Best of wishes to you! From kent37 at tds.net Sat Feb 5 00:13:49 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 00:13:53 2005 Subject: [Tutor] arrays In-Reply-To: <20050204224855.33514.qmail@web61306.mail.yahoo.com> References: <20050204224855.33514.qmail@web61306.mail.yahoo.com> Message-ID: <420401AD.3060506@tds.net> Numeric is an add-on module, not part of the standard distribution. You have to download it and install it. (I'm surprised your tutorial doesn't point that out!) Numeric is still in use but there is a newer version called numarray. You can read about them both here: http://www.pfdubois.com/numpy/ Kent alieks lao wrote: > in this tutorial it's telling me to > > "from Numeric import *" > > to load array functions > but it doesn't work is there a replacement for > "Numeric" or are arrays built in functions? > thanks > alex > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Helps protect you from nasty viruses. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 00:19:17 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 00:19:21 2005 Subject: [Tutor] Whitespace indentation In-Reply-To: Message-ID: On Fri, 4 Feb 2005, Smith, Jeff wrote: > On the indentation topic. I would be curious to know if anyone has had > an experience where a rogue process or editor has trashed the > indentation in your Python and how you recovered from it. [Meta: switching subject line again --- this conversation seems to be veering off to other subtopics.] Hi Jeff, I have run into some whitespace issues, but it had more to do with line-ending terminators for code sent between Windows and Unix machines. But that's more of a Unix vs. Windows thing than anything else. *grin* On the whole, though, using indentation as blocks has worked really well for me, and hasn't been a liability. I do try to keep my code backed by a version control system like Subversion or CVS: http://subversion.tigris.org/ https://www.cvshome.org/ which seems to keep me safe from my own incompetence most of the time. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 00:25:53 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 00:25:56 2005 Subject: [Tutor] arrays In-Reply-To: <20050204231727.43074.qmail@web61306.mail.yahoo.com> Message-ID: On Fri, 4 Feb 2005, alieks lao wrote: > > Just out of curiosity, which tutorial are you reading? > > heres the url... > http://www.pentangle.net/python/ Hi Alieks, Ah, ok, that makes sense now. Michael William's tutorial assumes an environment where some third-party modules, like Numeric, have already been installed by the Sun system administrators that the author refers to at the beginning of Chapter Two. So there will probably be small things in that coursebook that are really external resources. It would have been good for the author to explicitely mention things like Numeric though... oh well. We'll do what we can on Tutor to help if you run into issues like that again. Best of wishes! From alan.gauld at freenet.co.uk Sat Feb 5 00:39:10 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 00:39:00 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <045901c50b12$ba9ac830$68b78851@xp> > Now who's joking? :-) > Are you saying that > > switch var: > case 'a': > print 'a' > ... > default: > print 'default case' > > Is less clear and maintainable than I don;tthink I said (certainly didn't mean) less clear, but yes it is less maintainable. But then... > def do_this_function(): > print 'a' > .... > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() I did also say that it was best with proper lambdas ftable = {'a' : lambda: print 'a', 'b' : lambda: print 'b' etc/// and I'd code the calling section: try: ftable[value]() except KeyError: doDefaultFunction() Its more maintainable because even if the switches proliferates as they tend to do, the dictionary stays in one place and the calling code never needs changing. So the changes are much more localised. And of course the more complex the case actions are, the more effective the dictionary/function approach becomes. Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:18:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:18:08 2005 Subject: [Tutor] Re: Are you allowed to shoot camels? [kinda OT] References: <030b01c50a48$15e2df00$68b78851@xp> <03e001c50ae6$94dd15c0$68b78851@xp> Message-ID: <049901c50b18$3605fd50$68b78851@xp> > > I think its clearer! It says that the first two things happen > > or else the last thing. Plain English. > > That's apparently subjective then. So it seems. You always assume that whats clear to you will be clear to all! This discussion proves it ain't necessarily so... > eye. (x**2 for x in range(10)) didn't mean anything to me either, the > first time I saw it. Nor me and I knew comprehensions from Haskell. Its taken me about 203 years to get comfortable with LCS inPython. I really wish they'd stick a marker (| or : or even a $!) between the first item and the loop: [x**2 | for x in range(10)] I'd have found it much easier to grok. And I can't think iof any syntax rules of expressions it wouuld break. Do we use | as a bitwise operatorin Python? I don't think so... > absolutely be useful when judisciously used. Many such lists seem to > assume that developers can't judge such things for themselves. I think Having been involved in creating a couple such coding guidelines lists I can say from experience that they mostly reflect the problems the maintenance teams struggle with most. And having led a team of maintenance C programmers for 2 years I fully sympathise with the view that programmers can't judge very well. (And that includes myself, I am well aware that what seems perfectly clear to me when I write it may not be to some poor sap who has to fix/enhance it) And remember too that maintenance accounts for 80% of the cost on most software projects... Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:24:21 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:25:12 2005 Subject: [Tutor] Small GUI toolkit and executable creators References: <4203ED8E.9090407@kirks.net> Message-ID: <04a601c50b19$0a2ff450$68b78851@xp> > I'm writing an application that will distributed by download and want it > to be as small as possible. The target platform is Windows. In that case distribute Python source not executables! Or write in assembler... > For the GUI toolkit, I am looking at wxPython and tkinter. For a small > application with only 4 working forms, which can be expected to produce > the smaller programs? Sorry no idea on that one, any responses will be interesting. > To create executables, I'm looking at using > py2exe - http://starship.python.net/crew/theller/py2exe/ > or > Installer - http://davidf.sjsoft.com/mirrors/mcmillan-inc/install1.html Both will make your programs much bigger and, worse still, if you distribute updates each version with replicate the Python engine, better to do a two part downloiad IMHO - the python core then your programs as source(or compiled modules). Basically using Python for small downloads is probably not the best approach! But the really small sizes are much more effort to create! Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:27:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:27:38 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <04ad01c50b19$87635890$68b78851@xp> Marilyn, > I'll whisper that I'm a tiny bit disappointed to see the vaguely > demeaning 'are you joking' theme that has emerged in here. It's > unusual for us to be anything but generous and kind with each other. > I guess this is a hot topic. :^) Languages (and editors) are always emotional topics on the 'net... But I was actually thinking that here we are on a mailing list having a mini-language war and by internet standards its extremely civilised! Nobody has called anyone a moron or an idiot yet and an 'are you joking' is, to me at least, just a term of speech, not an insult. Certainly if anyone has been offended I apologise profusely it was never meant thus. Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 01:29:40 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 01:29:26 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <04c001c50b19$c87e1040$68b78851@xp> > an experience where a rogue process or editor has trashed the > indentation in your Python and how you recovered from it. Only in mailing list emails!! Alan G. From marilyn at deliberate.com Sat Feb 5 01:51:28 2005 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Feb 5 01:56:17 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <04ad01c50b19$87635890$68b78851@xp> Message-ID: On Sat, 5 Feb 2005, Alan Gauld wrote: > Marilyn, > > > I'll whisper that I'm a tiny bit disappointed to see the vaguely > > demeaning 'are you joking' theme that has emerged in here. It's > > unusual for us to be anything but generous and kind with each other. > > I guess this is a hot topic. :^) > > Languages (and editors) are always emotional topics on the 'net... > > But I was actually thinking that here we are on a mailing list having > a mini-language war and by internet standards its extremely civilised! > Nobody has called anyone a moron or an idiot yet and an 'are you > joking' is, to me at least, just a term of speech, not an insult. > Certainly if anyone has been offended I apologise profusely it > was never meant thus. This is a great list. Please don't apologize. Super-super-sensitive people like me are reluctant to post if they sense ridicule, even if it wasn't intended. So I'm sorry for my sensitivity. Thank you again for all the great help I've received, and the safe place to expose my ignorance. Marilyn > > Alan G. > > -- From keridee at jayco.net Sat Feb 5 02:18:32 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 02:22:51 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <20050204025418.49854.qmail@web54307.mail.yahoo.com> Message-ID: <000801c50b21$435d6e30$575428cf@JSLAPTOP> > Now this is a concrete example of how lambda simplifies code, at > least > for me because it does not clutter my mental name space. Also it is > much shorter. However it should be said that this is very much a > question of taste. Agreed. Which would make it pointless to remove in a future release. ;-) > However I must say that lambda's are very useful > even necessary for using Tkinter. I'll bet that there is an easy enough way to use Tkinter without them (Before anyone wants to argue my points, I would like to say that I'm neutral in this discussion, I only wish to point out alternative views) > aFuncList=[] > def x(): > print "one" > aFuncList.append(x) > def x(): > print "two" > aFuncList.append(x) > def x(): > print "three" > aFuncList.append(x) > for item in aFuncList: > item() Okay, for this problem (it can be altered otherwise) def makefunct(stri): def x(): print stri return x aFuncList = [makefunct('one'),makefunct('two'),makefunct('three')] for item in aFuncList: item() It's shorter, it works and it looks cool. Thanks to Jeff Shannon for the backbone of this example. Jacob Schmidt From fant at pobox.com Sat Feb 5 00:27:03 2005 From: fant at pobox.com (Andrew D. Fant) Date: Sat Feb 5 02:46:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <042601c50aea$e6edb410$68b78851@xp> References: <042601c50aea$e6edb410$68b78851@xp> Message-ID: <420404C7.2030409@pobox.com> Alan Gauld wrote: > > I said awk was easier to learn but less capable than Perl. > > Perl is capable of things that awk can only dream of! Surely you jest, Alan. :-) Both perl and awk are turing complete, hence anything perl can do, awk can do as well. Now, as to which one would be easier to work with for a large scale development project, I will leave that flame-fest up to the regulars. Andy From bvande at po-box.mcgill.ca Sat Feb 5 04:31:41 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 5 04:32:56 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <420404C7.2030409@pobox.com> References: <042601c50aea$e6edb410$68b78851@xp> <420404C7.2030409@pobox.com> Message-ID: <42043E1D.30702@po-box.mcgill.ca> Andrew D. Fant said unto the world upon 2005-02-04 18:27: > Alan Gauld wrote: > >> >> I said awk was easier to learn but less capable than Perl. >> >> Perl is capable of things that awk can only dream of! > > > Surely you jest, Alan. :-) I'm prettry sure he means it. And stop calling him Surely ;-) Brian vdB From shitizb at yahoo.com Sat Feb 5 04:37:14 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 5 04:37:17 2005 Subject: [Tutor] freeze Message-ID: <20050205033715.43926.qmail@web53807.mail.yahoo.com> Hi, I intend to create compiled python binaries on linux. I understand that freeze can be used to do this. But I have few doubts i would like to clarify. 1. In the freeze documentation i found the lines: "One tricky issue: Freeze assumes that the Python interpreter and environment you're using to run Freeze is the same one that would be used to run your program, which should also be the same whose sources and installed files you will learn about in the next section. In particular, your PYTHONPATH setting should be the same as for running your program locally. (Tip: if the program doesn't run when you type "python hello.py" there's little chance of getting the frozen version to run.)" My intention is to create files which can be run on Linux systems with python not installed.Do the above lines mean that freeze can't do it(which defeats the very pupose of the program i guess.). 2. While compiling with freeze....it seems that it is including all the available modules, even if they are not required.Of course using freeze -X is one option,but it being really cumbersome, is there a better option available. In case the above issues do present a problem, is there any alternative to freeze? Shitiz __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From keridee at jayco.net Sat Feb 5 04:58:06 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 04:58:24 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <04c001c50b19$c87e1040$68b78851@xp> Message-ID: <003501c50b36$eb4da140$215428cf@JSLAPTOP> >> an experience where a rogue process or editor has trashed the >> indentation in your Python and how you recovered from it. > > Only in mailing list emails!! I'll second that!!! Jacob > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sat Feb 5 05:22:12 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 05:22:33 2005 Subject: [Tutor] freeze References: <20050205033715.43926.qmail@web53807.mail.yahoo.com> Message-ID: <008201c50b3a$61e5dc70$215428cf@JSLAPTOP> My two bits. 1) Download py2exe found here http://py2exe.sourceforge.net/ 2) Make a setup file -- intructions can be found through above link, I think. (Hey that rhymes!) 3) Ask if you want my totally cool automation technique 4) Ask more questions, go on we don't mind. HTH, Jacob Schmidt > Hi, > > I intend to create compiled python binaries on linux. > I understand that freeze can be used to do this. > But I have few doubts i would like to clarify. > > 1. In the freeze documentation i found the lines: > > "One tricky issue: Freeze assumes that the Python > interpreter and > environment you're using to run Freeze is the same one > that would be > used to run your program, which should also be the > same whose sources > and installed files you will learn about in the next > section. In > particular, your PYTHONPATH setting should be the same > as for running > your program locally. (Tip: if the program doesn't > run when you type > "python hello.py" there's little chance of getting the > frozen version > to run.)" > > My intention is to create files which can be run on > Linux systems with python not installed.Do the above > lines mean that freeze can't do it(which defeats the > very pupose of the program i guess.). > > 2. While compiling with freeze....it seems that it is > including all the available modules, even if they are > not required.Of course using freeze -X is one > option,but it being really cumbersome, is there a > better option available. > > In case the above issues do present a problem, is > there any alternative to freeze? > > Shitiz > > > > __________________________________ > Do you Yahoo!? > The all-new My Yahoo! - Get yours free! > http://my.yahoo.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sat Feb 5 05:30:19 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 05:30:07 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> Message-ID: <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> > The binary value is the same as the hex value. > The binary representation is 000111110100, but > unfortunately Python doesn't support binary in > its string formatting(although it does in int()! Uh, question. Why not? It seems that all simple types should be included. Since the computer stores it as binary, why shouldn't python be able to display a string of it in binary? That seems to be a short coming that should be added to the next release... IMHO of course. Jacob Schmidt From pythontutor at yahoo.com Sat Feb 5 06:23:05 2005 From: pythontutor at yahoo.com (alieks lao) Date: Sat Feb 5 06:23:08 2005 Subject: [Tutor] question about expressing mathematical equations Message-ID: <20050205052306.45646.qmail@web61302.mail.yahoo.com> Once again i have a question concerning something from the tutorial im being tortured by. ___ x.y= \ x (dot)y(dot) /__ i i How would i express this in python. If the above doesn't make any sense to ya'll. It's at the bottom of this page>>> http://www.pentangle.net/python/handbook/node33.html Again thanks in advance... alex __________________________________ Do you Yahoo!? The all-new My Yahoo! - Get yours free! http://my.yahoo.com From patrick at kirks.net Sat Feb 5 07:30:01 2005 From: patrick at kirks.net (Patrick Kirk) Date: Sat Feb 5 07:30:05 2005 Subject: [Tutor] Small GUI toolkit and executable creators In-Reply-To: <42043AFD.4040706@adinet.com.uy> References: <4203ED8E.9090407@kirks.net> <42043AFD.4040706@adinet.com.uy> Message-ID: <420467E9.5070908@kirks.net> That looks fine size wise. Thanks. Ismael Garrido wrote: > Patrick Kirk wrote: > >> Hi all, >> >> I'm writing an application that will distributed by download and want >> it to be as small as possible. The target platform is Windows. > > > Use UPX, 7Z and NSIS. ;-) (and in that order, too :-P) > That's with Py2exe, never tryed the other one. > > I made a program with Tkinter and managed to get it all together in > 1.8Mb, 8kb of source :-S > > Gretz > Ismael From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 07:52:33 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 07:52:38 2005 Subject: [Tutor] question about expressing mathematical equations In-Reply-To: <20050205052306.45646.qmail@web61302.mail.yahoo.com> Message-ID: On Fri, 4 Feb 2005, alieks lao wrote: > Once again i have a question concerning something from the tutorial im > being tortured by. > > ___ > x.y= \ x (dot)y(dot) > /__ i > i > > How would i express this in python. > If the above doesn't make any sense to ya'll. > It's at the bottom of this page>>> > http://www.pentangle.net/python/handbook/node33.html [Note to author Michael Williams: we found a wacky typography bug on the HTML rendering of the link above. I'm CCing you to make sure you know about it.] Hi Alieks, Ah, ok, I see it: you're talking about exercise 3.10? The guide there is using linear algebra notation: it is defining the dot product between two vectors 'x' and 'y'. I think you're misreading the diagram: it's more like this: ___ x dot y= \ x * y /__ i i i (The period at the end of the equation is really meant to be just a typographic period. *grin*) As a concrete example, if we were taking the dot product between two sequences 'x' and 'y': x = (3, 1, 4, 1, 5) y = (2, 7, 1, 8, 2) then we'd be calculating, in effect: (x[0] * y[0] + x[1] * y[1] + x[2] * y[2] + x[3] * y[3] + x[4] * y[4]) --> ( 3 * 2 + 1 * 7 + 4 * 1 + 1 * 8 + 5 * 2 ) --> ( 6 + 7 + 4 + 8 + 10 ) --> 35 Numeric Python comes with an dot() function built in: http://www.pfdubois.com/numpy/html2/numpy-9.html#pgfId-36540 so if you're dealing strictly with Numeric arrays, you don't need to do any work to 'dot' two arrays together. *grin* ... Oh, that's not good! Warning: It looks like the typography of Exercise 3.10 in the HTML is screwed up. The problem as written in the HTML is nonsensical. Look at the PDF instead. You'll see that the question will make more sense in the PDF here: http://www.pentangle.net/python/handbook.pdf The GIF images in the HTML has some strange offset error that I don't understand, but img22.gif and img23.gif are in the wrong places on the HTML page. I'll CC the author to see if that can get fixed. I notice that you're learning from the "Handbook of the Physics Computing Course". There are other tutorials in: http://www.python.org/moin/BeginnersGuide/NonProgrammers that you may find more approachable if you want less math. Good luck to you! From alan.gauld at freenet.co.uk Sat Feb 5 09:59:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 09:59:45 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <042601c50aea$e6edb410$68b78851@xp> <420404C7.2030409@pobox.com> Message-ID: <04fc01c50b61$01535960$68b78851@xp> > Surely you jest, Alan. :-) Smiley noted but... > Both perl and awk are turing complete, hence anything perl can do, awk > can do as well. This is a popular misconception. Being Turing complete simply means you can implement any algorithm. But if the language doesn't provide I/O access for example it is impossible to write a device driver, or a comms stack, or any of a host of other low level programs. awk is non extendable (unless you have the source code!) so you can't do those things. Perl is not only extendable but actually comes wth a heap of those kinds of features that awk just doesn't have. And no amount of clever algorithms can compensate. Awk was designed for one task which it does spectacularly well but it was never intended for general purpose use. I/O is just one example, there are meny more... Alan G. From pythontutor at yahoo.com Sat Feb 5 11:47:12 2005 From: pythontutor at yahoo.com (alieks lao) Date: Sat Feb 5 11:47:15 2005 Subject: [Tutor] question about expressing mathematical equations In-Reply-To: Message-ID: <20050205104712.68003.qmail@web61303.mail.yahoo.com> I've spent hours trying things out and I'm no better off. I don't understand exactly what I'm supposed to do... alieks __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050205/02ff0e20/attachment.html From cyresse at gmail.com Sat Feb 5 12:44:43 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 5 12:44:46 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> Message-ID: Jacob - just for you, begin your agitation for the next release please ;) binstring.py, as attached. (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) Creating this, was just a brain teaser, but I was thinking 'what if I wanted to make this for the standard library.' And so you can see, I had to include a flag for endianess. But that was really a cheap trick. If this was going into a standard library, I'd want to query the OS for endianess. As for the bits, once again, 32 bit is the norm, but 64 bit is here and spreading. Also, should it display 11111111 as 255 or 256? Both are valid, depending on context. Thirdly, if I can do it in 2 minutes, (well, the main part), then should they bother putting it in the standard library considering also, - How often, really, are you going to need to present a decimal or hex as a binary string. Lastly - this only does base 10 to base 2. Should I include a base 6 to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? I wouldn't like to write for the standard library, because you can never please everyone. But yeah, feel free to use the above, just keep my doc strings and comments. Regards, Liam Clarke On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. wrote: > > The binary value is the same as the hex value. > > The binary representation is 000111110100, but > > unfortunately Python doesn't support binary in > > its string formatting(although it does in int()! > > Uh, question. Why not? It seems that all simple types should be included. > Since the computer stores it as binary, why shouldn't python be able to > display a > string of it in binary? That seems to be a short coming that should be added > to the > next release... IMHO of course. > Jacob Schmidt > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -------------- next part -------------- A non-text attachment was scrubbed... Name: binstring.py Type: text/x-python Size: 1107 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050206/28f6f80e/binstring.py From dyoo at hkn.eecs.berkeley.edu Sat Feb 5 13:06:06 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 5 13:06:09 2005 Subject: [Tutor] question about expressing mathematical equations In-Reply-To: <20050205104712.68003.qmail@web61303.mail.yahoo.com> Message-ID: On Sat, 5 Feb 2005, alieks lao wrote: > I've spent hours trying things out and I'm no better off. I don't > understand exactly what I'm supposed to do. Hi Alieks, What part of the problem are you working on? If you show us what you've tried so far; we can then try to figure out why you're getting stuck on, and help you so you get unstuck. But again, you may have a much easier time if you use a different tutorial. The one you're using right now is actually aimed for physicists! At least, it's aimed for beginning physicists, so they're assuming a familiarity with things like vector math, a particular computing lab environment, and a topical focus that appeals to folks who are doing numerical analysis stuff. This may not be the best tutorial for you. You may like this one better: http://www.freenetpages.co.uk/hp/alan.gauld/ Alan Gauld is the author of this tutorial, and he also answers questions on this mailing list, so if you try this tutorial, you may get answers that are quite, well, authoritative. *grin* If you have any questions, please feel free to ask. From shitizb at yahoo.com Sat Feb 5 13:08:57 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Sat Feb 5 13:09:00 2005 Subject: [Tutor] freeze In-Reply-To: <008201c50b3a$61e5dc70$215428cf@JSLAPTOP> Message-ID: <20050205120857.63243.qmail@web53810.mail.yahoo.com> Hi, Do exe files generated by py2run on linux???i thought it was only for windows. Shitiz --- "Jacob S." wrote: > My two bits. > > 1) Download py2exe found here > http://py2exe.sourceforge.net/ > 2) Make a setup file -- intructions can be found > through above link, I > think. > (Hey that rhymes!) > 3) Ask if you want my totally cool automation > technique > 4) Ask more questions, go on we don't mind. > > HTH, > Jacob Schmidt > > > Hi, > > > > I intend to create compiled python binaries on > linux. > > I understand that freeze can be used to do this. > > But I have few doubts i would like to clarify. > > > > 1. In the freeze documentation i found the lines: > > > > "One tricky issue: Freeze assumes that the Python > > interpreter and > > environment you're using to run Freeze is the same > one > > that would be > > used to run your program, which should also be the > > same whose sources > > and installed files you will learn about in the > next > > section. In > > particular, your PYTHONPATH setting should be the > same > > as for running > > your program locally. (Tip: if the program > doesn't > > run when you type > > "python hello.py" there's little chance of getting > the > > frozen version > > to run.)" > > > > My intention is to create files which can be run > on > > Linux systems with python not installed.Do the > above > > lines mean that freeze can't do it(which defeats > the > > very pupose of the program i guess.). > > > > 2. While compiling with freeze....it seems that it > is > > including all the available modules, even if they > are > > not required.Of course using freeze -X is one > > option,but it being really cumbersome, is there a > > better option available. > > > > In case the above issues do present a problem, is > > there any alternative to freeze? > > > > Shitiz > > > > > > > > __________________________________ > > Do you Yahoo!? > > The all-new My Yahoo! - Get yours free! > > http://my.yahoo.com > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From alan.gauld at freenet.co.uk Sat Feb 5 14:08:06 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 14:10:21 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> Message-ID: <051901c50b83$bc638ff0$68b78851@xp> > > unfortunately Python doesn't support binary in > > its string formatting(although it does in int()! > > Uh, question. Why not? It seems that all simple types should be included. I agree it has always seemed bizarre that inary is not included but octal is, IMHO binary is more useful as a representation than octal... My guess is brcause the C sprintf() function doesn't support binary... But that shouldn't really be an excuse. Alan G. From alan.gauld at freenet.co.uk Sat Feb 5 14:26:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 14:26:04 2005 Subject: [Tutor] question about expressing mathematical equations References: <20050205104712.68003.qmail@web61303.mail.yahoo.com> Message-ID: <052f01c50b86$3efe17d0$68b78851@xp> > I've spent hours trying things out and I'm no better off. > I don't understand exactly what I'm supposed to do... > alieks The tutor you are using is fairly specialised. What are you trying to learn? Python or math in Python? To learn Python use one of the other tutorials that focus on Pyhon itself - if you can already program use the official tutor on the web site(or download it) If you can't already program use one of the tutors on the Beginners page that Danny pointed you towards. If OTOH you can grok Python and want to do math in it then the tutor you have is fine. So what is it you don't understand? The math, otr the Python? Its hard for us to guess... :-) Alan G. From kent37 at tds.net Sat Feb 5 16:48:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 16:48:07 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> Message-ID: <4204EAB1.2050206@tds.net> Liam, I think you misunderstand what endianness is. Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory of the computer. This is not something you generally need to worry about in a Python program. For example, consider the number 0x12345678. On most modern computers this will be stored in four consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, 0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. Most programming languages will hide this detail from you most of the time. Even in assembly language, you generally load and store integers without worrying about endianness. Math operations just do the right thing so you don't have to worry about it. Endianness becomes an issue when you want to convert between representations, and when binary data is shared between computers which may have different endianness. For example in a C program you might want to get the high byte of an integer when you know the address of the integer. The desired byte will be at (address+0) or (address+3) depending on the endianness of the hardware. Similarly, if an array of integers is written to a file in a binary representation (not as ASCII strings representing the integers, but as 32-bit values), then to correctly read the file you have to know the endianness of the data in the file. OK, so what does this have to do with converting a number to binary in Python? Well, nothing, actually. First, note that 'binary representation' can mean two different things. In the description above, I was talking about the actual bit pattern stored in the computer. Python works with binary numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary representation' is that of a base-2 string representation of a number. So if you ask, "How do I convert a number to binary?" you can mean either of these. The first one is trivial. If you have a decimal string representation of the number, use int() to convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to do anything! So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an integer to a base-2 string representation?" And how do you do this? Well, you figured out one way using the mathematical properties of integers. These operations are independent of endianness, and so is the desired result. The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is '0001001000110100'. The order of digits here is determined by our convention of writing the most significant digits on the left, not by the endianness of the underlying computer. OK, this is long enough, I hope I have shed some light... Kent Liam Clarke wrote: > Jacob - just for you, begin your agitation for the next release please ;) > > binstring.py, as attached. > (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > > Creating this, was just a brain teaser, but I was thinking 'what if I > wanted to make this for the standard library.' > > And so you can see, I had to include a flag for endianess. But that > was really a cheap trick. If this was going into a standard library, > I'd want to query the OS for endianess. As for the bits, once again, > 32 bit is the norm, but 64 bit is here and spreading. > > Also, should it display 11111111 as 255 or 256? Both are valid, > depending on context. > > Thirdly, if I can do it in 2 minutes, (well, the main part), then > should they bother putting it in the standard library considering > also, > > - How often, really, are you going to need to present a decimal or hex > as a binary string. > > Lastly - this only does base 10 to base 2. Should I include a base 6 > to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > > I wouldn't like to write for the standard library, because you can > never please everyone. > > But yeah, feel free to use the above, just keep my doc strings and comments. > > Regards, > > Liam Clarke > > On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. wrote: > >>>The binary value is the same as the hex value. >>>The binary representation is 000111110100, but >>>unfortunately Python doesn't support binary in >>>its string formatting(although it does in int()! >> >>Uh, question. Why not? It seems that all simple types should be included. >>Since the computer stores it as binary, why shouldn't python be able to >>display a >>string of it in binary? That seems to be a short coming that should be added >>to the >>next release... IMHO of course. >>Jacob Schmidt >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > ------------------------------------------------------------------------ > > ###### > # binString.py > # by Liam Clarke > #(Let me know when it's included in the standard library ;-)) > ###### > > """Converts a integer base 10 to a string base 2""" > > def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > """ > Integer to be converted is essential, Endianess is an optional flag; > me being a Win32 user, Endianess is big by default, defaults to a 32-bit > representation, most integers in Python being 32 bit. truncExcess will > strip place-holder zeros for succintness. > > Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > to start counting for zero with this. It's a simple matter to change.""" > tempList = ['0' for x in range(bits)] > > for bitPlace in range(bits, -1, -1): > if decimalInt - 2**bitPlace >= 0: > tempList[bitPlace] = '1' > decimalInt = decimalInt - 2**bitPlace > if bigEndian: > tempList.reverse() > > outPut = ''.join(tempList) > > if truncExcess: > if bigEndian: > outPut=outPut.lstrip('0') > else: > outPut=outPut.rstrip('0') > > return outPut > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From mark.kels at gmail.com Sat Feb 5 18:19:04 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 5 18:19:08 2005 Subject: [Tutor] A problem with a Tkinter program (using the text widget) Message-ID: Hi all. Whats wrong here ?? : from Tkinter import * def p_text(): print text.get() root=Tk() text=Text(root).pack() button=Button(root,text="Click here!!",command=p_text).pack() root.mainloop() I get an error that says that nontype object has no attribute 'get'... whats wrong ?? Thanks. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From sandip at lug-delhi.org Sat Feb 5 19:58:08 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sat Feb 5 19:58:38 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> References: <812D33B03107804389D6F4247B69EFAC3A294F@dfre2k03.itg.ti.com> Message-ID: <42051740.7040906@lug-delhi.org> Tamm, Heiko wrote: > > > Ok, thank you. > > > Does anybody know how to convert a HEX into a BINARY? > > Just trying my hand out on python : To convert the value of i to binary: ================== i = 456 s = '' while i: s = str(i % 2) + s i/=2 print s ================= in case you have i in the form of a hex string, you can always add "i=int(i,16)" before the loop. - Sandip From kent37 at tds.net Sat Feb 5 20:12:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 20:12:31 2005 Subject: [Tutor] A problem with a Tkinter program (using the text widget) In-Reply-To: References: Message-ID: <42051A9B.60207@tds.net> Mark Kels wrote: > Hi all. > Whats wrong here ?? : > from Tkinter import * > def p_text(): > print text.get() > root=Tk() > text=Text(root).pack() pack() doesn't return a value. You have to do text = Text(root) text.pack() I've been bitten by this one more than once myself :-( Kent > button=Button(root,text="Click here!!",command=p_text).pack() > root.mainloop() > > I get an error that says that nontype object has no attribute 'get'... > whats wrong ?? > > Thanks. > > From alan.gauld at freenet.co.uk Sat Feb 5 20:29:32 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 5 20:29:29 2005 Subject: [Tutor] A problem with a Tkinter program (using the text widget) References: Message-ID: <055201c50bb9$05602710$68b78851@xp> > Whats wrong here ?? : > from Tkinter import * > def p_text(): > print text.get() > root=Tk() > text=Text(root).pack() pack() retirns None, YOu *must* use two steps: text = Text(....) text.pack() > button=Button(root,text="Click here!!",command=p_text).pack() > root.mainloop() > > I get an error that says that nontype object has no attribute 'get'... > whats wrong ?? Because your text variable contains None, which doesn't support get... Don't worry, its one of the most common Tkinter mistakes and bites most folks at some stage... Alan G. From keridee at jayco.net Sat Feb 5 22:10:33 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 5 22:10:59 2005 Subject: [Tutor] freeze References: <20050205120857.63243.qmail@web53810.mail.yahoo.com> Message-ID: <000901c50bc7$42718320$c45328cf@JSLAPTOP> Hey! Good question! I have no idea. Jacob Schmidt P.S. Here's a cool setup script for py2exe if you want to try it though. ### setup.py ### # Run the build process by entering 'setup.py py2exe' or # 'python setup.py py2exe' in a console prompt. from distutils.core import setup import py2exe import os def getdir(): current = os.getcwd() m = 'y' while m == 'y': print "Current directory is: %s" % current m = raw_input("Do you wish to change the directory? ") if m == 'y': n = raw_input("What is the new directory? ") if not n.count(":"): current = os.path.join(current,n) else: current = n os.chdir(current) getdir() listed = [] while 1: ask = raw_input('What is the file you want as an executable? ') if ask == 'quit' or ask == 'stop': break else: listed.append(os.path.join(desktop,ask)) os.chdir(uck) setup(console = listed) ## End of setup.py ### From kent37 at tds.net Sat Feb 5 22:22:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 5 22:22:15 2005 Subject: [Tutor] freeze In-Reply-To: <20050205120857.63243.qmail@web53810.mail.yahoo.com> References: <20050205120857.63243.qmail@web53810.mail.yahoo.com> Message-ID: <42053903.8030109@tds.net> Shitiz Bansal wrote: > Hi, > > Do exe files generated by py2run on linux???i thought > it was only for windows. py2exe makes Windows executables only. http://starship.python.net/crew/theller/py2exe/ Kent > > Shitiz > --- "Jacob S." wrote: > > >>My two bits. >> >>1) Download py2exe found here >>http://py2exe.sourceforge.net/ >>2) Make a setup file -- intructions can be found >>through above link, I >>think. >>(Hey that rhymes!) >>3) Ask if you want my totally cool automation >>technique >>4) Ask more questions, go on we don't mind. >> >>HTH, >>Jacob Schmidt >> >> >>>Hi, >>> >>>I intend to create compiled python binaries on >> >>linux. >> >>>I understand that freeze can be used to do this. >>>But I have few doubts i would like to clarify. >>> >>>1. In the freeze documentation i found the lines: >>> >>>"One tricky issue: Freeze assumes that the Python >>>interpreter and >>>environment you're using to run Freeze is the same >> >>one >> >>>that would be >>>used to run your program, which should also be the >>>same whose sources >>>and installed files you will learn about in the >> >>next >> >>>section. In >>>particular, your PYTHONPATH setting should be the >> >>same >> >>>as for running >>>your program locally. (Tip: if the program >> >>doesn't >> >>>run when you type >>>"python hello.py" there's little chance of getting >> >>the >> >>>frozen version >>>to run.)" >>> >>>My intention is to create files which can be run >> >>on >> >>>Linux systems with python not installed.Do the >> >>above >> >>>lines mean that freeze can't do it(which defeats >> >>the >> >>>very pupose of the program i guess.). >>> >>>2. While compiling with freeze....it seems that it >> >>is >> >>>including all the available modules, even if they >> >>are >> >>>not required.Of course using freeze -X is one >>>option,but it being really cumbersome, is there a >>>better option available. >>> >>>In case the above issues do present a problem, is >>>there any alternative to freeze? >>> >>>Shitiz >>> >>> >>> >>>__________________________________ >>>Do you Yahoo!? >>>The all-new My Yahoo! - Get yours free! >>>http://my.yahoo.com >>> >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Sun Feb 6 00:52:50 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 00:52:53 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <4204EAB1.2050206@tds.net> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> Message-ID: Oh... and while I hate to use acronyms like this, I did indeed LOL. What happened was, I was feeding the strings I got out into the Windows calculator to check it was working. And they worked if they went backwards, and I was wondering why, and I vaguely recalled something I read in a Java book about 'endianess' and Windows being bigendian. So, there you go, thought I, the biggest bit (2**32) goes first, so Windows must be bigEndian! Oops. Next time, I'll google. Thanks Kent for clearing that up. Sandip - Just looking at this - i = 456 s = '' while i: s = str(i % 2) + s i/=2 This works, far simpler than mine, which is always infuriating, but my question is, how exactly? if I have the number 15, when it divides by 2, it will become 7. Yet no error is introduced into the binary. Argggg. Driving me nuts trying to figure out how. I thought maybe a larger odd number would do it, but no. i = 320977545 s = 10011001000011011101010001001 Chuck that into ol' calc, and I get, 320977545. Can anyone shed some more light on this? Regards, Liam Clarke On Sat, 05 Feb 2005 10:48:01 -0500, Kent Johnson wrote: > Liam, > > I think you misunderstand what endianness is. > > Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory > of the computer. This is not something you generally need to worry about in a Python program. > > For example, consider the number 0x12345678. On most modern computers this will be stored in four > consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, > 0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the > most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will > be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the > lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. > > Most programming languages will hide this detail from you most of the time. Even in assembly > language, you generally load and store integers without worrying about endianness. Math operations > just do the right thing so you don't have to worry about it. > > Endianness becomes an issue when you want to convert between representations, and when binary data > is shared between computers which may have different endianness. > > For example in a C program you might want to get the high byte of an integer when you know the > address of the integer. The desired byte will be at (address+0) or (address+3) depending on the > endianness of the hardware. > > Similarly, if an array of integers is written to a file in a binary representation (not as ASCII > strings representing the integers, but as 32-bit values), then to correctly read the file you have > to know the endianness of the data in the file. > > OK, so what does this have to do with converting a number to binary in Python? Well, nothing, > actually. First, note that 'binary representation' can mean two different things. In the description > above, I was talking about the actual bit pattern stored in the computer. Python works with binary > numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary > representation' is that of a base-2 string representation of a number. > > So if you ask, "How do I convert a number to binary?" you can mean either of these. > > The first one is trivial. If you have a decimal string representation of the number, use int() to > convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to > do anything! > > So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an > integer to a base-2 string representation?" And how do you do this? Well, you figured out one way > using the mathematical properties of integers. These operations are independent of endianness, and > so is the desired result. > > The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is > '0001001000110100'. The order of digits here is determined by our convention of writing the most > significant digits on the left, not by the endianness of the underlying computer. > > OK, this is long enough, I hope I have shed some light... > Kent > > > Liam Clarke wrote: > > Jacob - just for you, begin your agitation for the next release please ;) > > > > binstring.py, as attached. > > (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > > > > Creating this, was just a brain teaser, but I was thinking 'what if I > > wanted to make this for the standard library.' > > > > And so you can see, I had to include a flag for endianess. But that > > was really a cheap trick. If this was going into a standard library, > > I'd want to query the OS for endianess. As for the bits, once again, > > 32 bit is the norm, but 64 bit is here and spreading. > > > > Also, should it display 11111111 as 255 or 256? Both are valid, > > depending on context. > > > > Thirdly, if I can do it in 2 minutes, (well, the main part), then > > should they bother putting it in the standard library considering > > also, > > > > - How often, really, are you going to need to present a decimal or hex > > as a binary string. > > > > Lastly - this only does base 10 to base 2. Should I include a base 6 > > to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > > > > I wouldn't like to write for the standard library, because you can > > never please everyone. > > > > But yeah, feel free to use the above, just keep my doc strings and comments. > > > > Regards, > > > > Liam Clarke > > > > On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. wrote: > > > >>>The binary value is the same as the hex value. > >>>The binary representation is 000111110100, but > >>>unfortunately Python doesn't support binary in > >>>its string formatting(although it does in int()! > >> > >>Uh, question. Why not? It seems that all simple types should be included. > >>Since the computer stores it as binary, why shouldn't python be able to > >>display a > >>string of it in binary? That seems to be a short coming that should be added > >>to the > >>next release... IMHO of course. > >>Jacob Schmidt > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > > > ------------------------------------------------------------------------ > > > > ###### > > # binString.py > > # by Liam Clarke > > #(Let me know when it's included in the standard library ;-)) > > ###### > > > > """Converts a integer base 10 to a string base 2""" > > > > def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > > """ > > Integer to be converted is essential, Endianess is an optional flag; > > me being a Win32 user, Endianess is big by default, defaults to a 32-bit > > representation, most integers in Python being 32 bit. truncExcess will > > strip place-holder zeros for succintness. > > > > Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > > to start counting for zero with this. It's a simple matter to change.""" > > tempList = ['0' for x in range(bits)] > > > > for bitPlace in range(bits, -1, -1): > > if decimalInt - 2**bitPlace >= 0: > > tempList[bitPlace] = '1' > > decimalInt = decimalInt - 2**bitPlace > > if bigEndian: > > tempList.reverse() > > > > outPut = ''.join(tempList) > > > > if truncExcess: > > if bigEndian: > > outPut=outPut.lstrip('0') > > else: > > outPut=outPut.rstrip('0') > > > > return outPut > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 6 01:14:33 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 01:14:37 2005 Subject: [Tutor] Re: variation of Unique items question In-Reply-To: <42038E81.4020906@tds.net> References: <42038E81.4020906@tds.net> Message-ID: When someone joins the list, they shoudl receive a welcome email that contains - > - a clear description of what you want to do > - sample data > - desired results > - code that attempts to solve the problem as a helpful hint of how to ask questions. I have this bookmarked - http://catb.org/~esr/faqs/smart-questions.html "Never assume you are entitled to an answer. You are not; you aren't, after all, paying for the service. You will earn an answer, if you earn it, by asking a question that is substantial, interesting, and thought-provoking ? one that implicitly contributes to the experience of the community rather than merely passively demanding knowledge from others." "RTFM has a younger relative. If you get a reply that reads "STFW", the person who sent it thinks you should have Searched The F**king Web. He is almost certainly right. Go search it. (The milder version of this is when you are told "Google is your friend!")" "Q: My {program, configuration, SQL statement} doesn't work A: This is not a question, and I'm not interested in playing Twenty Questions to pry your actual question out of you ? I have better things to do. Q: How can I crack root/steal channel-ops privileges/read someone's email? A: You're a lowlife for wanting to do such things and a moron for asking a hacker to help you." Arrogant words of wisdom to ask help by. :- ) (But, some of them seem appropriate here from time to time.) Liam Clarke On Fri, 04 Feb 2005 10:02:25 -0500, Kent Johnson wrote: > I will give some credit to you for asking a clear question. You included > - a clear description of what you want to do > - sample data > - desired results > - code that attempts to solve the problem > > When all of these are present I am much more likely to respond. The first three elements especially > make a big difference. > > Kent > > Scott Melnyk wrote: > > Hello. > > > > Kent once again you have responded incredibly quickly in a most > > helpful manor. I sometimes wonder if the old reference to a > > "Kent-bot" has some truth to it. > > > > Thanks again, I will play with it and keep on going. > > > > Scott > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From sandip at lug-delhi.org Sun Feb 6 02:14:50 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sun Feb 6 02:15:00 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> Message-ID: <42056F8A.7030205@lug-delhi.org> Liam Clarke wrote: > Sandip - > > Just looking at this - > i = 456 > s = '' > while i: > s = str(i % 2) + s > i/=2 > > This works, far simpler than mine, which is always infuriating, but my > question is, how exactly? > > if I have the number 15, when it divides by 2, it will become 7. Yet > no error is introduced into the binary. Argggg. Driving me nuts trying > to figure out how. I thought maybe a larger odd number would do it, > but no. > > i = 320977545 > s = 10011001000011011101010001001 > > Chuck that into ol' calc, and I get, 320977545. > > Can anyone shed some more light on this? If you imagine the number being displayed in binary inside your calculator, i % 2, gives us the rightmost bit of the number (has to be 0 or 1) 1/=2 just right shifts the number by one. So if you consider 15, a. i % 2 will give you "1". b. So even if 15/2 gives you 7, it is ok, as the odd bit has been taken care of in (a). - Sandip From ismaelgf at adinet.com.uy Sun Feb 6 04:55:00 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Sun Feb 6 04:54:14 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> Message-ID: <42059514.7000708@adinet.com.uy> Liam Clarke wrote: >Just looking at this - >i = 456 >s = '' >while i: > s = str(i % 2) + s > i/=2 > >This works, far simpler than mine, which is always infuriating, but my >question is, how exactly? > >if I have the number 15, when it divides by 2, it will become 7. Yet >no error is introduced into the binary. Argggg. Driving me nuts trying >to figure out how. I thought maybe a larger odd number would do it, >but no. > >Can anyone shed some more light on this? > > Let's step over it : i = 15 # = 1111b s = str(i % 2) + s # 15 % 2 = 1 so now s = "1" i = i / 2 # i = 7 where's the 1 missing? s has got it s = 7 % 2 = 1 so now s = "11" i = 7/2 = 3 ... and so on... Remember when you do the base-conversion by hand: (ASCII-ese graphics, use fixed font) 15 | 2 ---- 1 7 | 2 ---- 1 3 and so on... You're basically doing the same thing Perhaps that code could be improved by not using strings: ### Warning, untested code! ### i = 15 power = 0 f = 0 while i > 0: f = f+ (i%2)**power i /= 2 power += 1 I don't know if that's faster, but I see it as a more "mathematic" way to do it. Bye Ismael From alan.gauld at freenet.co.uk Sun Feb 6 09:44:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 6 09:44:42 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> Message-ID: <056f01c50c28$1ac59a30$68b78851@xp> Liam, > Just looking at this - > i = 456 > s = '' > while i: > s = str(i % 2) + s > i/=2 > > This works, far simpler than mine, which is always infuriating, but my > question is, how exactly? This is the classic math treatment of how to calculate a binary number. Just keep dividing by two and take the remainder into the number. Almost any math textbook will cover this approach. The snag is that from a computing point of view its pretty slow so computer texts usually highlught a lookup approach 8instead. Alan G. From cyresse at gmail.com Sun Feb 6 09:59:32 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 09:59:35 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <056f01c50c28$1ac59a30$68b78851@xp> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <056f01c50c28$1ac59a30$68b78851@xp> Message-ID: Ah, yeah, gotta get me one of those textbooks. (Wait a minute, that would mean, my approach wasn't the textbook approach... /me salvages a little pride.) While I jest somewhat, that highlights a serious deficiency in my education that becomes more and more apparent, which is in maths. Sheesh, if I'd known I wanted to use maths for something I enjoyed, I would've paid attention in class. But the remainder thing - would this be why we read binary the way we do? 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach we get 100. Regards, Liam Clarke On Sun, 6 Feb 2005 08:44:42 -0000, Alan Gauld wrote: > Liam, > > > Just looking at this - > > i = 456 > > s = '' > > while i: > > s = str(i % 2) + s > > i/=2 > > > > This works, far simpler than mine, which is always infuriating, but > my > > question is, how exactly? > > This is the classic math treatment of how to calculate a binary > number. > Just keep dividing by two and take the remainder into the number. > Almost any math textbook will cover this approach. > The snag is that from a computing point of view its pretty slow so > computer texts usually highlught a lookup approach 8instead. > > Alan G. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 6 12:57:35 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 12:57:39 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <04fc01c50b61$01535960$68b78851@xp> References: <042601c50aea$e6edb410$68b78851@xp> <420404C7.2030409@pobox.com> <04fc01c50b61$01535960$68b78851@xp> Message-ID: Even more OT it would seem, but harking back to the original subject, Perl isn't looking too bad because I've been working through Java tonight. $j = ; is relatively intuitive for a child of Unix, and it's also documented. BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); String j = keyboard.readline(); is not intuitive, and is hidden very well in the bowels of Sun's API's. Scary, when a language makes me think Perl would be nicer. : ) Heh. Oh, and whoever recommended Eclipse to me? Thank you very much. On Sat, 5 Feb 2005 08:59:30 -0000, Alan Gauld wrote: > > > Surely you jest, Alan. :-) > > Smiley noted but... > > > Both perl and awk are turing complete, hence anything perl can do, > awk > > can do as well. > > This is a popular misconception. > > Being Turing complete simply means you can implement any algorithm. > But if the language doesn't provide I/O access for example it is > impossible to write a device driver, or a comms stack, or any of > a host of other low level programs. awk is non extendable (unless > you have the source code!) so you can't do those things. Perl is > not only extendable but actually comes wth a heap of those kinds > of features that awk just doesn't have. And no amount of clever > algorithms can compensate. Awk was designed for one task which it > does spectacularly well but it was never intended for general > purpose use. > > I/O is just one example, there are meny more... > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Sun Feb 6 13:27:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 6 13:27:39 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <056f01c50c28$1ac59a30$68b78851@xp> Message-ID: <42060D36.8090500@tds.net> Liam Clarke wrote: > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach > we get 100. ?? 4 (decimal) is 100 (binary). Not because of how the conversion algorithm works, but because that is how we write numbers. The least-significant digit is always the rightmost digit. 001 is 1 in every number base >= 2. Actually, generating the digits from the right complicates the algorithm quite a bit. It's hidden in the Python version, but s = str(i % 2) + s is a relatively expensive operation here - it has to copy all of s to make room for the new digit. Kent From maxnoel_fr at yahoo.fr Sun Feb 6 13:28:51 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Feb 6 13:28:59 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <056f01c50c28$1ac59a30$68b78851@xp> Message-ID: <5c246c73b673fe2ae8baaa9e7df08ac2@yahoo.fr> On Feb 6, 2005, at 08:59, Liam Clarke wrote: > Ah, yeah, gotta get me one of those textbooks. > (Wait a minute, that would mean, my approach wasn't the textbook > approach... /me salvages a little pride.) > > While I jest somewhat, that highlights a serious deficiency in my > education that becomes more and more apparent, which is in maths. > Sheesh, if I'd known I wanted to use maths for something I enjoyed, I > would've paid attention in class. > > But the remainder thing - would this be why we read binary the way we > do? > > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach > we get 100. > > > Regards, > > Liam Clarke Yes, it is 100. The most significant bit (i.e. the highest power of 2) is on the left, just as the most significant digit (matching the highest power of 10) is on the left when representing base-10 numbers: 415 is 4*10^2 + 1*10^1 + 5*10^0. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From mark.kels at gmail.com Sun Feb 6 15:18:13 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sun Feb 6 15:18:17 2005 Subject: [Tutor] The Tkinter Text widget and .get() Message-ID: Hi all. As I understand, .get() has to get an index argument to get the text from the Text index... The problem is that I dont realy understand what is this index thing and what index do I need to give to the function so I'll get all the text in the widget. Any ideas ?? Thanks ! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From sigurd at 12move.de Sun Feb 6 15:23:27 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Sun Feb 6 15:29:46 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <42060D36.8090500@tds.net> (Kent Johnson's message of "Sun, 06 Feb 2005 07:27:34 -0500") References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <056f01c50c28$1ac59a30$68b78851@xp> <42060D36.8090500@tds.net> Message-ID: On 6 Feb 2005, kent37@tds.net wrote: > Actually, generating the digits from the right complicates the algorithm quite > a bit. It's hidden in > the Python version, but s = str(i % 2) + s is a relatively expensive operation here - it has to copy > all of s to make room for the new digit. Because of that the standard answer is to write: s = [] s.append(...) return ''.join(s) Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld at freenet.co.uk Sun Feb 6 16:10:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Feb 6 16:10:27 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net><056f01c50c28$1ac59a30$68b78851@xp> Message-ID: <058101c50c5e$0736faf0$68b78851@xp> > While I jest somewhat, that highlights a serious deficiency in my > education that becomes more and more apparent, which is in maths. Yes, its a sad fact. Good programming beyond basics does require a modicum of maths. You can learnn enough to do useful things without math, but there reaches a point when math becomes essential. Its no coincidence that at university Computing was traditionally (up till the late 70's at least) a branch of mathematics. > But the remainder thing - would this be why we read binary the way we do? > > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above approach > we get 100. Not really. The reason we read 4 as 100 is the same reason we read 400 as 400 instead of 004 - we traditionally put the most significant part tothe left since we (in English at least) read from left to right. 400 = 4x10**2 + 0x10**1 + 0x10**0 110 = 1x2**2 + 0x2**1 + 0x2**0 But if we convert back again we can generate the number 400 from the value 400 by the same technique we saw for binary: 400/10 = 40 rem 0 40/10 = 4 rem 0 4/10 = 0 rem 4 So reading remainders bottom up we get 400, which is the decimal representation of 400! :-) So the algorithm is identical, we can write a generic function to convert a value into a representation if we pass in the value and base. Alan G. From askoose at sandia.gov Sun Feb 6 18:27:18 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Sun Feb 6 18:27:48 2005 Subject: [Tutor] Percolation model in python Message-ID: Hello, I have been working with some high school students to create a model of small pox transmission. I am somewhat new to python (my programming experience is in f77) so I have borrowed parts of Danny's code that he posted for the Game of Life. I have included the code that we are using below. I have two questions. Once a MxN world is generated how would you search for nearest neighbors (to see who is connected) and then color the '*' so it's easier to see who is connected and who isn't. For a definition of percolation theory- http://en.wikipedia.org/wiki/Percolation_theory or for the wolfram fans http://mathworld.wolfram.com/PercolationTheory.html Thanks, Ara CODE STARTS HERE: print """ Please pick your option: 1) Percolation model for Small Pox 2) 3) Instructions 4) Exit """ option = raw_input("Which option[1,2,3,4]? ") if option == '1': import random perc = raw_input("Please enter a thresold between 0-1. ") perc = float(perc) ### PERSON, EMPTY = '*', '.' ### ### def percolation(perc): randval = random.random() if randval > perc: return EMPTY else: return PERSON def make_random_world(M, N): """Constructs a new random game world of size MxN.""" world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def print_world(world): """Prints out a string representation of a world.""" M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print n = int(raw_input("Please enter a n dimension. ")) m = int(raw_input("Please enter a m dimension. ")) raw_input("Press return to make a world") print_world(make_random_world(n,m)) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050206/94af87cd/attachment.html From cyresse at gmail.com Sun Feb 6 19:52:02 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 19:52:05 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <058101c50c5e$0736faf0$68b78851@xp> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <056f01c50c28$1ac59a30$68b78851@xp> <058101c50c5e$0736faf0$68b78851@xp> Message-ID: Ah, thanks all. I wasn't thinking of base 2 numbers like base 10 - when you describe it like that, I get i. (100 = 10^2 + 0*10^1 + 0*10^0) I was thinking strictly in terms of a base 10 number described by flags for each power of 2, which (to me) would logically start from 2^0 and go right. And yeah, I intend to study computer science as I can, so it's definitely the maths papers first. I'm working through my little brother's textbook on matrix algebra at the moment. Ick. Regards, Liam Clarke On Sun, 6 Feb 2005 15:10:42 -0000, Alan Gauld wrote: > > While I jest somewhat, that highlights a serious deficiency in my > > education that becomes more and more apparent, which is in maths. > > Yes, its a sad fact. Good programming beyond basics does require a > modicum of maths. You can learnn enough to do useful things without > math, but there reaches a point when math becomes essential. Its > no coincidence that at university Computing was traditionally > (up till the late 70's at least) a branch of mathematics. > > > But the remainder thing - would this be why we read binary the way > we do? > > > > 4 is 001 (on a continuum of 2^0 to 2^n), but using the above > approach > > we get 100. > > Not really. The reason we read 4 as 100 is the same reason we > read 400 as 400 instead of 004 - we traditionally put the most > significant part tothe left since we (in English at least) read > from left to right. > > 400 = 4x10**2 + 0x10**1 + 0x10**0 > > 110 = 1x2**2 + 0x2**1 + 0x2**0 > > But if we convert back again we can generate the number 400 > from the value 400 by the same technique we saw for binary: > > 400/10 = 40 rem 0 > 40/10 = 4 rem 0 > 4/10 = 0 rem 4 > > So reading remainders bottom up we get 400, which is > the decimal representation of 400! :-) > > So the algorithm is identical, we can write a generic > function to convert a value into a representation if we > pass in the value and base. > > Alan G. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sun Feb 6 19:58:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sun Feb 6 19:58:38 2005 Subject: [Tutor] The Tkinter Text widget and .get() In-Reply-To: References: Message-ID: >From http://effbot.org/books/tkinterbook/text.htm "Indexes Indexes are used to point to positions within the text handled by the text widget. Like Python sequence indexes, text widget indexes correspond to positions between the actual characters. Tkinter provides a number of different index types: * line/column ("line.column") * line end ("line.end") * INSERT * CURRENT * END * user-defined marks * user-defined tags ("tag.first", "tag.last") * selection (SEL_FIRST, SEL_LAST) * window coordinate ("@x,y") * embedded object name (window, images) * expressions" I believe you want textWidget.get(1.0, END) But I seriously recommend the above book. 1.0 is line 1, column 0, to END of text. HTH Liam Clarke On Sun, 6 Feb 2005 16:18:13 +0200, Mark Kels wrote: > Hi all. > > As I understand, .get() has to get an index argument to get the text > from the Text index... > The problem is that I dont realy understand what is this index thing > and what index do I need to give to the function so I'll get all the > text in the widget. > Any ideas ?? > > Thanks ! > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From flaxeater at yahoo.com Sun Feb 6 19:59:11 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun Feb 6 19:59:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050206185911.85201.qmail@web54303.mail.yahoo.com> Jacob S. wrote: >> aFuncList=[] >> def x(): >> print "one" >> aFuncList.append(x) >> def x(): >> print "two" >> aFuncList.append(x) >> def x(): >> print "three" >> aFuncList.append(x) >> for item in aFuncList: >> item() > > > Okay, for this problem (it can be altered otherwise) > > def makefunct(stri): > def x(): > print stri > return x > aFuncList = [makefunct('one'),makefunct('two'),makefunct('three')] > for item in aFuncList: > item() > > It's shorter, it works and it looks cool. > Thanks to Jeff Shannon for the backbone of this example. My intent in showing the above code was not to really print one two three, but to show that a function doesn't care what it's called. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at freenet.co.uk Mon Feb 7 01:22:33 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 01:22:15 2005 Subject: [Tutor] The Tkinter Text widget and .get() References: Message-ID: <05a801c50cab$1e9e02e0$68b78851@xp> > As I understand, .get() has to get an index argument to get the text > from the Text index... Thats true. > The problem is that I dont realy understand what is this index thing Thats not surprising the Text widget index in Tk (its not really a Tkinter thing, its part of the underlying Tk toolkit...) is just a little bit weird! > and what index do I need to give to the function so I'll get all the > text in the widget. THe magic incantation (or one option, there are various ways) is: txt.get(1.0,END) Where 1.0 means first line, zeroth character (ie before the first!) is the starting position and END is the ending position. The index is a conceptual cursor that sits *between* characters. Thus for a line like: Here is a line If we only wanted the second word we'd use get(1.5, 1.7) This is explained in both the Tkinter documentation (but slightly vaguely), and,more precisely in the Tk documentation. AS with most things Python the best bet is to experiment at the >>> prompt till you get it right! There are some examples of using the Text widget in my tutorial in both the Event Driven Programming and Case Study topics. Specifically the doReset() method inthe case study uses indexing to delete the text in a Text box and doAnalyze shown text being appended (inserted at END). HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From reed at intersiege.com Mon Feb 7 07:58:57 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Mon Feb 7 07:59:42 2005 Subject: [Tutor] manipulating a file Message-ID: I want to read the httpd-access.log and remove any oversized log records I quickly tossed this script together. I manually mv-ed log to log.bak and touched a new logfile. running the following with print i uncommented does print each line to stdout. but it doesn't write to the appropriate file... a) what am I missing? b) is there a less expensive way to do it? c) I originally wanted to delete lines over 2085 in length but couldn't find a way to do that... did I miss it? Thanks #!/usr/local/bin/python import os srcfile = open('/var/log/httpd-access.log.bak', 'r') dstfile = open('/var/log/httpd-access.log', 'w') while 1: lines = srcfile.readlines() if not lines: break # print lines for i in lines: if len(i) < 2086: #print i dstfile.write(i) srcfile.close() dstfile.close() From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 08:37:45 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 08:37:50 2005 Subject: [Tutor] manipulating a file In-Reply-To: Message-ID: On Mon, 7 Feb 2005, Reed L. O'Brien wrote: > I want to read the httpd-access.log and remove any oversized log records > > I quickly tossed this script together. I manually mv-ed log to log.bak > and touched a new logfile. > > running the following with print i uncommented does print each line to > stdout. but it doesn't write to the appropriate file... Hello! Let's take a look at the program again: ### import os srcfile = open('/var/log/httpd-access.log.bak', 'r') dstfile = open('/var/log/httpd-access.log', 'w') while 1: lines = srcfile.readlines() if not lines: break for i in lines: if len(i) < 2086: dstfile.write(i) srcfile.close() dstfile.close() ### > a) what am I missing? > b) is there a less expensive way to do it? Hmmm... I don't see anything offhand that prevents httpd-access.log from containing the lines you expect. Do you get any error messages, like permission problems, when you run the program? Can you show us how you are running the program, and how you are checking that the resulting file is empty? Addressing the question on efficiency and expense: yes. The program at the moment tries to read all lines into memory at once, and this is expensive if the file is large. Let's fix this. In recent versions of Python, we can modify file-handling code from: ### lines = somefile.readlines() for line in lines: ... ### to this: ### for line in somefile: ... ### That is, we don't need to extract a list of 'lines' out of a file. Python allows us to loop directly across a file object. We can find more details about this in the documentation on "Iterators" (PEP 234): http://www.python.org/peps/pep-0234.html Iterators are a good thing to know, since Python's iterators are deeply rooted in the language design. (Even if it they were retroactively embedded. *grin*) A few more comments: the while loop appears unnecessary, since on the second run-through the loop, we'll have already read all the lines out of the file. (I am assuming that nothing is writing to the backup file at the time.) If the body of a while loop just runs once, we don't need a loop. This simplifies the code down to: ### srcfile = open('/var/log/httpd-access.log.bak', 'r') dstfile = open('/var/log/httpd-access.log', 'w') for line in srcfile: if len(line) < 2086: dstfile.write(line) srcfile.close() dstfile.close() ### I don't see anything else here that causes the file writing to fail. If you can tell us more information on how you're checking the program's effectiveness, that may give us some more clues. Best of wishes to you! From tony at tcapp.com Mon Feb 7 10:03:08 2005 From: tony at tcapp.com (Tony Cappellini) Date: Mon Feb 7 10:03:28 2005 Subject: [Tutor] Iterating over multiple lists- options Message-ID: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> I'm trying to generate an HTML table, from multiple lists. There are 4 lists total, each of which *may* have a different length from the other lists. Each list has been stored in a master dictionary. North=[Bill, Bob, Sue, Mary] South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] etc d1={'North':North, 'South':South, 'East':East, 'West':West] I want to iterate over all the lists a the same time, so I can populate an html table. This is approximately what the HTML table should look like, but the lists can be in any order, top to bottom, and left to right. South North East West Tim Bill May Ellen Tom Bob Mick Jim Sue Ron John Mary Keith Carl Joey Evan Rich Looking through my books on Python I've found examples for zip() and map() both of which have serious shortcomings That being, both of these functions can truncate the data, depending on certain conditions When iterating over multiple lists, it is fine if the mechanism returns an empty string , or None for a non-existing list item. I just wont display anything in the HTML table for missing items. I know how to create the HTML table, statically. The problem is being able to fill the table in one pass (preferably), which means my program would need to iterate over more than one list at the same time. Even using the range to generate an index has different effects, depending on the order in which the lists are referenced in the for loop. Are there any other options available for iterating over multiple lists ? From shitizb at yahoo.com Mon Feb 7 10:18:52 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 7 10:18:55 2005 Subject: [Tutor] manipulating a file In-Reply-To: Message-ID: <20050207091852.87090.qmail@web53808.mail.yahoo.com> Hi, I do see a problem. The script is fine, the problem lies else where. Your script is trying to write log.bak to log, it should b other way round. i.e.... srcfile = open('/var/log/httpd-access.log', 'r') dstfile = open('/var/log/httpd-access.log.bak', 'w') hope that fixes it. About the efficiency, why do u need python at all... How abt a simple shell command.... cat httpd-access.log>>log.bak Shitiz --- Danny Yoo wrote: > > > On Mon, 7 Feb 2005, Reed L. O'Brien wrote: > > > I want to read the httpd-access.log and remove any > oversized log records > > > > I quickly tossed this script together. I manually > mv-ed log to log.bak > > and touched a new logfile. > > > > running the following with print i uncommented > does print each line to > > stdout. but it doesn't write to the appropriate > file... > > > Hello! > > Let's take a look at the program again: > > ### > import os > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > for i in lines: > if len(i) < 2086: > dstfile.write(i) > srcfile.close() > dstfile.close() > ### > > > a) what am I missing? > > b) is there a less expensive way to do it? > > Hmmm... I don't see anything offhand that prevents > httpd-access.log from > containing the lines you expect. Do you get any > error messages, like > permission problems, when you run the program? > > Can you show us how you are running the program, and > how you are checking > that the resulting file is empty? > > > Addressing the question on efficiency and expense: > yes. The program at > the moment tries to read all lines into memory at > once, and this is > expensive if the file is large. Let's fix this. > > > In recent versions of Python, we can modify > file-handling code from: > > ### > lines = somefile.readlines() > for line in lines: > ... > ### > > to this: > > ### > for line in somefile: > ... > ### > > That is, we don't need to extract a list of 'lines' > out of a file. > Python allows us to loop directly across a file > object. We can find more > details about this in the documentation on > "Iterators" (PEP 234): > > http://www.python.org/peps/pep-0234.html > > Iterators are a good thing to know, since Python's > iterators are deeply > rooted in the language design. (Even if it they > were retroactively > embedded. *grin*) > > > A few more comments: the while loop appears > unnecessary, since on the > second run-through the loop, we'll have already read > all the lines out of > the file. (I am assuming that nothing is writing to > the backup file at > the time.) If the body of a while loop just runs > once, we don't need a > loop. > > This simplifies the code down to: > > ### > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > for line in srcfile: > if len(line) < 2086: > dstfile.write(line) > srcfile.close() > dstfile.close() > ### > > > I don't see anything else here that causes the file > writing to fail. If > you can tell us more information on how you're > checking the program's > effectiveness, that may give us some more clues. > > Best of wishes to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From shitizb at yahoo.com Mon Feb 7 10:27:14 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 7 10:27:18 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> Message-ID: <20050207092714.75163.qmail@web53807.mail.yahoo.com> Hi, My solution might raise purist's eyebrows but here it goes... How about using a try loop every time you read from the list. try: x=list[someno] except: x=nothing(or whatever) This goes on till the all lists start returning none. for shorter lists try throws an index out of range exception which is caught by except. Shitiz --- Tony Cappellini wrote: > > > I'm trying to generate an HTML table, from multiple > lists. > > There are 4 lists total, each of which *may* have a > different length from > the other lists. > Each list has been stored in a master dictionary. > > > North=[Bill, Bob, Sue, Mary] > South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', > 'Rich'] > etc > > d1={'North':North, 'South':South, 'East':East, > 'West':West] > > > I want to iterate over all the lists a the same > time, so I can populate an > html table. > This is approximately what the HTML table should > look like, but the lists > can be in any order, top to bottom, and left to > right. > > South North East West > > Tim Bill May Ellen > Tom Bob Mick > Jim Sue Ron > John Mary Keith > Carl Joey > Evan > Rich > > > Looking through my books on Python I've found > examples for zip() and map() > both of which have serious shortcomings > That being, both of these functions can truncate the > data, depending on > certain conditions > > When iterating over multiple lists, it is fine if > the mechanism returns an > empty string , or None for a non-existing list item. > I just wont display anything in the HTML table for > missing items. > I know how to create the HTML table, statically. The > problem is being able > to fill the table in one pass (preferably), which > means my program would > need to iterate over > more than one list at the same time. > > Even using the range to generate an index has > different effects, depending > on the order in which the lists are referenced in > the for loop. > > Are there any other options available for iterating > over multiple lists ? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 10:32:09 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 10:32:13 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> Message-ID: On Mon, 7 Feb 2005, Tony Cappellini wrote: > There are 4 lists total, each of which *may* have a different length > from the other lists. Each list has been stored in a master dictionary. > > North=[Bill, Bob, Sue, Mary] > South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] > etc > > I want to iterate over all the lists a the same time, so I can populate an > html table. [some text cut] > Looking through my books on Python I've found examples for zip() and map() > both of which have serious shortcomings Hi Tony, Out of curiosity, if it's not possible to run zip() directly on the lists that you have, can you bend the lists so that zip() will fit? Here's a quick function that should force a certain length on an iterator: ### def ipad(iterable, length, sentinel=None): """Returns a new iterator whose elements are taken from iterator. If there are fewer elements than 'length', we pad the rest with sentinels. Assumptions: len(iterator) <= length. The result from ipad never truncates the elements out of i, so the iterator always goes through all the elements in iterable. """ i = 0 for thing in iterable: yield thing i = i + 1 while i < length: yield sentinel i = i + 1 ### For example: ### >>> names = ['knuth', 'mcconnell', 'bentley', 'witten'] >>> for n in ipad(names, 7): ... print n ... knuth mcconnell bentley witten None None None >>> >>> >>> for n in ipad(names, 2): ... print n ... knuth mcconnell bentley witten ### So we could use something like ipad() to bring all the lists to the same length, and that should make it suitable for zip(). Hope this helps! From kent37 at tds.net Mon Feb 7 12:03:50 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 12:03:55 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> References: <6.1.2.0.0.20050207004003.01f59e78@mail.yamato.com> Message-ID: <42074B16.8080302@tds.net> Tony Cappellini wrote: > > > I'm trying to generate an HTML table, from multiple lists. > > There are 4 lists total, each of which *may* have a different length > from the other lists. > Each list has been stored in a master dictionary. > > > North=[Bill, Bob, Sue, Mary] > South=['Tim', ''Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] > etc > > d1={'North':North, 'South':South, 'East':East, 'West':West] > > > I want to iterate over all the lists a the same time, so I can populate > an html table. > This is approximately what the HTML table should look like, but the > lists can be in any order, top to bottom, and left to right. > > South North East West > > Tim Bill May Ellen > Tom Bob Mick > Jim Sue Ron > John Mary Keith > Carl Joey > Evan > Rich > > > Looking through my books on Python I've found examples for zip() and > map() both of which have serious shortcomings map(None, North, South, East West) does exactly what you want: >>> North=['Bill', 'Bob', 'Sue', 'Mary'] >>> South=['Tim', 'Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] >>> map(None, North, South) [('Bill', 'Tim'), ('Bob', 'Tom'), ('Sue', 'Jim'), ('Mary', 'John'), (None, 'Carl'), (None, 'Evan'), (None, 'Rich')] > That being, both of these functions can truncate the data, depending on > certain conditions I don't think that is true for map(); what conditions are you thinking of? Kent From ch_chandu9 at yahoo.com Mon Feb 7 12:09:14 2005 From: ch_chandu9 at yahoo.com (chandrasekhar cherukuri) Date: Mon Feb 7 12:09:18 2005 Subject: [Tutor] where do we use acquisition ? Message-ID: <20050207110914.12461.qmail@web21201.mail.yahoo.com> I completely understood what is acquisition. Now can some one explain me where it is useful and give some contextual examples where we can see the power of acquisition. regards chandu. __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From kent37 at tds.net Mon Feb 7 13:37:26 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 13:37:30 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <20050207110914.12461.qmail@web21201.mail.yahoo.com> References: <20050207110914.12461.qmail@web21201.mail.yahoo.com> Message-ID: <42076106.80806@tds.net> chandrasekhar cherukuri wrote: > I completely understood what is acquisition. I don't :-) Can you tell us what you mean by acquisition? I see Zope has something called acquisition; I can't think of anything by that name in standard Python... Kent Now can > some one explain me where it is useful and give some > contextual examples where we can see the power of > acquisition. > > regards > chandu. From kent37 at tds.net Mon Feb 7 14:00:15 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 14:00:17 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <20050207125053.25163.qmail@web21201.mail.yahoo.com> References: <20050207125053.25163.qmail@web21201.mail.yahoo.com> Message-ID: <4207665F.5020908@tds.net> chandrasekhar cherukuri wrote: > http://zope.org/Documentation/Books/ZopeBook/2_6Edition/ScriptingZope.stx/Acquisition.stx > > http://zope.org/Members/crazybrett/acquisition > > Hope there is no sarcasm in this. No, none at all. A light irony, maybe. When I first read your post, I thought, "I have no idea what acquisition is". I thought it was funny that you completely understand it but I am clueless about it. I had to google 'python acquisition' to see that Zope uses that term. I hope someone else here has more of a clue than me. If not, you might want to try a Zope-specific mailing list. Kent > > > --- Kent Johnson wrote: > > >>chandrasekhar cherukuri wrote: >> >>>I completely understood what is acquisition. >> >>I don't :-) >>Can you tell us what you mean by acquisition? I see >>Zope has something called acquisition; I can't >>think of anything by that name in standard Python... >> >>Kent >> >>Now can >> >>>some one explain me where it is useful and give >> >>some >> >>>contextual examples where we can see the power of >>>acquisition. >>> >>>regards >>>chandu. >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail > From pierre.barbier at cirad.fr Mon Feb 7 14:09:50 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon Feb 7 14:07:51 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <4207665F.5020908@tds.net> References: <20050207125053.25163.qmail@web21201.mail.yahoo.com> <4207665F.5020908@tds.net> Message-ID: <4207689E.9010501@cirad.fr> I may say this is no subject for the Python _tutor_ list ! You'll at least want to post this message to the comp.lang.python newsgroup. Pierre Kent Johnson a ?crit : > chandrasekhar cherukuri wrote: > >> http://zope.org/Documentation/Books/ZopeBook/2_6Edition/ScriptingZope.stx/Acquisition.stx >> >> >> http://zope.org/Members/crazybrett/acquisition >> >> Hope there is no sarcasm in this. > > > No, none at all. A light irony, maybe. When I first read your post, I > thought, "I have no idea what acquisition is". I thought it was funny > that you completely understand it but I am clueless about it. I had to > google 'python acquisition' to see that Zope uses that term. > > I hope someone else here has more of a clue than me. If not, you might > want to try a Zope-specific mailing list. > > Kent > >> >> >> --- Kent Johnson wrote: >> >> >>> chandrasekhar cherukuri wrote: >>> >>>> I completely understood what is acquisition. >>> >>> >>> I don't :-) >>> Can you tell us what you mean by acquisition? I see >>> Zope has something called acquisition; I can't think of anything by >>> that name in standard Python... >>> >>> Kent >>> >>> Now can >>> >>>> some one explain me where it is useful and give >>> >>> >>> some >>> >>>> contextual examples where we can see the power of >>>> acquisition. >>>> >>>> regards >>>> chandu. >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> >> >> >> >> __________________________________ Do you Yahoo!? Yahoo! Mail - You >> care about security. So do we. http://promotions.yahoo.com/new_mail >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From karen.leever at falw.vu.nl Mon Feb 7 14:40:06 2005 From: karen.leever at falw.vu.nl (Karen Leever) Date: Mon Feb 7 14:40:09 2005 Subject: [Tutor] calling subroutines into program Message-ID: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Hello, I've been writing some small python programs that basically do function analysis on the (x,y) output of a fortran code called COBRA. The COBRA output (basin.out) is the shape of a flexed beam, of which I calculate the 0-crossing, x and y of max. amplitude, and cross sectional area between function and y=0. I managed to make python calculate these things, so it actually works. No problems there. However, I'd like to make the format a bit more elegant. Each python program consists of several components, some of which occur in each of the programs. These components comprise: (1) reading the COBRA output file and write the contents to an array, (2) reading a second COBRA output file for reference values. See below for an example. How can I refer in my programs to these components without actually incorporating them in the program? I don't see how I could define them as functions. And "import 'component'.py" does not work either: I tried this but it will not recognize the array arr_xy (defined in 'component'.py) later on. thanks for suggestion or reference, Karen example of (1): --------------------------------------------------------- #this part of the program reads the file basin.out (the data we want to analyze) and changes its contents to the array arr_xy #layout of basin.out: #1 -950.00 10.00 200 > this line contains start, interval and number of x values; # 0.000000E+00 > remainder is a column of y values # -1.931787E-07 # -5.713295E-07 # -9.322559E-07 # -1.071361E-06 # -7.801342E-07 # ..... import re #open the (x,y) output file cobra_xy_file = open('/home/tecguest/leek/Suncobra/Screen/basin.out') #read first line and change it to a list so it can be read by the program firstline = cobra_xy_file.readline() p = re.compile(r'\s+') list = p.split(firstline) #from the list defined above, x-values have to be calculated. #the list contains strings that are converted to integers before they can be used in further calculations start = int(float(list[1])) interval = int(float(list[2])) n = int(float(list[3])) stop = start + n*interval arr_x = range(start, stop, interval) #the calculated x-values are stored in 1D array arr_x (note, fake array, is really a list) #the list of calculated x values, together with the y values in the cobra_xy_file have to be put in an array: arr_xy #first define the new array: arr_xy = [] #then fill the array with the x and y values: for i in range(0, len(arr_x)): sub_arr_xy = [] sub_arr_xy.append(arr_x[i]) sub_arr_xy.append(float(cobra_xy_file.readline())) arr_xy.append(sub_arr_xy) #print 'These are the first values from the x,y file:' #print arr_xy[:5] #print cobra_xy_file.close -------------------------------------------------------- >>> please note new phone and fax number <<< ---------------------------------------------------- Karen Leever Department of Tectonics Faculty of Earth and Life Sciences Vrije Universiteit Amsterdam De Boelelaan 1085 1081 HV Amsterdam The Netherlands tel: +31 20 598 7278 fax: +31 20 598 9943 @: karen.leever@falw.vu.nl ---------------------------------------------------- From cyresse at gmail.com Mon Feb 7 14:45:37 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 7 14:45:40 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Message-ID: Hi Karen, if I have a file called foo.py = def la() return "la" x = 15 I can do the following in bar.py = import foo #Notice there's no .py extension! j = foo.la() print j print foo.x > la > 15 Hope that helps Liam Clarke On Mon, 07 Feb 2005 14:40:06 +0100, Karen Leever wrote: > Hello, > > I've been writing some small python programs that basically do function > analysis on the (x,y) output of a fortran code called COBRA. > The COBRA output (basin.out) is the shape of a flexed beam, of which I > calculate the 0-crossing, x and y of max. amplitude, and cross sectional > area between function and y=0. > > I managed to make python calculate these things, so it actually works. No > problems there. > However, I'd like to make the format a bit more elegant. Each python > program consists of several components, some of which occur in each of the > programs. These components comprise: (1) reading the COBRA output file and > write the contents to an array, (2) reading a second COBRA output file for > reference values. See below for an example. > > How can I refer in my programs to these components without actually > incorporating them in the program? > I don't see how I could define them as functions. > And "import 'component'.py" does not work either: I tried this but it will > not recognize the array arr_xy (defined in 'component'.py) later on. > > thanks for suggestion or reference, > > Karen > > example of (1): > --------------------------------------------------------- > #this part of the program reads the file basin.out (the data we want to > analyze) and changes its contents to the array arr_xy > #layout of basin.out: > #1 -950.00 10.00 200 > this line contains start, interval and > number of x values; > # 0.000000E+00 > remainder is a column of y values > # -1.931787E-07 > # -5.713295E-07 > # -9.322559E-07 > # -1.071361E-06 > # -7.801342E-07 > # ..... > > import re > > #open the (x,y) output file > cobra_xy_file = open('/home/tecguest/leek/Suncobra/Screen/basin.out') > > #read first line and change it to a list so it can be read by the program > firstline = cobra_xy_file.readline() > p = re.compile(r'\s+') > list = p.split(firstline) > > #from the list defined above, x-values have to be calculated. > #the list contains strings that are converted to integers before they can > be used in further calculations > start = int(float(list[1])) > interval = int(float(list[2])) > n = int(float(list[3])) > stop = start + n*interval > arr_x = range(start, stop, interval) #the calculated x-values are stored > in 1D array arr_x (note, fake array, is really a list) > > #the list of calculated x values, together with the y values in the > cobra_xy_file have to be put in an array: arr_xy > #first define the new array: > arr_xy = [] > > #then fill the array with the x and y values: > for i in range(0, len(arr_x)): > sub_arr_xy = [] > sub_arr_xy.append(arr_x[i]) > sub_arr_xy.append(float(cobra_xy_file.readline())) > arr_xy.append(sub_arr_xy) > > #print 'These are the first values from the x,y file:' > #print arr_xy[:5] > #print > > cobra_xy_file.close > -------------------------------------------------------- > > >>> please note new phone and fax number <<< > ---------------------------------------------------- > Karen Leever > Department of Tectonics > Faculty of Earth and Life Sciences > Vrije Universiteit Amsterdam > De Boelelaan 1085 > 1081 HV Amsterdam > The Netherlands > > tel: +31 20 598 7278 > fax: +31 20 598 9943 > @: karen.leever@falw.vu.nl > ---------------------------------------------------- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Feb 7 15:02:32 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 7 15:02:42 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Message-ID: Actually, if I may rewrite some sections of your code - > > example of (1): > > --------------------------------------------------------- > > #this part of the program reads the file basin.out (the data we want to > > analyze) and changes its contents to the array arr_xy > > #layout of basin.out: > > #1 -950.00 10.00 200 > this line contains start, interval and > > number of x values; > > # 0.000000E+00 > remainder is a column of y values > > # -1.931787E-07 > > # -5.713295E-07 > > # -9.322559E-07 > > # -1.071361E-06 > > # -7.801342E-07 > > # ..... So to clarify the first line has 4 values? Are they likely to be separated by whitespace characters other than space? If not, then you could just use a = firstline.split(" ") instead of > > p = re.compile(r'\s+') > > list = p.split(firstline) >start = int(float(list[1])) > interval = int(float(list[2])) > n = int(float(list[3])) list[1] is a string, so if I'm not missing something, start = int(list[1]) will do just fine. >>arr_x = range(start, stop, interval) #the calculated x-values are stored > > in 1D array arr_x (note, fake array, is really a list) > > > > #the list of calculated x values, together with the y values in the > > cobra_xy_file have to be put in an array: arr_xy > > #first define the new array: > > arr_xy = [] > > > > #then fill the array with the x and y values: > > for i in range(0, len(arr_x)): > > sub_arr_xy = [] > > sub_arr_xy.append(arr_x[i]) > > sub_arr_xy.append(float(cobra_xy_file.readline())) > > arr_xy.append(sub_arr_xy) arr_xy=[] for i in range(start, stop, interval): sub_arr_xy = [] sub_arr_xy.append(i) sub_arr_xy.append(float(cobra_xy_file.readline() ) ) arr_xy.append(sub_arr_xy) Should do the same thing. Good luck, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 7 15:04:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 15:04:56 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Message-ID: <42077586.3080900@tds.net> Karen, Put all of your code into a function, maybe called import_cobra(). The function should take the path to the basic.out file as a parameter and return the array of data. So it will look something like this: def import_cobra(basicPath): cobra_xy_file = open(basicPath) # All the same code as below all the way to... cobra_xy_file.close() # Oops, you were missing parentheses here! # End with a return statement that passes the array back to the caller return arr_xy If you put this in a file called component.py (you might want to think of a more descriptive name, maybe CobraUtils.py?), then in a client program you can do this: from component import import_cobra arr_xy = import_cobra Now you can do what you want with arr_xy. Kent Karen Leever wrote: > Hello, > > I've been writing some small python programs that basically do function > analysis on the (x,y) output of a fortran code called COBRA. > The COBRA output (basin.out) is the shape of a flexed beam, of which I > calculate the 0-crossing, x and y of max. amplitude, and cross sectional > area between function and y=0. > > I managed to make python calculate these things, so it actually works. > No problems there. > However, I'd like to make the format a bit more elegant. Each python > program consists of several components, some of which occur in each of > the programs. These components comprise: (1) reading the COBRA output > file and write the contents to an array, (2) reading a second COBRA > output file for reference values. See below for an example. > > How can I refer in my programs to these components without actually > incorporating them in the program? > I don't see how I could define them as functions. > And "import 'component'.py" does not work either: I tried this but it > will not recognize the array arr_xy (defined in 'component'.py) later on. > > thanks for suggestion or reference, > > Karen > > > example of (1): > --------------------------------------------------------- > #this part of the program reads the file basin.out (the data we want to > analyze) and changes its contents to the array arr_xy > #layout of basin.out: > #1 -950.00 10.00 200 > this line contains start, interval and > number of x values; > # 0.000000E+00 > remainder is a column of y values > # -1.931787E-07 > # -5.713295E-07 > # -9.322559E-07 > # -1.071361E-06 > # -7.801342E-07 > # ..... > > import re > > #open the (x,y) output file > cobra_xy_file = open('/home/tecguest/leek/Suncobra/Screen/basin.out') > > > #read first line and change it to a list so it can be read by the program > firstline = cobra_xy_file.readline() > p = re.compile(r'\s+') > list = p.split(firstline) > > > #from the list defined above, x-values have to be calculated. > #the list contains strings that are converted to integers before they > can be used in further calculations > start = int(float(list[1])) > interval = int(float(list[2])) > n = int(float(list[3])) > stop = start + n*interval > arr_x = range(start, stop, interval) #the calculated x-values are > stored in 1D array arr_x (note, fake array, is really a list) > > > #the list of calculated x values, together with the y values in the > cobra_xy_file have to be put in an array: arr_xy > #first define the new array: > arr_xy = [] > > #then fill the array with the x and y values: > for i in range(0, len(arr_x)): > sub_arr_xy = [] > sub_arr_xy.append(arr_x[i]) > sub_arr_xy.append(float(cobra_xy_file.readline())) > arr_xy.append(sub_arr_xy) > > #print 'These are the first values from the x,y file:' > #print arr_xy[:5] > #print > > cobra_xy_file.close > -------------------------------------------------------- > > > > > >>> please note new phone and fax number <<< > ---------------------------------------------------- > Karen Leever > Department of Tectonics > Faculty of Earth and Life Sciences > Vrije Universiteit Amsterdam > De Boelelaan 1085 > 1081 HV Amsterdam > The Netherlands > > tel: +31 20 598 7278 > fax: +31 20 598 9943 > @: karen.leever@falw.vu.nl > ---------------------------------------------------- > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jsmith at medplus.com Mon Feb 7 15:14:55 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 15:15:19 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Alan, No use beating this dead horse...I guess that's why there are so many languages in the first place. Different people are comfortable with different things. (I did warn you that I like both Lisp and Prolog and only wish I had more of a reason to use them :-) As an aside, I did try to create a lambda based solution but was unable. Let me know what's wrong: ftable = { 'a' : lambda: print 'a', 'b' : lambda: print 'b or c', 'c' : lambda: print 'b or c', 'd' : lambda: pass } ftable.get(var, lambda: print 'default case')() File "C:\scratch\Script1.py", line 2 ftable = { 'a' : lambda: print 'a', ^ SyntaxError: invalid syntax Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Friday, February 04, 2005 6:39 PM To: Smith, Jeff; Jacob S.; Nicholas.Montpetit@deluxe.com; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > Now who's joking? :-) > Are you saying that > > switch var: > case 'a': > print 'a' > ... > default: > print 'default case' > > Is less clear and maintainable than I don;tthink I said (certainly didn't mean) less clear, but yes it is less maintainable. But then... > def do_this_function(): > print 'a' > .... > ftable = { 'a' : do_this_function, > 'b' : do_that_function, > 'c' : do_that_function, > 'd' : do_pass_function } > ftable.get(var, do_default_function)() I did also say that it was best with proper lambdas ftable = {'a' : lambda: print 'a', 'b' : lambda: print 'b' etc/// and I'd code the calling section: try: ftable[value]() except KeyError: doDefaultFunction() Its more maintainable because even if the switches proliferates as they tend to do, the dictionary stays in one place and the calling code never needs changing. So the changes are much more localised. And of course the more complex the case actions are, the more effective the dictionary/function approach becomes. Alan G. From hornak at csb.sunysb.edu Mon Feb 7 15:27:56 2005 From: hornak at csb.sunysb.edu (Viktor Hornak) Date: Mon Feb 7 15:28:33 2005 Subject: [Tutor] python lists to C arrays and vice versa Message-ID: <42077AEC.5060007@csb.sunysb.edu> Hello All, I've been trying to find more resources/documentation about how to convert python lists to C arrays (and vice versa) when writing a python extension. Surprisingly, there's very little one can find about this even though it must be a fairly common procedure. I looked through official python guide on "Extending and Embedding the Python Interpreter" but it's very terse on examples and the important topic on reference counting is still not very clear. I also found one or two examples of similar operations on this list postings (from 6 years ago!) but they didn't quite explain all I need to know. Here is the code I was trying to use to convert two lists (one is a list of strings with the same length and the other is a list of doubles) to C arrays in a C extension: typedef char Name[5]; extern void parseMask(int, char*, Name *, double *); /* this is the function I am trying to wrap */ static PyObject *print_sel(PyObject *self, PyObject *args) { PyObject *anamestr, *xdbl; PyObject *pylist; /* return list of 0/1 */ PyObject *item; int nat; int i, k; Name *aname; double *x; PyArg_ParseTuple(args,"iOO", &nat, &anamestr, &xdbl); if (!PySequence_Check(anamestr) || !PySequence_Check(xdbl)) { PyErr_SetString(PyExc_TypeError, "expected sequence"); return NULL; } /* create dynamic C arrays */ aname = (Name *) malloc(sizeof(Name)*nat); x = (double *) malloc(sizeof(double)*nat); for (i = 0; i < nat; i++) { /* get the element from the list*/ item = PySequence_GetItem(anamestr,i); /* check that item != NULL, i.e. make sure it is Python string */ if (!PyString_Check(item)) { free(aname); /* free up the memory before leaving */ free(x); PyErr_SetString(PyExc_TypeError, "expected sequence of strings"); return NULL; } /* assign to the C array */ strcpy(aname[i], PyString_AsString(item)); Py_DECREF(item); item = PySequence_GetItem(xdbl,i); if (!PyFloat_Check(item)) { free(aname); free(x); PyErr_SetString(PyExc_TypeError, "expected sequence of integers"); return NULL; } x[i] = PyFloat_AsDouble(item); Py_DECREF(item); } Then I call the function "parseMask" (which I am trying to wrap in this extension) which returns a C array (integer array, elements are either 0 or 1). Now I need to convert this integer array to python list and return it back to python. Here is the code for that: result = (int *) malloc(sizeof(int) * nat); parseMask(...) -> returns int array result pylist = PyTuple_New(nat); for (i = 0; i < nat; i++) { /* convert resulting array [0/1] to PyObject */ if (result[i] == 0) item = PyInt_FromLong(0); else item = PyInt_FromLong(1); PyTuple_SetItem(pylist, i, item); Py_DECREF(item); } /* free up all arrays before leaving */ free((void *) aname); free((void *) x); free((void *) result); return pylist; I was wondering if some 'extension guru' (or whoever has experience with writing extensions :-)) could see if the above code is correct, especially with respect to reference counting. When I use this extension from Python (on Fedora Core 3, Python2.3) I get the following error: *** glibc detected *** double free or corruption (out): 0x09f724e8 *** Aborted This is supposed to mean some deeper memory allocation/deallocation error. I suspect I am not creating or releasing python objects in my C extension above correctly. Of course, it is also possible that the C function I am wrapping (parseMask()) is not allocating memory properly, but it works without problem when I call it from a C program. I am sorry for this looong post, but I didn't see a way to make it shorter and still be very specific about what I am trying to do... Many thanks for any help, -Viktor Hornak From kent37 at tds.net Mon Feb 7 15:36:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 15:36:03 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> Message-ID: <42077CD2.5040107@tds.net> Liam Clarke wrote: >>>example of (1): >>>--------------------------------------------------------- >>>#this part of the program reads the file basin.out (the data we want to >>>analyze) and changes its contents to the array arr_xy >>>#layout of basin.out: >>>#1 -950.00 10.00 200 > this line contains start, interval and >>>number of x values; >>># 0.000000E+00 > remainder is a column of y values >>># -1.931787E-07 >>># -5.713295E-07 >>># -9.322559E-07 >>># -1.071361E-06 >>># -7.801342E-07 >>># ..... >>start = int(float(list[1])) >>interval = int(float(list[2])) >>n = int(float(list[3])) > > > list[1] is a string, so if I'm not missing something, start = > int(list[1]) will do just fine. No, because list[1] is '-950.00' which will not parse as an int. Kent From bgailer at alum.rpi.edu Mon Feb 7 15:47:33 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Feb 7 15:42:03 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <6.1.2.0.0.20050207074342.034cec58@mail.mric.net> At 07:14 AM 2/7/2005, Smith, Jeff wrote: >Alan, > >No use beating this dead horse...I guess that's why there are so many >languages in the first place. Different people are comfortable with >different things. (I did warn you that I like both Lisp and Prolog and >only wish I had more of a reason to use them :-) > >As an aside, I did try to create a lambda based solution but was unable. >Let me know what's wrong: > >ftable = { 'a' : lambda: print 'a', > 'b' : lambda: print 'b or c', > 'c' : lambda: print 'b or c', > 'd' : lambda: pass } >ftable.get(var, lambda: print 'default case')() From the docs: lambda arguments: expression print 'a' is not an expression > File "C:\scratch\Script1.py", line 2 > ftable = { 'a' : lambda: print 'a', > ^ >SyntaxError: invalid syntax Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jsmith at medplus.com Mon Feb 7 15:43:07 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 15:43:13 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: That's kinda what I thought but a couple of people suggested that I used lambdas to make it clearer that I figured I was doing something wrong... Jeff -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: Monday, February 07, 2005 9:48 AM To: Smith, Jeff; tutor@python.org Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] At 07:14 AM 2/7/2005, Smith, Jeff wrote: >Alan, > >No use beating this dead horse...I guess that's why there are so many >languages in the first place. Different people are comfortable with >different things. (I did warn you that I like both Lisp and Prolog and >only wish I had more of a reason to use them :-) > >As an aside, I did try to create a lambda based solution but was >unable. Let me know what's wrong: > >ftable = { 'a' : lambda: print 'a', > 'b' : lambda: print 'b or c', > 'c' : lambda: print 'b or c', > 'd' : lambda: pass } >ftable.get(var, lambda: print 'default case')() From the docs: lambda arguments: expression print 'a' is not an expression > File "C:\scratch\Script1.py", line 2 > ftable = { 'a' : lambda: print 'a', > ^ >SyntaxError: invalid syntax Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bgailer at alum.rpi.edu Mon Feb 7 16:09:57 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Feb 7 16:04:26 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <6.1.2.0.0.20050207080358.0347faf8@mail.mric.net> At 07:43 AM 2/7/2005, Smith, Jeff wrote: >That's kinda what I thought but a couple of people suggested that I used >lambdas to make it clearer that I figured I was doing something wrong... Well you can use lambdas. Have them return an expression which you print after retrieving: ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: ''} print ftable.get(var, lambda: 'default case')() But it would be clearer to store just the expressions: ftable = { 'a' : 'a', 'b' : 'b or c', 'c' : 'b or c', 'd' : ''} print ftable.get(var, 'default case') Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jsmith at medplus.com Mon Feb 7 16:06:10 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 16:06:15 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Bob, Unfortunately, that doesn't do the same thing. In the 'd' case, you get a print rather than a pass for instance. It was also just happenstance that I chose to print on each switch rather than do something like increment a counter. Jeff -----Original Message----- From: Bob Gailer [mailto:bgailer@alum.rpi.edu] Sent: Monday, February 07, 2005 10:10 AM To: Smith, Jeff; tutor@python.org Subject: RE: [Tutor] Are you allowed to shoot camels? [kinda OT] At 07:43 AM 2/7/2005, Smith, Jeff wrote: >That's kinda what I thought but a couple of people suggested that I >used lambdas to make it clearer that I figured I was doing something >wrong... Well you can use lambdas. Have them return an expression which you print after retrieving: ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: ''} print ftable.get(var, lambda: 'default case')() But it would be clearer to store just the expressions: ftable = { 'a' : 'a', 'b' : 'b or c', 'c' : 'b or c', 'd' : ''} print ftable.get(var, 'default case') Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Mon Feb 7 16:16:12 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 16:16:14 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <6.1.2.0.0.20050207074342.034cec58@mail.mric.net> References: <6.1.2.0.0.20050207074342.034cec58@mail.mric.net> Message-ID: <4207863C.2030109@tds.net> Bob Gailer wrote: > At 07:14 AM 2/7/2005, Smith, Jeff wrote: > >> Alan, >> >> No use beating this dead horse...I guess that's why there are so many >> languages in the first place. Different people are comfortable with >> different things. (I did warn you that I like both Lisp and Prolog and >> only wish I had more of a reason to use them :-) >> >> As an aside, I did try to create a lambda based solution but was unable. >> Let me know what's wrong: >> >> ftable = { 'a' : lambda: print 'a', >> 'b' : lambda: print 'b or c', >> 'c' : lambda: print 'b or c', >> 'd' : lambda: pass } >> ftable.get(var, lambda: print 'default case')() > > > From the docs: lambda arguments: expression > print 'a' is not an expression As a workaround to use print in a lambda you can use sys.stdout.write() instead. Kent From sandip at lug-delhi.org Mon Feb 7 16:09:27 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Mon Feb 7 16:44:45 2005 Subject: [Tutor] want recommendations for interfacing with postgresql Message-ID: <1107788967.29067.5.camel@pluto.home> Hi! I am planning to work with postgresql and python for one of my projects. Which library module would you recommend for the job? I have seen: 1. http://www.pygresql.org (pgdb module) 2. http://initd.org/projects/psycopg1 Thanks, Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From sandip at lug-delhi.org Mon Feb 7 17:01:15 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Mon Feb 7 16:53:12 2005 Subject: [Tutor] Fwd: want recommendations for interfacing with postgresql Message-ID: <1107792075.29067.10.camel@pluto.home> [Reposting. Didnt make it the first time - Sandip] -------- Forwarded Message -------- From: Sandip Bhattacharya To: Python Tutor Mailing List Subject: want recommendations for interfacing with postgresql Date: Mon, 07 Feb 2005 20:39:27 +0530 Hi! I am planning to work with postgresql and python for one of my projects. Which library module would you recommend for the job? I have seen: 1. http://www.pygresql.org (pgdb module) 2. http://initd.org/projects/psycopg1 Thanks, Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From tony at tcapp.com Mon Feb 7 19:32:57 2005 From: tony at tcapp.com (Tony Cappellini) Date: Mon Feb 7 19:30:42 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: References: Message-ID: <20050207102429.O90909@yamato.yamato.com> > Out of curiosity, if it's not possible to run zip() directly on the lists > that you have, can you bend the lists so that zip() will fit? It is possible, however zip() truncates the longer list, based on the size of the smaller list, so it's just not feasible in my case. > Here's a quick function that should force a certain length on an iterator: > > ### > def ipad(iterable, length, sentinel=None): > """Returns a new iterator whose elements are taken from iterator. If > there are fewer elements than 'length', we pad the rest with > sentinels. > > Assumptions: len(iterator) <= length. The result from ipad never > truncates the elements out of i, so the iterator always goes through > all the elements in iterable. > """ > i = 0 > for thing in iterable: > yield thing > i = i + 1 > while i < length: > yield sentinel > i = i + 1 > ### > > > For example: > > ### > >>> names = ['knuth', 'mcconnell', 'bentley', 'witten'] > >>> for n in ipad(names, 7): > ... print n > ... > knuth > mcconnell > bentley > witten > None > None > None > >>> > >>> > >>> for n in ipad(names, 2): > ... print n > ... > knuth > mcconnell > bentley > witten > ### > > > So we could use something like ipad() to bring all the lists to the same > length, and that should make it suitable for zip(). > > > Hope this helps! > > I see- yes it does. And since it's my first use of generators, without really having to understand them, I'm more inclined to use this approach :-) I will just pad the short lists with the lenght of the longest list. However, this brings up a question about map() ing over lists of different lengths (which is what I started to use), but I'll post that in a different message. BTW, is your def ipad() function the 20gb, 40gb, or 60gb model ? :-) Thanks From alan.gauld at freenet.co.uk Mon Feb 7 20:28:34 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:28:04 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <05ad01c50d4b$37c1c040$68b78851@xp> > As an aside, I did try to create a lambda based solution but was unable. > Let me know what's wrong: > > ftable = { 'a' : lambda: print 'a', > SyntaxError: invalid syntax I did say "if Python had *proper* lambdas..." Unfortunately Python insists on only having *expressions* as lambdas and since print is a command not a function you can't use it in Python lambdas! Dumb or what??! So you are stuck with predefining a bunch of one liner functions and then creating a dictionary or going back to if/elif chains, which is where we came in... :-) HTH, Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 20:49:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:50:20 2005 Subject: [Tutor] manipulating a file References: Message-ID: <05d401c50d4e$2058fc40$68b78851@xp> > running the following with print i uncommented does print each line to > stdout. but it doesn't write to the appropriate file... Does it do anything? BTW YOu don;t need to touch a file, the 'w' parameter will create a new file if one doesn't exist. > c) I originally wanted to delete lines over 2085 in length but couldn't > find a way to do that... did I miss it? deleting files from a file aint so easy, its much simpler to just create a new file with the lines you want, as you do here. > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > for i in lines: This is much easier with: for i in srcfile: It will automatically detect and stop at the end of the file. > if len(i) < 2086: > #print i > dstfile.write(i) You should add a newline character otherwise you will just get one enormously long line! dstfile.write(i+'\n') > srcfile.close() > dstfile.close() But I don't see anything obviously wrong. What exactly does happen? A single line as explained above? Or just a blank file? Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 20:53:05 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:52:28 2005 Subject: [Tutor] manipulating a file References: <20050207091852.87090.qmail@web53808.mail.yahoo.com> Message-ID: <05dd01c50d4e$a404df00$68b78851@xp> > About the efficiency, why do u need python at all... > How abt a simple shell command.... > cat httpd-access.log>>log.bak > Because that would be a copy, well actually an append... cp httpd-access.log log.bak would be better! But the OP wanted to strip out long lines in transit not just copy... Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 20:56:41 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 20:56:06 2005 Subject: [Tutor] Iterating over multiple lists- options References: <20050207092714.75163.qmail@web53807.mail.yahoo.com> Message-ID: <05e201c50d4f$25213d40$68b78851@xp> > How about using a try loop every time you read from > the list. try is not a loop. > try: > x=list[someno] > except: > x=nothing(or whatever) > > This goes on till the all lists start returning none. No, sorry it just does it once. try/except is for detecting errors not a looping construct. > for shorter lists try throws an index out of range > exception which is caught by except. This much is true. But to do as you suggest the try/except would need to be placed inside a for or while loop. However that would be an interesting approach. I don't know if it would be faster than comparing the len(), I suspect not, but try/except is fairly fast so it just might be. Alan G. From jsmith at medplus.com Mon Feb 7 20:58:03 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 20:58:10 2005 Subject: [Tutor] manipulating a file Message-ID: -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Monday, February 07, 2005 2:49 PM To: Reed L. O'Brien; tutor@python.org Subject: Re: [Tutor] manipulating a file >You should add a newline character otherwise you will just >get one enormously long line! > > dstfile.write(i+'\n') In these cases, I've taken to doing print >> dstfile, I ...hmmm starting to look like Perl's many ways to accomplish the same thing approach :-) Jeff From alan.gauld at freenet.co.uk Mon Feb 7 21:06:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 21:05:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <062001c50d50$82d50330$68b78851@xp> > That's kinda what I thought but a couple of people suggested > that I used lambdas to make it clearer I suggested that if we had proper lambdas we could use 'em... But of course you can still use lambdas just put the print at the client side: def p(): pass ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: p} print ftable.get(var, lambda: 'default case')() But I still had to use a def for the pass... :-( Alan G. From alan.gauld at freenet.co.uk Mon Feb 7 21:08:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Feb 7 21:07:35 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <6.1.2.0.0.20050207080358.0347faf8@mail.mric.net> Message-ID: <062501c50d50$bc2715b0$68b78851@xp> > Well you can use lambdas. Have them return an expression which you print > after retrieving: > ftable = { 'a' : lambda: 'a', > 'b' : lambda: 'b or c', > But it would be clearer to store just the expressions: > ftable = { 'a' : 'a', > 'b' : 'b or c', True for this special case, but where the lambda has to do some calculation it starts to make sense! :-) Alan G. From jsmith at medplus.com Mon Feb 7 21:08:59 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Mon Feb 7 21:09:05 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Alan, That's actually worse than you might think. Try this: var = 'd' def p(): pass ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: p} print ftable.get(var, lambda: 'default case')() And what you get is: That's hardly a pass :-) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Monday, February 07, 2005 3:06 PM To: Smith, Jeff; Bob Gailer; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > That's kinda what I thought but a couple of people suggested > that I used lambdas to make it clearer I suggested that if we had proper lambdas we could use 'em... But of course you can still use lambdas just put the print at the client side: def p(): pass ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c', 'd' : lambda: p} print ftable.get(var, lambda: 'default case')() But I still had to use a def for the pass... :-( Alan G. From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 21:30:59 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 21:31:03 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <20050207102429.O90909@yamato.yamato.com> Message-ID: On Mon, 7 Feb 2005, Tony Cappellini wrote: > > Here's a quick function that should force a certain length on an > > iterator: > > > > ### > > def ipad(iterable, length, sentinel=None): > > i = 0 > > for thing in iterable: > > yield thing > > i = i + 1 > > while i < length: > > yield sentinel > > i = i + 1 > > ### > > BTW, is your def ipad() function the 20gb, 40gb, or 60gb model ? :-) Hi Tony, Oh, I had some terrible puns I was going to use in the last message. Here's one, just for your amusement: ### import sys def ipad_maxi(iterable, sentinel=None): """Applies a maximum ipad()ding on a given iterable.""" return ipad(iterable, sys.maxint, sentinel) ### But getting back on topic: I like Kent's solution with map() much better than my own. I had completely forgotten that map() had a special case that applies directly to what you're trying to do. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 21:43:42 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 21:43:47 2005 Subject: [Tutor] where do we use acquisition ? In-Reply-To: <4207689E.9010501@cirad.fr> Message-ID: Hi Chandu, Ah, so you're looking into "environmental acquisition". I think the reason you're asking about on Tutor is because one of the most visible deployments of acquisition has been in the Zope web framework. But just because Zope is written in Python doesn't mean that acquisition is a concept that's exclusive to Python. If you would like to learn more, here's a link to a really nice web site on acquisition: http://www.ccs.neu.edu/home/lorenz/research/acquisition/ It appears to house a lot of the accumulated knowledge on acquisition. Because this topic is very specialized, we probably won't be able to do any justice to it on Python-tutor. The acquisition web site linked above should give you references for why it's cool, and what communities you can talk with to learn more about it. Best of wishes to you! From shitizb at yahoo.com Mon Feb 7 22:01:29 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Mon Feb 7 22:01:32 2005 Subject: [Tutor] manipulating a file In-Reply-To: <05dd01c50d4e$a404df00$68b78851@xp> Message-ID: <20050207210129.83279.qmail@web53801.mail.yahoo.com> How about cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak The issue is - will unix shell command be any more efficient than a python script?? Also i used append because i gathered that the user will not want to erase the previous logs. He is free to use a single > if he does. --- Alan Gauld wrote: > > About the efficiency, why do u need python at > all... > > How abt a simple shell command.... > > cat httpd-access.log>>log.bak > > > > Because that would be a copy, well actually an > append... > > cp httpd-access.log log.bak > > would be better! > > But the OP wanted to strip out long lines in transit > not just copy... > > Alan G. > > > __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From cyresse at gmail.com Mon Feb 7 22:12:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Mon Feb 7 22:12:03 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: <42077CD2.5040107@tds.net> References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <42077CD2.5040107@tds.net> Message-ID: oh? Is is the negative? On Mon, 07 Feb 2005 09:36:02 -0500, Kent Johnson wrote: > Liam Clarke wrote: > >>>example of (1): > >>>--------------------------------------------------------- > >>>#this part of the program reads the file basin.out (the data we want to > >>>analyze) and changes its contents to the array arr_xy > >>>#layout of basin.out: > >>>#1 -950.00 10.00 200 > this line contains start, interval and > >>>number of x values; > >>># 0.000000E+00 > remainder is a column of y values > >>># -1.931787E-07 > >>># -5.713295E-07 > >>># -9.322559E-07 > >>># -1.071361E-06 > >>># -7.801342E-07 > >>># ..... > >>start = int(float(list[1])) > >>interval = int(float(list[2])) > >>n = int(float(list[3])) > > > > > > list[1] is a string, so if I'm not missing something, start = > > int(list[1]) will do just fine. > > No, because list[1] is '-950.00' which will not parse as an int. > > Kent > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Feb 7 22:21:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 22:21:44 2005 Subject: [Tutor] calling subroutines into program In-Reply-To: References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <42077CD2.5040107@tds.net> Message-ID: <4207DBE2.6000109@tds.net> Liam Clarke wrote: > oh? Is is the negative? No, the decimal fraction. It's easy enough to try it: >>> int('950') 950 >>> int('-950') -950 >>> int('950.00') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): 950.00 >>> int('-950.00') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): -950.00 Kent > > > On Mon, 07 Feb 2005 09:36:02 -0500, Kent Johnson wrote: >>No, because list[1] is '-950.00' which will not parse as an int. >> >>Kent >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From lumbricus at gmx.net Mon Feb 7 22:09:48 2005 From: lumbricus at gmx.net (Joerg Woelke) Date: Mon Feb 7 22:27:23 2005 Subject: [Tutor] manipulating a file In-Reply-To: <20050207210129.83279.qmail@web53801.mail.yahoo.com> References: <05dd01c50d4e$a404df00$68b78851@xp> <20050207210129.83279.qmail@web53801.mail.yahoo.com> Message-ID: <20050207210948.GB19208@laplace> On Mon, Feb 07, 2005 at 01:01:29PM -0800, Shitiz Bansal wrote: > > How about > cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak UUOC (Useless Use Of Cat) SCNR J"o! -- You're at the end of the road again. From ternary at gmail.com Mon Feb 7 22:37:47 2005 From: ternary at gmail.com (Mike Bell) Date: Mon Feb 7 22:37:50 2005 Subject: [Tutor] manipulating a file In-Reply-To: References: Message-ID: <82975b0c050207133779e71018@mail.gmail.com> without the explicit newlines in file.write(i), could it be that the file was closed before the write buffer was ever flushed? mike On Mon, 7 Feb 2005 14:58:03 -0500, Smith, Jeff wrote: > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Monday, February 07, 2005 2:49 PM > To: Reed L. O'Brien; tutor@python.org > Subject: Re: [Tutor] manipulating a file > > >You should add a newline character otherwise you will just > >get one enormously long line! > > > > dstfile.write(i+'\n') > > In these cases, I've taken to doing > print >> dstfile, I > > ...hmmm starting to look like Perl's many ways to accomplish the same > thing approach :-) > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Mon Feb 7 22:48:24 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 7 22:48:28 2005 Subject: [Tutor] python lists to C arrays and vice versa In-Reply-To: <42077AEC.5060007@csb.sunysb.edu> Message-ID: On Mon, 7 Feb 2005, Viktor Hornak wrote: > I've been trying to find more resources/documentation about how to > convert python lists to C arrays (and vice versa) when writing a python > extension. Hi Viktor, There was a post back in 1999 that might be useful for you: http://mail.python.org/pipermail/tutor/1999-November/000758.html I'm not positive if there is a nicer helper function to do this. > I also found one or two examples of similar operations on this list > postings (from 6 years ago!) but they didn't quite explain all I need > to know. Ah, so you did see that posting then. *grin* Ok, good. What parts of their explanation were incomplete? Maybe one of us here can help fill in more details for you. > Here is the code I was trying to use to convert two lists (one > is a list of strings with the same length and the other is a list of > doubles) to C arrays in a C extension: [Some code cut] The code there seems sorta ok: you might want to add a string length check in there somewhere: the code expects that names are at most 4 characters long, but that condition isn't being checked by strcpy(). > Then I call the function "parseMask" (which I am trying to wrap in this > extension) which returns a C array (integer array, elements are either 0 > or 1). Now I need to convert this integer array to python list and > return it back to python. Here is the code for that: > > result = (int *) malloc(sizeof(int) * nat); > parseMask(...) -> returns int array result > > pylist = PyTuple_New(nat); > for (i = 0; i < nat; i++) { > /* convert resulting array [0/1] to PyObject */ > if (result[i] == 0) > item = PyInt_FromLong(0); > else > item = PyInt_FromLong(1); > > PyTuple_SetItem(pylist, i, item); > Py_DECREF(item); /** <-- (dyoo): bug located */ > } Ah! Got it. Don't call Py_DECREF() here: PyTuple_SetItem will already "steal" the reference, according to the documentation: http://docs.python.org/api/tupleObjects.html#l2h-576 so there's no need to decrement the reference count here. By the way, if you're really going to do more C extension stuff, take a look at Pyrex or SWIG: http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/ http://www.swig.org/ Coding C wrappers by hand is painful: use these tools to make your life easier. *grin* Best of wishes! From kent37 at tds.net Mon Feb 7 22:59:56 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon Feb 7 23:00:00 2005 Subject: [Tutor] manipulating a file In-Reply-To: References: Message-ID: <4207E4DC.3000908@tds.net> Reed L. O'Brien wrote: > I want to read the httpd-access.log and remove any oversized log records > > I quickly tossed this script together. I manually mv-ed log to log.bak > and touched a new logfile. > > running the following with print i uncommented does print each line to > stdout. but it doesn't write to the appropriate file... Is the log open for writing in another application? Kent > > a) what am I missing? > b) is there a less expensive way to do it? > c) I originally wanted to delete lines over 2085 in length but couldn't > find a way to do that... did I miss it? > > Thanks > > #!/usr/local/bin/python > > import os > > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > # print lines > for i in lines: > if len(i) < 2086: > #print i > dstfile.write(i) > > srcfile.close() > dstfile.close() > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Tue Feb 8 00:15:23 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 00:14:46 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <062e01c50d6a$e6eaa900$68b78851@xp> That's actually worse than you might think. Try this: > def p(): pass > ftable = { 'a' : lambda: 'a', > 'd' : lambda: p} That should be: 'd': p} ie No lambda used at all. I wish Python had real lambdas! > And what you get is: > Yep, coz the lambda returns a function object! Which it should, I just shouldn't have used lambda there. My bad, Alan G. From missive at hotmail.com Tue Feb 8 00:48:36 2005 From: missive at hotmail.com (Lee Harr) Date: Tue Feb 8 00:49:05 2005 Subject: [Tutor] Re: Percolation model in python Message-ID: > I have two questions. Once a MxN world is generated how would you >search for nearest neighbors (to see who is connected) and then color Does this help? import random PERSON, EMPTY = '*', '.' def get_threshold(): perc = raw_input("Please enter a thresold between 0-1. ") perc = float(perc) return perc def make_random_world(M, N): """Constructs a new random game world of size MxN.""" perc = get_threshold() world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def percolation(perc): randval = random.random() if randval > perc: return EMPTY else: return PERSON def neighbors(world, x, y): M, N = world['dimensions'] nxmin = max(0, x-1) nxmax = min(M, x+1) nymin = max(0, y-1) nymax = min(N, y+1) r = [] for nx in range(nxmin, nxmax+1): for ny in range(nymin, nymax+1): if nx != x or ny != y: r.append((nx, ny)) return r def print_world(world): """Prints out a string representation of a world.""" M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print def make_world_option(): m = int(raw_input("Please enter a m dimension. ")) n = int(raw_input("Please enter a n dimension. ")) raw_input("Press return to make a world") return make_random_world(m, n) def show_neighbors_option(world): x = int(raw_input("Please enter an x coord. ")) y = int(raw_input("Please enter a y coord. ")) print neighbors(world, x, y) def menu(): print """ Please pick your option: 1) Percolation model for Small Pox 2) Show world 3) Instructions 4) Show neighbors 5) Exit """ option = int(raw_input("Which option[1,2,3,4,5]? ")) return option if __name__ == '__main__': option = None while option != 5: if option == 1: world = make_world_option() elif option == 2: print_world(world) elif option == 4: show_neighbors_option(world) option = menu() _________________________________________________________________ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ From alan.gauld at freenet.co.uk Tue Feb 8 00:53:46 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 00:53:09 2005 Subject: [Tutor] manipulating a file References: <20050207210129.83279.qmail@web53801.mail.yahoo.com> Message-ID: <067701c50d70$43e31160$68b78851@xp> > How about > cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak OK< but you can miss the cat out grep -v -E [[:alnum]]'{2096}' log >> log.bak But I confess I've no idea how that works, I've never seen that notation in a grep before! Checking man reveals an "extended regex" which I interpret as: any alphanumeric repeated 2096 times? But I'm not sure about my interpretation... > The issue is - will unix shell command be any more > efficient than a python script?? Usually, if you only use a single process like grep because they are written in C. But when you pipeline with cat it might slow it down enough to make Python competitive. Process startup tends to be the limiting factor in shell pipelines. > Also i used append because i gathered that the user > will not want to erase the previous logs. He is free > to use a single > if he does. Interesting, I assumed he would want to delete the old logs... As you say, whichever is appropriate is easily controlled. Alan G. From alan.gauld at freenet.co.uk Tue Feb 8 00:55:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 00:54:49 2005 Subject: [Tutor] manipulating a file References: <82975b0c050207133779e71018@mail.gmail.com> Message-ID: <068201c50d70$801a4270$68b78851@xp> > without the explicit newlines in file.write(i), could it be that the > file was closed before the write buffer was ever flushed? No because close() was called explicitly, which does a flush first... Alan G. From flaxeater at yahoo.com Tue Feb 8 00:55:33 2005 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Feb 8 00:55:37 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: <20050207235533.16392.qmail@web54307.mail.yahoo.com> Alan Gauld wrote: >ie No lambda used at all. > >I wish Python had real lambdas! > > If python had real lambda's then it would be lisp or schema. __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From shitizb at yahoo.com Tue Feb 8 01:30:25 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Feb 8 01:30:28 2005 Subject: [Tutor] manipulating a file In-Reply-To: <20050207210129.83279.qmail@web53801.mail.yahoo.com> Message-ID: <20050208003025.88618.qmail@web53808.mail.yahoo.com> I aplogise for a typo... Please read the command as: cat log|grep -v -E [[:alnum]]'{2096,}'>> log.bak note the missing comma in the previous command. --- Shitiz Bansal wrote: > > How about > cat log|grep -v -E [[:alnum]]'{2096}'>> log.bak > > The issue is - will unix shell command be any more > efficient than a python script?? > > Also i used append because i gathered that the user > will not want to erase the previous logs. He is free > to use a single > if he does. > > > --- Alan Gauld wrote: > > > > About the efficiency, why do u need python at > > all... > > > How abt a simple shell command.... > > > cat httpd-access.log>>log.bak > > > > > > > Because that would be a copy, well actually an > > append... > > > > cp httpd-access.log log.bak > > > > would be better! > > > > But the OP wanted to strip out long lines in > transit > > not just copy... > > > > Alan G. > > > > > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Find what you need with new enhanced > search. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From tony at tcapp.com Tue Feb 8 01:59:56 2005 From: tony at tcapp.com (Tony Cappellini) Date: Tue Feb 8 01:57:37 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: References: Message-ID: <20050207165704.M96328@yamato.yamato.com> LOL > Here's one, just for your amusement: > > But getting back on topic: I like Kent's solution with map() much better > than my own. I had completely forgotten that map() had a special case > that applies directly to what you're trying to do. I havne't seen Kent's reply yet- will have to look when I get home from work. But I 've found some inconsistnacies with map, depending on which order the args were passed in. If the shorter list was passed to map first, as in map(shortlist, longerlist), it behaved one way. If I reversed the order of the args, as in map(longerlist, shortlist), map() behaved slighlty different. Almost like what zip() did. Perhaps Kent's suggestion addresses this. I will see later. Thanks! From jeff at ccvcorp.com Tue Feb 8 03:18:40 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Feb 8 03:17:32 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: <05ad01c50d4b$37c1c040$68b78851@xp> References: <05ad01c50d4b$37c1c040$68b78851@xp> Message-ID: <42082180.4040907@ccvcorp.com> Alan Gauld wrote: >>As an aside, I did try to create a lambda based solution but was >>unable. Let me know what's wrong: >> >>ftable = { 'a' : lambda: print 'a', >>SyntaxError: invalid syntax > > I did say "if Python had *proper* lambdas..." > > Unfortunately Python insists on only having *expressions* as > lambdas and since print is a command not a function you can't > use it in Python lambdas! Dumb or what??! > > So you are stuck with predefining a bunch of one liner > functions and then creating a dictionary or going back > to if/elif chains, which is where we came in... :-) Well, in this particular case, if one really wants to use lambdas then one could (after importing sys, of course) replace the print statement with a call to sys.stdout.write() -- ftable = { 'a': lambda: sys.stdout.write('a\n'), ... } Note that sys.stdout.write() will *not* automatically add the newline that print does (which is why I've specified it in the above sample). Indeed, print can do all sorts of odd things with whitespace, leaving sys.stdout.write() as the best way to have real control over your output anyhow... Jeff Shannon Technician/Programmer Credit International From kent37 at tds.net Tue Feb 8 04:32:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 04:32:11 2005 Subject: [Tutor] Iterating over multiple lists- options In-Reply-To: <20050207165704.M96328@yamato.yamato.com> References: <20050207165704.M96328@yamato.yamato.com> Message-ID: <420832B6.2070909@tds.net> Tony Cappellini wrote: > I havne't seen Kent's reply yet- will have to look when I get home from > work. > But I 've found some inconsistnacies with map, depending on which order > the args were passed in. > If the shorter list was passed to map first, as in map(shortlist, > longerlist), it behaved one way. The first argument to map() is a function or None, not one of the lists. You should try map(None, shortlist, longerlist). Kent From tony at tcapp.com Tue Feb 8 07:12:08 2005 From: tony at tcapp.com (Tony Cappellini) Date: Tue Feb 8 07:12:22 2005 Subject: [Tutor] Iterating over multiple lists- options Message-ID: <6.1.2.0.0.20050207215900.01b30de8@mail.yamato.com> map(None, North, South, East West) does exactly what you want: >>> North=['Bill', 'Bob', 'Sue', 'Mary'] >>> South=['Tim', 'Tom', 'Jim', 'John', 'Carl', 'Evan', 'Rich'] >>> map(None, North, South) [('Bill', 'Tim'), ('Bob', 'Tom'), ('Sue', 'Jim'), ('Mary', 'John'), (None, 'Carl'), (None, 'Evan'), (None, 'Rich')] > That being, both of these functions can truncate the data, depending on > certain conditions >>I don't think that is true for map(); what conditions are you thinking of? Well, I've tried duplicating what I was seeing last night when I posted the message, and it's not happening the same now. Maybe I was up too later working on this problem... What I *thought* I was seeing was map() would return a list of a certain length when I called it like this map(None, North, South) and returned a list of a different length when I called it like this map(None, South, North) However, trying that now basically returns the a list that appears to be the same length, for both calls. I think this will work after all. I'll add it to my program . Thanks for your quick replies From johan at accesstel.co.za Tue Feb 8 08:28:35 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Feb 8 08:30:12 2005 Subject: [Tutor] CRC-16 calculation Message-ID: <1107847715.4673.9.camel@KMA.accesstel> Hi everybody, I have a data packet in Hex values and need to determine how to calculate the CRC-16 bit checksum for these values. Eg.: 0x55,0x00,0x0A,0x01,0x01, 0x01,0xFF,0x00,0xDC,0xCC Sync| Lenght |source addr|dest. adr |Data| CRC check| This example shows me the CRC chechsum, but if I change the source addr, this chechsum is no longer valid. Any suggestions on how to calculate that? Thanks Johan -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/3c07fe23/attachment.htm From kohlerj at ukzn.ac.za Tue Feb 8 08:58:37 2005 From: kohlerj at ukzn.ac.za (Johan Kohler) Date: Tue Feb 8 08:58:56 2005 Subject: [Tutor] Have I run into a limitation of Pickle? Message-ID: Hi, In the attached code, I'm trying to pickle and unpickle (1) an object containing a list of dictionaries. (2) an object containing a list objects each containing a dictionary. Case (1) seems to work (printing succesfully), ----- Running '/home/johan/prog/ratings/testpickle2.py' ... {'tel': 1234, 'name': 'Johan'} {'tel': 12454, 'name': 'Elize'} {'tel': 1234, 'name': 'Johan'} {'tel': 12454, 'name': 'Elize'} but (2) fails with the following error: <__main__.User instance at 0x41a56fac> <__main__.User instance at 0x41a56f2c> Traceback (most recent call last): File "/usr/lib/python2.3/site-packages/sm/scriptutils.py", line 49, in run exec codeObject in mainDict File "", line 87, in ? File "", line 79, in loadbroken File "", line 33, in readfromfile File "/usr/lib/python2.3/pickle.py", line 1390, in load return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.3/pickle.py", line 1140, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'User' Exception raised while running script --- I hope this is not a limitation of Pickle, because that would mean I have to change a large section of my code :-( Any help will be greatly appreciated Johan -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ -------------------------------------------------------------------- Please find our disclaimer at http://www.ukzn.ac.za/disclaimer -------------------------------------------------------------------- <<<>>> -------------- next part -------------- A non-text attachment was scrubbed... Name: testpickle2.py Type: application/octet-stream Size: 1952 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20050208/04c5983f/testpickle2-0001.obj From johan at accesstel.co.za Tue Feb 8 11:03:04 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Feb 8 11:04:08 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <4204EAB1.2050206@tds.net> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> Message-ID: <1107856983.4603.6.camel@KMA.accesstel> Hi everybody, I used binary.py and is a bit puzzled by the results I get when comparing the binary of decimal 2 and the value I get when I convert the binary to an int. >>> binary(2) '00000000000000000000000000000010' >>> int(00000000000000000000000000000010) 8 >>> Isn't the int value of this binary string supposd to be '2' and not '8'? Johan On Sat, 2005-02-05 at 17:48, Kent Johnson wrote: > Liam, > > I think you misunderstand what endianness is. > > Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory > of the computer. This is not something you generally need to worry about in a Python program. > > For example, consider the number 0x12345678. On most modern computers this will be stored in four > consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, > 0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the > most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will > be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the > lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. > > Most programming languages will hide this detail from you most of the time. Even in assembly > language, you generally load and store integers without worrying about endianness. Math operations > just do the right thing so you don't have to worry about it. > > Endianness becomes an issue when you want to convert between representations, and when binary data > is shared between computers which may have different endianness. > > For example in a C program you might want to get the high byte of an integer when you know the > address of the integer. The desired byte will be at (address+0) or (address+3) depending on the > endianness of the hardware. > > Similarly, if an array of integers is written to a file in a binary representation (not as ASCII > strings representing the integers, but as 32-bit values), then to correctly read the file you have > to know the endianness of the data in the file. > > > OK, so what does this have to do with converting a number to binary in Python? Well, nothing, > actually. First, note that 'binary representation' can mean two different things. In the description > above, I was talking about the actual bit pattern stored in the computer. Python works with binary > numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary > representation' is that of a base-2 string representation of a number. > > So if you ask, "How do I convert a number to binary?" you can mean either of these. > > The first one is trivial. If you have a decimal string representation of the number, use int() to > convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to > do anything! > > So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an > integer to a base-2 string representation?" And how do you do this? Well, you figured out one way > using the mathematical properties of integers. These operations are independent of endianness, and > so is the desired result. > > The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is > '0001001000110100'. The order of digits here is determined by our convention of writing the most > significant digits on the left, not by the endianness of the underlying computer. > > OK, this is long enough, I hope I have shed some light... > Kent > > > > Liam Clarke wrote: > > Jacob - just for you, begin your agitation for the next release please ;) > > > > binstring.py, as attached. > > (also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > > > > Creating this, was just a brain teaser, but I was thinking 'what if I > > wanted to make this for the standard library.' > > > > And so you can see, I had to include a flag for endianess. But that > > was really a cheap trick. If this was going into a standard library, > > I'd want to query the OS for endianess. As for the bits, once again, > > 32 bit is the norm, but 64 bit is here and spreading. > > > > Also, should it display 11111111 as 255 or 256? Both are valid, > > depending on context. > > > > Thirdly, if I can do it in 2 minutes, (well, the main part), then > > should they bother putting it in the standard library considering > > also, > > > > - How often, really, are you going to need to present a decimal or hex > > as a binary string. > > > > Lastly - this only does base 10 to base 2. Should I include a base 6 > > to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > > > > I wouldn't like to write for the standard library, because you can > > never please everyone. > > > > But yeah, feel free to use the above, just keep my doc strings and comments. > > > > Regards, > > > > Liam Clarke > > > > On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. wrote: > > > >>>The binary value is the same as the hex value. > >>>The binary representation is 000111110100, but > >>>unfortunately Python doesn't support binary in > >>>its string formatting(although it does in int()! > >> > >>Uh, question. Why not? It seems that all simple types should be included. > >>Since the computer stores it as binary, why shouldn't python be able to > >>display a > >>string of it in binary? That seems to be a short coming that should be added > >>to the > >>next release... IMHO of course. > >>Jacob Schmidt > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > > > > ------------------------------------------------------------------------ > > > > ###### > > # binString.py > > # by Liam Clarke > > #(Let me know when it's included in the standard library ;-)) > > ###### > > > > """Converts a integer base 10 to a string base 2""" > > > > def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > > """ > > Integer to be converted is essential, Endianess is an optional flag; > > me being a Win32 user, Endianess is big by default, defaults to a 32-bit > > representation, most integers in Python being 32 bit. truncExcess will > > strip place-holder zeros for succintness. > > > > Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > > to start counting for zero with this. It's a simple matter to change.""" > > tempList = ['0' for x in range(bits)] > > > > for bitPlace in range(bits, -1, -1): > > if decimalInt - 2**bitPlace >= 0: > > tempList[bitPlace] = '1' > > decimalInt = decimalInt - 2**bitPlace > > if bigEndian: > > tempList.reverse() > > > > outPut = ''.join(tempList) > > > > if truncExcess: > > if bigEndian: > > outPut=outPut.lstrip('0') > > else: > > outPut=outPut.rstrip('0') > > > > return outPut > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/ca1ef0df/attachment.htm From pierre.barbier at cirad.fr Tue Feb 8 11:12:22 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue Feb 8 11:10:27 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1107856983.4603.6.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> Message-ID: <42089086.8010407@cirad.fr> MMmmhh ... no ! The number you wrote is equivalent to '010' and any number beginning by '0' and not followed by "x" will be considered octal. So "10" in base 8 is ... 8 :) If you want to convert a number from base 2 to base 10 write : >>> int("0000000010", 2) 2 Pierre Johan Geldenhuys a ?crit : > Hi everybody, > I used binary.py and is a bit puzzled by the results I get when > comparing the binary of decimal 2 and the value I get when I convert the > binary to an int. > > >>>>binary(2) > > '00000000000000000000000000000010' > >>>>int(00000000000000000000000000000010) > > 8 > > > Isn't the int value of this binary string supposd to be '2' and not '8'? > > Johan > On Sat, 2005-02-05 at 17:48, Kent Johnson wrote: > > >>Liam, >> >>I think you misunderstand what endianness is. >> >>Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory >>of the computer. This is not something you generally need to worry about in a Python program. >> >>For example, consider the number 0x12345678. On most modern computers this will be stored in four >>consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, >>0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the >>most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will >>be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the >>lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. >> >>Most programming languages will hide this detail from you most of the time. Even in assembly >>language, you generally load and store integers without worrying about endianness. Math operations >>just do the right thing so you don't have to worry about it. >> >>Endianness becomes an issue when you want to convert between representations, and when binary data >>is shared between computers which may have different endianness. >> >>For example in a C program you might want to get the high byte of an integer when you know the >>address of the integer. The desired byte will be at (address+0) or (address+3) depending on the >>endianness of the hardware. >> >>Similarly, if an array of integers is written to a file in a binary representation (not as ASCII >>strings representing the integers, but as 32-bit values), then to correctly read the file you have >>to know the endianness of the data in the file. >> >> >>OK, so what does this have to do with converting a number to binary in Python? Well, nothing, >>actually. First, note that 'binary representation' can mean two different things. In the description >>above, I was talking about the actual bit pattern stored in the computer. Python works with binary >>numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary >>representation' is that of a base-2 string representation of a number. >> >>So if you ask, "How do I convert a number to binary?" you can mean either of these. >> >>The first one is trivial. If you have a decimal string representation of the number, use int() to >>convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to >>do anything! >> >>So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an >>integer to a base-2 string representation?" And how do you do this? Well, you figured out one way >>using the mathematical properties of integers. These operations are independent of endianness, and >>so is the desired result. >> >>The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is >>'0001001000110100'. The order of digits here is determined by our convention of writing the most >>significant digits on the left, not by the endianness of the underlying computer. >> >>OK, this is long enough, I hope I have shed some light... >>Kent >> >> >> >>Liam Clarke wrote: >> >>>Jacob - just for you, begin your agitation for the next release please ;) >>> >>>binstring.py, as attached. >>>(also pasted up - http://www.rafb.net/paste/results/5feItM57.html) >>> >>>Creating this, was just a brain teaser, but I was thinking 'what if I >>>wanted to make this for the standard library.' >>> >>>And so you can see, I had to include a flag for endianess. But that >>>was really a cheap trick. If this was going into a standard library, >>>I'd want to query the OS for endianess. As for the bits, once again, >>>32 bit is the norm, but 64 bit is here and spreading. >>> >>>Also, should it display 11111111 as 255 or 256? Both are valid, >>>depending on context. >>> >>>Thirdly, if I can do it in 2 minutes, (well, the main part), then >>>should they bother putting it in the standard library considering >>>also, >>> >>>- How often, really, are you going to need to present a decimal or hex >>>as a binary string. >>> >>>Lastly - this only does base 10 to base 2. Should I include a base 6 >>>to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? >>> >>>I wouldn't like to write for the standard library, because you can >>>never please everyone. >>> >>>But yeah, feel free to use the above, just keep my doc strings and comments. >>> >>>Regards, >>> >>>Liam Clarke >>> >>>On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. wrote: >>> >>> >>>>>The binary value is the same as the hex value. >>>>>The binary representation is 000111110100, but >>>>>unfortunately Python doesn't support binary in >>>>>its string formatting(although it does in int()! >>>> >>>>Uh, question. Why not? It seems that all simple types should be included. >>>>Since the computer stores it as binary, why shouldn't python be able to >>>>display a >>>>string of it in binary? That seems to be a short coming that should be added >>>>to the >>>>next release... IMHO of course. >>>>Jacob Schmidt >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> >>> >>> >>>------------------------------------------------------------------------ >>> >>>###### >>># binString.py >>># by Liam Clarke >>>#(Let me know when it's included in the standard library ;-)) >>>###### >>> >>>"""Converts a integer base 10 to a string base 2""" >>> >>>def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): >>> """ >>>Integer to be converted is essential, Endianess is an optional flag; >>>me being a Win32 user, Endianess is big by default, defaults to a 32-bit >>>representation, most integers in Python being 32 bit. truncExcess will >>>strip place-holder zeros for succintness. >>> >>>Oh, and it will represent 11111111 as 256, as I'm not sure whether you want >>>to start counting for zero with this. It's a simple matter to change.""" >>> tempList = ['0' for x in range(bits)] >>> >>> for bitPlace in range(bits, -1, -1): >>> if decimalInt - 2**bitPlace >= 0: >>> tempList[bitPlace] = '1' >>> decimalInt = decimalInt - 2**bitPlace >>> if bigEndian: >>> tempList.reverse() >>> >>> outPut = ''.join(tempList) >>> >>> if truncExcess: >>> if bigEndian: >>> outPut=outPut.lstrip('0') >>> else: >>> outPut=outPut.rstrip('0') >>> >>> return outPut >>> >>> >>>------------------------------------------------------------------------ >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From dyoo at hkn.eecs.berkeley.edu Tue Feb 8 11:18:10 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 8 11:18:43 2005 Subject: [Tutor] CRC-16 calculation In-Reply-To: <1107847715.4673.9.camel@KMA.accesstel> Message-ID: On Tue, 8 Feb 2005, Johan Geldenhuys wrote: > I have a data packet in Hex values and need to determine how to > calculate the CRC-16 bit checksum for these values: > > 0x55,0x00,0x0A,0x01,0x01, 0x01,0xFF,0x00,0xDC,0xCC > Sync| Lenght |source addr|dest. adr |Data| CRC check| > > This example shows me the CRC checksum, but if I change the source addr, > this chechsum is no longer valid. Hi Johan, I'm not exactly sure what you are asking: are you looking for an implementation of the CRC-16 algorithm in Python? Or are you asking how it actually works? If you'd like to learn how CRC error detection works, the web site: http://www.ross.net/crc/crcpaper.html has a nice tutorial that explain their fundamentals. If you are looking for a CRC-16 implementation, there appears to be one here: http://mail.python.org/pipermail/python-list/2004-January/204983.html From alan.gauld at freenet.co.uk Tue Feb 8 11:28:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 11:28:32 2005 Subject: [Tutor] (no subject) References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel>X-Antivirus: avast! (VPS 0505-2, 05/02/2005), Outbound message Message-ID: <06c601c50dc9$05883f90$68b78851@xp> Subject: Re: [Tutor] Hex to Str - still an open issue Date: Tue, 8 Feb 2005 10:29:07 -0000 MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-Transfer-Encoding: 7bit X-Priority: 3 X-MSMail-Priority: Normal X-Mailer: Microsoft Outlook Express 6.00.2800.1437 X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1441 > >>> binary(2) > '00000000000000000000000000000010' > >>> int(00000000000000000000000000000010) > 8 In Python (and most C based languages) a number starting with 0 is assumed to be in octal. so 010 in octal is 8 in decimal. Alan g. From jsmith at medplus.com Tue Feb 8 14:37:31 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 8 14:37:37 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Alan, That's no good. You still get something printed out. In this case: None Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Monday, February 07, 2005 6:15 PM To: Smith, Jeff; Bob Gailer; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] That's actually worse than you might think. Try this: > def p(): pass > ftable = { 'a' : lambda: 'a', > 'd' : lambda: p} That should be: 'd': p} ie No lambda used at all. I wish Python had real lambdas! > And what you get is: > Yep, coz the lambda returns a function object! Which it should, I just shouldn't have used lambda there. My bad, Alan G. From javier at ruere.com.ar Tue Feb 8 14:26:45 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Tue Feb 8 14:42:03 2005 Subject: [Tutor] Re: Have I run into a limitation of Pickle? In-Reply-To: References: Message-ID: Johan Kohler wrote: > Hi, > In the attached code, I'm trying to pickle and unpickle > (1) an object containing a list of dictionaries. > (2) an object containing a list objects each containing a dictionary. > [successful usecase] > > but (2) fails with the following error: > > <__main__.User instance at 0x41a56fac> > <__main__.User instance at 0x41a56f2c> > Traceback (most recent call last): > File "/usr/lib/python2.3/site-packages/sm/scriptutils.py", line 49, > in run > exec codeObject in mainDict > File "", line 87, in ? > File "", line 79, in loadbroken > File "", line 33, in readfromfile > File "/usr/lib/python2.3/pickle.py", line 1390, in load > return Unpickler(file).load() > File "/usr/lib/python2.3/pickle.py", line 872, in load > dispatch[key](self) > File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst > klass = self.find_class(module, name) > File "/usr/lib/python2.3/pickle.py", line 1140, in find_class > klass = getattr(mod, name) > AttributeError: 'module' object has no attribute 'User' > Exception raised while running script > --- > > I hope this is not a limitation of Pickle, because that would mean I > have to change a large section of my code :-( Pickle can handle any object but it needs the definition of the class of the object to be available in order to unpickle. For example: .>>> class A: pass .... .>>> a = A() .>>> import pickle .>>> s = pickle.dumps(a) .>>> s '(i__main__\nA\np0\n(dp1\nb.' .>>> pickle.loads(s) <__main__.A instance at 0x403fdcec> .>>> del A .>>> pickle.loads(s) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 1083, in load_inst klass = self.find_class(module, name) File "/usr/lib/python2.3/pickle.py", line 1140, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'A' The tracebacks are similar. It seems class User is not available when unpickling in the second case. Javier PS: I have not actually looked at the code so YMMV. :p From jsmith at medplus.com Tue Feb 8 14:42:54 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 8 14:43:04 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Jeff, It looks like that finally is the simplest expression of the original switch statement: import sys def p(): pass ftable = { 'a' : lambda: sys.stdout.write('a\n'), 'b' : lambda: sys.stdout.write('b or c\n'), 'c' : lambda: sys.stdout.write('b or c\n'), 'd' : p } ftable.get(var, lambda: sys.stdout.write('default case\n'))() I do note that it took this group of experienced programmers several tries to impliment this simple switch statement without actually using switch. I dare say with standard switch syntax we would've had it right the first time :-) Jeff -----Original Message----- From: Jeff Shannon [mailto:jeff@ccvcorp.com] Sent: Monday, February 07, 2005 9:19 PM To: tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] Alan Gauld wrote: >>As an aside, I did try to create a lambda based solution but was >>unable. Let me know what's wrong: >> >>ftable = { 'a' : lambda: print 'a', >>SyntaxError: invalid syntax > > I did say "if Python had *proper* lambdas..." > > Unfortunately Python insists on only having *expressions* as lambdas > and since print is a command not a function you can't use it in Python > lambdas! Dumb or what??! > > So you are stuck with predefining a bunch of one liner functions and > then creating a dictionary or going back to if/elif chains, which is > where we came in... :-) Well, in this particular case, if one really wants to use lambdas then one could (after importing sys, of course) replace the print statement with a call to sys.stdout.write() -- ftable = { 'a': lambda: sys.stdout.write('a\n'), ... } Note that sys.stdout.write() will *not* automatically add the newline that print does (which is why I've specified it in the above sample). Indeed, print can do all sorts of odd things with whitespace, leaving sys.stdout.write() as the best way to have real control over your output anyhow... Jeff Shannon Technician/Programmer Credit International _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From tktucker at gmail.com Tue Feb 8 16:34:32 2005 From: tktucker at gmail.com (Tom Tucker) Date: Tue Feb 8 16:34:37 2005 Subject: [Tutor] Match on current line and next line. Possible? Message-ID: <2a278ffe05020807347045c8ad@mail.gmail.com> Hello! How can I instruct Python to match on the current line and the next line? Assumptions; - We are reading in one line at a time BROKEN EXAMPLE (discussion) ###################### file = open('/somefile','r').readlines() for line in file: match_one = re.search('^Python', line) match_two = re.search('^\tBLAH', line) if match_one and nextline == match_two: do_something() Maybe this just isn't possible, since we are working line by line. Any suggestions? Tom From kent37 at tds.net Tue Feb 8 16:53:00 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 16:52:57 2005 Subject: [Tutor] Match on current line and next line. Possible? In-Reply-To: <2a278ffe05020807347045c8ad@mail.gmail.com> References: <2a278ffe05020807347045c8ad@mail.gmail.com> Message-ID: <4208E05C.9080301@tds.net> Tom Tucker wrote: > Hello! How can I instruct Python to match on the current line and the > next line? > BROKEN EXAMPLE (discussion) > ###################### > file = open('/somefile','r').readlines() > for line in file: > match_one = re.search('^Python', line) > match_two = re.search('^\tBLAH', line) > if match_one and nextline == match_two: > do_something() > match_one = None for line in open(...): match_two = re.search('^\tBLAH', line) if match_one and match_two: do_something() match_one = re.search('^Python', line) Add a last_line variable as well if do_something() needs access to the line data. Kent From pierre.barbier at cirad.fr Tue Feb 8 16:55:36 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue Feb 8 16:53:42 2005 Subject: [Tutor] Match on current line and next line. Possible? In-Reply-To: <2a278ffe05020807347045c8ad@mail.gmail.com> References: <2a278ffe05020807347045c8ad@mail.gmail.com> Message-ID: <4208E0F8.1030508@cirad.fr> MMmh ... one way to do that : Py> file_content = open('/somefile', 'r').readlines() Py> next_file_content = iter(file_content) Py> next_file_content.next() Py> for (line, next_line) in izip(file_content, next_file_content): Py> match_one = re.search('^Python', line) Py> match_two = re.search('^\tBLAH', line) Py> if match_one and nextline == match_two: Py> do_something() Pierre Tom Tucker a ?crit : > Hello! How can I instruct Python to match on the current line and the > next line? > > > Assumptions; > - We are reading in one line at a time > > > BROKEN EXAMPLE (discussion) > ###################### > file = open('/somefile','r').readlines() > for line in file: > match_one = re.search('^Python', line) > match_two = re.search('^\tBLAH', line) > if match_one and nextline == match_two: > do_something() > > > Maybe this just isn't possible, since we are working line by line. > > Any suggestions? > > > Tom > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Tue Feb 8 17:16:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 17:16:31 2005 Subject: [Tutor] Match on current line and next line. Possible? In-Reply-To: <4208E0F8.1030508@cirad.fr> References: <2a278ffe05020807347045c8ad@mail.gmail.com> <4208E0F8.1030508@cirad.fr> Message-ID: <4208E5E4.7060300@tds.net> Hmm, this would be a good use of itertools.tee() (Python 2.4 only): import itertools iter1, iter2 = itertools.tee(open('/somefile', 'r')) iter2.next() for line, next_line in izip(iter1, iter2): ... Kent Pierre Barbier de Reuille wrote: > MMmh ... one way to do that : > > Py> file_content = open('/somefile', 'r').readlines() > Py> next_file_content = iter(file_content) > Py> next_file_content.next() > Py> for (line, next_line) in izip(file_content, next_file_content): > Py> match_one = re.search('^Python', line) > Py> match_two = re.search('^\tBLAH', line) > Py> if match_one and nextline == match_two: > Py> do_something() > > Pierre > > Tom Tucker a ?crit : > >> Hello! How can I instruct Python to match on the current line and the >> next line? >> >> >> Assumptions; >> - We are reading in one line at a time >> >> >> BROKEN EXAMPLE (discussion) >> ###################### >> file = open('/somefile','r').readlines() >> for line in file: >> match_one = re.search('^Python', line) >> match_two = re.search('^\tBLAH', line) >> if match_one and nextline == match_two: >> do_something() >> >> >> Maybe this just isn't possible, since we are working line by line. >> Any suggestions? >> >> Tom >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From WilliTf at dshs.wa.gov Tue Feb 8 18:49:51 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Tue Feb 8 18:50:04 2005 Subject: [Tutor] executing SAS and passing parameters Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC2E@dshs-exch2.dshs.wa.lcl> Greetings, I am trying to use python to run a SAS program by passing the needed parameters. I am able to start SAS, but unable to start the correct SAS program with its parameters. Any assistance you could provide will be appreciated. Tom Williams DSHS - Research and Data Analysis Division 14th and Jefferson, MS: 45204 Olympia, WA 98504-5204 360.902.0764 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/cb30e823/attachment.html From alan.gauld at freenet.co.uk Tue Feb 8 19:24:29 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 19:26:30 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <06d601c50e0b$6e1b9e20$68b78851@xp> > That's no good. You still get something printed out. In this case: > > None Of course, silly me, p will return the default value None, you need to replace the pass with return '' or, I guess use the lambda... > ftable = { 'a' : lambda: 'a',... > 'd' : lambda: ''} Now it should work and is consistent again! But only for this trivial case of printing a label... Alan G. From john.ertl at fnmoc.navy.mil Tue Feb 8 19:31:32 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue Feb 8 19:30:20 2005 Subject: [Tutor] What is in the traceback object Message-ID: I have a bit of code that uses a module and I am trying to get more info on the error. I am using this bit of code: try: rhfill = Ngl.contour(wks,rhisobar,rh_res) except: execType,value,tracebak = sys.exc_info()[:3] print execType print value print tracebak In the log file I get this: exceptions.SystemError error return without exception set How do I get the actual traceback so I can read it? Thanks, John Ertl -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/0e92e952/attachment.html From jsmith at medplus.com Tue Feb 8 19:32:57 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Tue Feb 8 19:33:08 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] Message-ID: Not to be nit-picky but it's still not the same. The switch would give no output but yours would give a newline. I think the sys write solution would be the closest equivalent...and took a lot longer for us to code correctly :-) Jeff -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Tuesday, February 08, 2005 1:24 PM To: Smith, Jeff; Bob Gailer; tutor@python.org Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT] > That's no good. You still get something printed out. In this case: > > None Of course, silly me, p will return the default value None, you need to replace the pass with return '' or, I guess use the lambda... > ftable = { 'a' : lambda: 'a',... > 'd' : lambda: ''} Now it should work and is consistent again! But only for this trivial case of printing a label... Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Feb 8 19:39:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 8 19:39:07 2005 Subject: [Tutor] What is in the traceback object In-Reply-To: Message-ID: On Tue, 8 Feb 2005, Ertl, John wrote: > I have a bit of code that uses a module and I am trying to get more info > on the error. > > I am using this bit of code: > > try: > rhfill = Ngl.contour(wks,rhisobar,rh_res) > except: > execType,value,tracebak = sys.exc_info()[:3] > print execType > print value > print tracebak > > In the log file I get this: > > exceptions.SystemError > error return without exception set > > > How do I get the actual traceback so I can read it? Hi John, You can use the 'traceback' module: http://www.python.org/doc/lib/module-traceback.html Use the traceback.print_exc() function within the except block: it'll automatically pull information from sys.exc_info() for you: ###### try: rhfill = Ngl.contour(wks,rhisobar,rh_res) except: traceback.print_exc() ###### Best of wishes to you! From john.ertl at fnmoc.navy.mil Tue Feb 8 19:42:27 2005 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Tue Feb 8 19:41:18 2005 Subject: [Tutor] What is in the traceback object Message-ID: Danny, That is great...every time I have a problem someone has already solved it...the other problem is finding that solution...Thanks again. John Ertl -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Tuesday, February 08, 2005 10:39 To: Ertl, John Cc: 'tutor@python.org' Subject: Re: [Tutor] What is in the traceback object On Tue, 8 Feb 2005, Ertl, John wrote: > I have a bit of code that uses a module and I am trying to get more info > on the error. > > I am using this bit of code: > > try: > rhfill = Ngl.contour(wks,rhisobar,rh_res) > except: > execType,value,tracebak = sys.exc_info()[:3] > print execType > print value > print tracebak > > In the log file I get this: > > exceptions.SystemError > error return without exception set > > > How do I get the actual traceback so I can read it? Hi John, You can use the 'traceback' module: http://www.python.org/doc/lib/module-traceback.html Use the traceback.print_exc() function within the except block: it'll automatically pull information from sys.exc_info() for you: ###### try: rhfill = Ngl.contour(wks,rhisobar,rh_res) except: traceback.print_exc() ###### Best of wishes to you! From askoose at sandia.gov Tue Feb 8 21:03:50 2005 From: askoose at sandia.gov (Kooser, Ara S) Date: Tue Feb 8 21:04:22 2005 Subject: [Tutor] Printing columns of data Message-ID: Hello all, I am writing a program to take a data file, divide it up into columns and print the information back with headers. The data files looks like this 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00 -0.6024320E-04 0.4529416E-05 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00 -0.2290866E-03 0.4187074E-03 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00 -0.4953443E-03 0.2383621E-02 etc... 10.0 ... So I wrote the program included below and it only prints the last line of the file. Timestep PE 10.0 -3091.80609 I have one question. Do I need to put ts and pe into a list before I print then to screen or I am just missing something. Thanks. Ara import string inp = open("fort.44","r") all_file = inp.readlines() inp.close() outp = open("out.txt","w") cols = map(string.split,all_file) ##print cols Data = {} for line in cols: ts = line[0] # print line[0] pe = line[1] # print line[1] print """ Timestep PE""" print "%s %s " % (ts,pe) outp.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/3ba3b3ec/attachment.htm From jeff at ccvcorp.com Tue Feb 8 21:41:26 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Feb 8 21:40:33 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] In-Reply-To: References: Message-ID: <420923F6.6050103@ccvcorp.com> Smith, Jeff wrote: > Jeff, > > It looks like that finally is the simplest expression of the original > switch statement: > > import sys > def p(): > pass > ftable = { 'a' : lambda: sys.stdout.write('a\n'), > 'b' : lambda: sys.stdout.write('b or c\n'), > 'c' : lambda: sys.stdout.write('b or c\n'), > 'd' : p } > ftable.get(var, lambda: sys.stdout.write('default case\n'))() > > I do note that it took this group of experienced programmers several > tries to impliment this simple switch statement without actually using > switch. I dare say with standard switch syntax we would've had it right > the first time :-) I wasn't following this thread all the way through, but to be honest, I'd have solved this differently -- that may be the best "direct translation" of some switch statement, but that doesn't mean it's the best-fit solution here. ISTM that, given the desire to print some text (or nothing) based on the contents of a variable, I would *not* handle the output inside the "switch" -- that is, I'd (conditionally) print a value from a string-containing dictionary, rather than use a table of functions that print strings. table = { 'a': 'a', 'b': 'b or c', 'c': 'b or c', 'd': None } result = table.get(var, 'default case') if result: print result This, to my mind, is much cleaner -- you're factoring out the repeated code, whether print statement or call to sys.stdout.write(), reducing the complexity of the dict. You're making flow control much more straightforward. You're making the whole thing easier to read. The key, here, is that instead of saying "I want a switch, how can I implement that in Python?", I've taken the approach of "The end result I want is ***; what tools does Python offer to achieve that?" This conceptual shift is, IMHO, *the* most important mental hurdle in learning a [second/third/n-th] language. Jeff Shannon Technician/Programmer Credit International From kent37 at tds.net Tue Feb 8 21:49:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue Feb 8 21:49:24 2005 Subject: [Tutor] Printing columns of data In-Reply-To: References: Message-ID: <420925D1.3050809@tds.net> Kooser, Ara S wrote: > Hello all, > > I am writing a program to take a data file, divide it up into columns > and print the information back with headers. The data files looks like this > > 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00 > -0.6024320E-04 0.4529416E-05 > 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00 > -0.2290866E-03 0.4187074E-03 > 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00 > -0.4953443E-03 0.2383621E-02 > etc? > 10.0 ... > > So I wrote the program included below and it only prints the last line > of the file. > > Timestep PE > 10.0 -3091.80609 > > I have one question. Do I need to put ts and pe into a list before I > print then to screen or I am just missing something. Thanks. You should print the header before the loop, and the contents inside the loop. So: print """ Timestep PE""" for line in cols: ts = line[0] # print line[0] pe = line[1] # print line[1] # The next line is indented so it is included in the loop: print "%s %s " % (ts,pe) You probably will want to set the field width in the print format so the columns all line up, something like this (just guessing on the widths): print "%10s %10" % (ts,pe) You might be interested in this recipe which does a very slick job of pretty-printing a table: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 Kent > > Ara > > import string > > inp = open("fort.44","r") > all_file = inp.readlines() > inp.close() > > outp = open("out.txt","w") > > cols = map(string.split,all_file) > ##print cols > > Data = {} > for line in cols: > ts = line[0] > # print line[0] > pe = line[1] > # print line[1] > > print """ > > Timestep PE""" > print "%s %s " % (ts,pe) > > > outp.close() > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Tue Feb 8 21:51:39 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 21:50:50 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <06db01c50e1f$fd1e65d0$68b78851@xp> > Not to be nit-picky but it's still not the same. The switch would give > no output but yours would give a newline. I think the sys write > solution would be the closest equivalent...and took a lot longer for us > to code correctly :-) I can't really argue with that! :-) Me, I'm blaming the lambdas! Alan g. From bgailer at alum.rpi.edu Tue Feb 8 21:57:33 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Feb 8 21:52:03 2005 Subject: [Tutor] Printing columns of data In-Reply-To: References: Message-ID: <6.1.2.0.0.20050208135547.03615ff0@mail.mric.net> At 01:03 PM 2/8/2005, Kooser, Ara S wrote: >Content-class: urn:content-classes:message >Content-Type: multipart/alternative; > boundary="----_=_NextPart_001_01C50E19.4E45912A" > >Hello all, > > I am writing a program to take a data file, divide it up into columns > and print the information back with headers. The data files looks like this > > 0.0 -3093.44908 -3084.59762 387.64329 26.38518 0.3902434E+00 > -0.6024320E-04 0.4529416E-05 > 1.0 -3094.09209 -3084.52987 391.42288 105.55994 0.3889897E+00 > -0.2290866E-03 0.4187074E-03 > 2.0 -3094.59358 -3084.88826 373.64911 173.44885 0.3862430E+00 > -0.4953443E-03 0.2383621E-02 > etc > 10.0 ... > >So I wrote the program included below and it only prints the last line of >the file. > >Timestep PE >10.0 -3091.80609 > >I have one question. Do I need to put ts and pe into a list before I print >then to screen or I am just missing something. Thanks. > >Ara > >import string > >inp = open("fort.44","r") >all_file = inp.readlines() >inp.close() > >outp = open("out.txt","w") > >cols = map(string.split,all_file) >##print cols > >Data = {} >for line in cols: > ts = line[0] ># print line[0] > pe = line[1] ># print line[1] > >print """ > >Timestep PE""" >print "%s %s " % (ts,pe) > >outp.close() Put the print statement in the for loop. for line in cols: ... print "%s %s " % (ts,pe) Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050208/03a98ee6/attachment.htm From alan.gauld at freenet.co.uk Tue Feb 8 22:51:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 22:50:55 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: Message-ID: <06fa01c50e28$65ebcc80$68b78851@xp> As one last option... (And I confess I've kind of got off the original thread here, this is just catching my interest now! :-) try: ftable = { 'a' : lambda: 'a', 'b' : lambda: 'b or c', 'c' : lambda: 'b or c' } print ftable[var] except KeyError: pass Which is actually how I would probably code it if I wqs using a dictionary (well actually I'd miss out the lambdas in this case, but let's imagine we are doing something just a tad more exciting!) Using the get() method actrually makes it more complex in this case. But if we really do want a specific 'd' that does nothing (or more specifically a default that does *something*, then we are back to that bad ol' def p() again.) Now lets look at a putative switch version: switch var: case 'a' : print 'a' case 'b' : case 'c' : print 'b or c' else : pass It is one line less, but is not reusable, so if the switch needs to be used more than once - as is often the case in label printing scenarios particularly - the dictionary wins. But for a one-off the switch wins. The switch also, by using drop through has the advantage of only a single message for 'b or c' - a maintenance win. (But that can be ameliorated by having the messages in a separate table someplace - which is good practice anyhow for multi lingual code.) The final option is the if/elif option: if var == 'a': print 'a' elif var == 'b' or var == 'c': print 'b or c' Which is the shortest of all of them and for simple label printing is probably the best option too! But once the number of cases increases, performance starts to wane and we go back to a dictionary or our missing switch... What does all of this tell us? Probably only that the old adage KISS is right: Keep It Simple Stupid! :-) > I do note that it took this group of experienced programmers several > tries to impliment this simple switch statement without actually using > switch. I dare say with standard switch syntax we would've had it right > the first time :-) Oh I dunno, I've seen some pretty weird switch code. But if the switch didn't allow drop through it might've worked first time ;-) Alan G. From alan.gauld at freenet.co.uk Tue Feb 8 22:56:30 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 22:55:39 2005 Subject: [Tutor] executing SAS and passing parameters References: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC2E@dshs-exch2.dshs.wa.lcl> Message-ID: <071001c50e29$0ca16940$68b78851@xp> > I am trying to use python to run a SAS program by passing the needed > parameters. I am able to start SAS, but unable to start the correct SAS > program with its parameters. Not being familiar with SAS or its parameters we'll need more clues... > Any assistance you could provide will be appreciated. Can you show us what you used to start SAS? Can you tell us exactly what happened? - any errors etc? Can you show us how you'd do it outside of Python? Can you tell us which OS you are using? With that info we should be able to make a stab at it. Alan G. From alan.gauld at freenet.co.uk Tue Feb 8 23:02:01 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 23:02:01 2005 Subject: [Tutor] Printing columns of data References: Message-ID: <073801c50e29$d1c3b840$68b78851@xp> > So I wrote the program included below and it only prints the last line > of the file. > I have one question. Do I need to put ts and pe into a list before I > print then to screen or I am just missing something. Thanks. You just need to indent your last print statement so it is inside the loop and put the heading print statement before the loop. print """ Timestep PE""" for line in cols: ts = line[0] pe = line[1] print "%s %s " % (ts,pe) You might also like to use stroing formatting to force column widths to be constant: print "%20s%20s" % (ts,pe) should illustrate...adjust the size to suit. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Feb 8 23:04:59 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Feb 8 23:04:05 2005 Subject: [Tutor] Are you allowed to shoot camels? [kinda OT] References: <420923F6.6050103@ccvcorp.com> Message-ID: <073d01c50e2a$3c1128e0$68b78851@xp> > table = { 'a': 'a', 'b': 'b or c', 'c': 'b or c', 'd': None } > result = table.get(var, 'default case') > if result: > print result > > This, to my mind, is much cleaner -- you're factoring out the repeated > code, whether print statement or call to sys.stdout.write(), reducing > the complexity of the dict. You're making flow control much more > straightforward. You're making the whole thing easier to read. Yep, the lambda stuff etc is there on the assumption that we are trying to do something a tad more interesting than just print the label - but as it happens printing the label has been hard enough!! :-) Alan G. From WilliTf at dshs.wa.gov Tue Feb 8 23:04:43 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Tue Feb 8 23:05:00 2005 Subject: [Tutor] executing SAS and passing parameters Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC31@dshs-exch2.dshs.wa.lcl> I'll do my best to answer these questions for you. I am able to start the SAS executable from python, but not the specific SAS program in question. When this executable is executed, the typical SAS environment is displayed (SAS editor Window, SAS libraries, and the output and log windows). I want to have a specific SAS program executing with the assigned parameters that will be read into a SAS macro. This SAS program was originally called from an AML (Arc Macro Language), again, with the parameters passed to it. OS: WindowsNT Let me know if you need further information. Thanks again, Tom -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Tuesday, February 08, 2005 1:57 PM To: Williams, Thomas; tutor@python.org Subject: Re: [Tutor] executing SAS and passing parameters > I am trying to use python to run a SAS program by passing the needed > parameters. I am able to start SAS, but unable to start the correct SAS > program with its parameters. Not being familiar with SAS or its parameters we'll need more clues... > Any assistance you could provide will be appreciated. Can you show us what you used to start SAS? Can you tell us exactly what happened? - any errors etc? Can you show us how you'd do it outside of Python? Can you tell us which OS you are using? With that info we should be able to make a stab at it. Alan G. From carroll at tjc.com Wed Feb 9 01:31:42 2005 From: carroll at tjc.com (Terry Carroll) Date: Wed Feb 9 01:31:47 2005 Subject: [Tutor] executing SAS and passing parameters In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC31@dshs-exch2.dshs.wa.lcl> Message-ID: Ah, SAS. I used that a lot in the early '80s for general programming. I felt a lot about SAS then as I do about Python now. Enough of that. Can you show your python code that invokes SAS; and can you also show what you type at a command line that makes SAS run the way you want? Given the command line, it should be pretty straightforward to move the command line invocation into Python. On Tue, 8 Feb 2005, Williams, Thomas wrote: > I'll do my best to answer these questions for you. > > I am able to start the SAS executable from python, but not the specific SAS > program in question. When this executable is executed, the typical SAS > environment is displayed (SAS editor Window, SAS libraries, and the output > and log windows). I want to have a specific SAS program executing with the > assigned parameters that will be read into a SAS macro. > > This SAS program was originally called from an AML (Arc Macro Language), > again, with the parameters passed to it. > > OS: WindowsNT > > Let me know if you need further information. > > Thanks again, > Tom > > > -----Original Message----- > From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] > Sent: Tuesday, February 08, 2005 1:57 PM > To: Williams, Thomas; tutor@python.org > Subject: Re: [Tutor] executing SAS and passing parameters > > > I am trying to use python to run a SAS program by passing the needed > > parameters. I am able to start SAS, but unable to start the correct > SAS > > program with its parameters. > > Not being familiar with SAS or its parameters we'll need more clues... > > > Any assistance you could provide will be appreciated. > > Can you show us what you used to start SAS? > Can you tell us exactly what happened? - any errors etc? > Can you show us how you'd do it outside of Python? > Can you tell us which OS you are using? > > With that info we should be able to make a stab at it. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Wed Feb 9 03:17:21 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 9 03:22:15 2005 Subject: [Tutor] calling subroutines into program References: <5.1.0.14.0.20050207140910.00bbe528@mailhost.geo.vu.nl> <42077CD2.5040107@tds.net> <4207DBE2.6000109@tds.net> Message-ID: <004b01c50e4e$3dab4680$935328cf@JSLAPTOP> > Liam Clarke wrote: >> oh? Is is the negative? > > No, the decimal fraction. It's easy enough to try it: Not exactly, it's a combination of string *and* decimal fraction. >>> int('-945') -945 >>> int('-945.0') Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for int(): -945.0 >>> int(-945.0) -945 >>> Jacob > >>> int('950') > 950 > >>> int('-950') > -950 > >>> int('950.00') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): 950.00 > >>> int('-950.00') > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for int(): -950.00 > > Kent > From keridee at jayco.net Wed Feb 9 05:12:46 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 9 05:12:26 2005 Subject: [Tutor] manipulating a file References: Message-ID: <008301c50e5d$a15a8a60$935328cf@JSLAPTOP> > import os > > srcfile = open('/var/log/httpd-access.log.bak', 'r') > dstfile = open('/var/log/httpd-access.log', 'w') > while 1: > lines = srcfile.readlines() > if not lines: break > # print lines > for i in lines: > if len(i) < 2086: > #print i > dstfile.write(i) > > srcfile.close() > dstfile.close() Okay, so how about... a = '/var/log/httpd-access.log' srcfile = open(a,'r') dstfile = open(a+'.bak,'w') for x in srcfile: try: x[2086] except: print >> dstfile, x srcfile.close() dstfile.close() 1) Put filename in seperate variable because I'm lazy and didn't want to type it twice. 2) Implemented the file iteration technique. 3) Odd alternative way for line check. Remeber, there's more than one way to do it! 4) Implemented the cool redirection of print statement Not bad, what do you thing, Reed? Does anybody have any input on alternative length check technique? Will it be less efficient than just using len()? HTH, Jacob From keridee at jayco.net Wed Feb 9 05:29:39 2005 From: keridee at jayco.net (Jacob S.) Date: Wed Feb 9 05:29:46 2005 Subject: [Tutor] Match on current line and next line. Possible? References: <2a278ffe05020807347045c8ad@mail.gmail.com> Message-ID: <00b901c50e60$09d1a270$935328cf@JSLAPTOP> It's getting late, so if someone already suggested something like this, just pretend to smack me across the face, and I'll flinch later... import re fi = open('/somefile','r') ## Don't do readlines and bring the whole file in memory... match1 = re.compile('^Python') match2 = re.compile('^/tBLAH') prevline = '' for line in fi: if match1.search(line) and match2.search(line): do_something() prevline = line fi.close() HTH, Jacob > Hello! How can I instruct Python to match on the current line and the > next line? > > > Assumptions; > - We are reading in one line at a time > > > BROKEN EXAMPLE (discussion) > ###################### > file = open('/somefile','r').readlines() > for line in file: > match_one = re.search('^Python', line) > match_two = re.search('^\tBLAH', line) > if match_one and nextline == match_two: > do_something() > > > Maybe this just isn't possible, since we are working line by line. > > Any suggestions? > > > Tom > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From james2dope at yahoo.com Wed Feb 9 05:35:39 2005 From: james2dope at yahoo.com (james middendorff) Date: Wed Feb 9 05:35:43 2005 Subject: [Tutor] help Message-ID: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> I want to use mysqldb to add people into a database, but when I ask for the certain fields like Name, PhoneNumber and such, I cannot get it to put them in as a string? I am not sure what I am doing wrong but here is my code thanks to anyone who helps: import MySQLdb username = raw_input("what is your username? ") password = raw_input("what is the password? ") database = raw_input("what database do you want to enter? ") conn = MySQLdb.connect(host='127.0.0.1', user=username, passwd=password, db=database) c = conn.cursor() Name = raw_input("what is the name you want to add? ") PhoneNumber = input("what is the phone number for the person you are adding? ") Address = raw_input("what is the address for the person you are adding? ") EmailAddress = raw_input("what is the email address of the person you are adding? ") BirthDate = raw_input("what is the birthdate of the person you are adding? year-month-day") c.execute (""" INSERT INTO people () VALUES ('%s','%s','%s','%s','%s'); """)% (Name, PhoneNumber, Address, EmailAddress, BirthDate) print "%d rows were inserted" % c.rowcount ===== "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From reed at intersiege.com Wed Feb 9 06:13:37 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Wed Feb 9 06:14:30 2005 Subject: [Tutor] Re: manipulating a file In-Reply-To: <20050207091852.87090.qmail@web53808.mail.yahoo.com> References: <20050207091852.87090.qmail@web53808.mail.yahoo.com> Message-ID: Shitiz Bansal wrote: > Hi, > I do see a problem. > The script is fine, the problem lies else where. > > Your script is trying to write log.bak to log, it > should b other way round. > > i.e.... > srcfile = open('/var/log/httpd-access.log', 'r') > dstfile = open('/var/log/httpd-access.log.bak', 'w') > > hope that fixes it. > > About the efficiency, why do u need python at all... > How abt a simple shell command.... > cat httpd-access.log>>log.bak > > Shitiz > > --- Danny Yoo wrote: > > >> >>On Mon, 7 Feb 2005, Reed L. O'Brien wrote: >> >> >>>I want to read the httpd-access.log and remove any >> >>oversized log records >> >>>I quickly tossed this script together. I manually >> >>mv-ed log to log.bak >> >>>and touched a new logfile. >>> >>>running the following with print i uncommented >> >>does print each line to >> >>>stdout. but it doesn't write to the appropriate >> >>file... >> >> >>Hello! >> >>Let's take a look at the program again: >> >>### >>import os >>srcfile = open('/var/log/httpd-access.log.bak', 'r') >>dstfile = open('/var/log/httpd-access.log', 'w') >>while 1: >> lines = srcfile.readlines() >> if not lines: break >> for i in lines: >> if len(i) < 2086: >> dstfile.write(i) >>srcfile.close() >>dstfile.close() >>### >> >> >>>a) what am I missing? >>>b) is there a less expensive way to do it? >> >>Hmmm... I don't see anything offhand that prevents >>httpd-access.log from >>containing the lines you expect. Do you get any >>error messages, like >>permission problems, when you run the program? >> >>Can you show us how you are running the program, and >>how you are checking >>that the resulting file is empty? >> >> >>Addressing the question on efficiency and expense: >>yes. The program at >>the moment tries to read all lines into memory at >>once, and this is >>expensive if the file is large. Let's fix this. >> >> >>In recent versions of Python, we can modify >>file-handling code from: >> >>### >>lines = somefile.readlines() >>for line in lines: >> ... >>### >> >>to this: >> >>### >>for line in somefile: >> ... >>### >> >>That is, we don't need to extract a list of 'lines' >>out of a file. >>Python allows us to loop directly across a file >>object. We can find more >>details about this in the documentation on >>"Iterators" (PEP 234): >> >> http://www.python.org/peps/pep-0234.html >> >>Iterators are a good thing to know, since Python's >>iterators are deeply >>rooted in the language design. (Even if it they >>were retroactively >>embedded. *grin*) >> >> >>A few more comments: the while loop appears >>unnecessary, since on the >>second run-through the loop, we'll have already read >>all the lines out of >>the file. (I am assuming that nothing is writing to >>the backup file at >>the time.) If the body of a while loop just runs >>once, we don't need a >>loop. >> >>This simplifies the code down to: >> >>### >>srcfile = open('/var/log/httpd-access.log.bak', 'r') >>dstfile = open('/var/log/httpd-access.log', 'w') >>for line in srcfile: >> if len(line) < 2086: >> dstfile.write(line) >>srcfile.close() >>dstfile.close() >>### >> >> >>I don't see anything else here that causes the file >>writing to fail. If >>you can tell us more information on how you're >>checking the program's >>effectiveness, that may give us some more clues. >> >>Best of wishes to you! >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Helps protect you from nasty viruses. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > I am actually mv log to bak and write the non offening entries back to log. I can not be working on log as it needs to be able to accept new entries as the webserver is accessed. Plus I am learning python, I could have sh scripted it easy but am broadening my horizons... reed From nixonron at yahoo.com Wed Feb 9 06:36:55 2005 From: nixonron at yahoo.com (Ron Nixon) Date: Wed Feb 9 06:37:02 2005 Subject: [Tutor] print out lines that start with a word Message-ID: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Can anyone tell me what I've done wrong in this script. I'm trying to get only the lines that start with "This" for a text file. Here's what I wrote: >>> import re >>> f = open('c:/lines.txt').readlines() >>> for line in f: match = re.search('^This',f) if line == match: print match here's the error message I got: Traceback (most recent call last): File "", line 2, in -toplevel- match = re.search('^This',f) File "C:\Python24\lib\sre.py", line 134, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer Thanks in advance __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Wed Feb 9 08:15:03 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 9 08:15:09 2005 Subject: [Tutor] Re: manipulating a file In-Reply-To: Message-ID: > >>This simplifies the code down to: > >> > >>### > >>srcfile = open('/var/log/httpd-access.log.bak', 'r') > >>dstfile = open('/var/log/httpd-access.log', 'w') > >>for line in srcfile: > >> if len(line) < 2086: > >> dstfile.write(line) > >>srcfile.close() > >>dstfile.close() > >>### > >> > >> > I am actually mv log to bak and write the non offening entries back to > log. Hi Reed, Oh, so the web server is still continuing to write things onto the open log file then. Out of curiosity, what web server are you using? One remote possiblility for the weirdness might depend on how your web server writes new log messages into the file: perhaps it can automatically detect log file rotation, and may be overwriting http-access.log? It's very hard to say. I'll talk about this a little more below. > I can not be working on log as it needs to be able to accept new entries > as the webserver is accessed. Plus I am learning python, I could have > sh scripted it easy but am broadening my horizons... Sure, I think that's perfectly fine. I think there was some confusion on the list earlier, so I'm glad you cleared that up. I'm still trying to figure out what could be causing the problem. You mentioned that you were running the programs as root, so permission problems are probably not an issue. I don't think we have enough information to debug this, and I hate shooting arrows in random directions. I feel a little nervous programs that try to do 'in-place' changes. Conceptually, we're trying to swap out httpd_access out from underneath the httpd process's nose, and that might not work. If you're doing a 'mv', then the log messages should continue to log to the backup file, if I understand how apache works. Let's test something. Can you try writing the truncated log to another file, like '/var/log/http-access.truncated.log'? This at least should prevent any wacky writing conflicst between the httpd process and our log-filtering program. Also, what happens if instead of opening up explicit files you use standard input and output? Here's a modified program that uses sys.stdin and sys.stdout: ###### """Cut really long lines out of the output.""" import sys for line in sys.stdin: if len(line) < 2086: sys.stdout.write(line) sys.stdin.close() sys.stdout.close() ###### This can be equivalent to the previous program if we use the shell's file redirection. It also allows us to run the program on different input and output files with ease. Try it on some other files first and see that it does work on regular files first. Best of wishes to you! From cyresse at gmail.com Wed Feb 9 08:18:48 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 08:18:52 2005 Subject: [Tutor] print out lines that start with a word In-Reply-To: <20050209053656.60027.qmail@web20326.mail.yahoo.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: H Ron, >>> import re >>> f = open('c:/lines.txt').readlines() >>> for line in f: match = re.search('^This',f) if line == match: print match Hi Ron, Welcome to the wonderful world of Python. from re.search.__doc__ ; "Scan through string looking for a match to the pattern, returning a match object, or None if no match was found." OK, so if there's a match, you get an object returned, otherwise it returns None. So, you can boolean test this. I'm guessing you want to print lines that start with this. import re f = file('c:/lines.txt) #Also, you can iterate over a file for line in f: match = re.search('^This', line) #you want to search line by line? if match: print line else: print "No match" Or, you could store all the lines in a list to use afterwards - lineStore =[] for line in f: match = re.search('^This', line) #you want to search line by line? if match: lineStore.append(line) else: print "No match" On Tue, 8 Feb 2005 21:36:55 -0800 (PST), Ron Nixon wrote: > Can anyone tell me what I've done wrong in this > script. > > I'm trying to get only the lines that start with > "This" for a text file. > > Here's what I wrote: > > >>> import re > >>> f = open('c:/lines.txt').readlines() > >>> for line in f: > match = re.search('^This',f) > if line == match: > print match > > here's the error message I got: > > Traceback (most recent call last): > File "", line 2, in -toplevel- > match = re.search('^This',f) > File "C:\Python24\lib\sre.py", line 134, in search > return _compile(pattern, flags).search(string) > TypeError: expected string or buffer > > Thanks in advance > > > __________________________________ > Do you Yahoo!? > Read only the mail you want - Yahoo! Mail SpamGuard. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Wed Feb 9 08:33:22 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 9 08:33:27 2005 Subject: [Tutor] help In-Reply-To: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> Message-ID: On Tue, 8 Feb 2005, james middendorff wrote: > I want to use mysqldb to add people into a database, but when I ask for > the certain fields like Name, PhoneNumber and such, I cannot get it to > put them in as a string? I am not sure what I am doing wrong but here is > my code thanks to anyone who helps: Hi James, Ok, I see a few things in the execute statement that can be fixed. Let's first take a look at the code: > c.execute (""" > INSERT INTO people () > VALUES > ('%s','%s','%s','%s','%s'); > """)% (Name, PhoneNumber, Address, > EmailAddress, BirthDate) The SQL here has an empty column list: INSERT into people () ^^ and this is probably not a good idea: instead, list out the field names explicitely. The reason is because SQL tables don't necessarily imply a specific order. The empty column list approach is also not robust to SQL table changes in the future: if you add a new column into people, your existing code will certainly break since the number of values don't match the number of columns. More than that, though, is a silly syntax issue that's related to string interpolation. Let's pretend for the moment that we do fix the SQL column issue: ### c.execute (""" INSERT INTO people (name, phone_number, address, email_address, birthdate) VALUES ('%s','%s','%s','%s','%s'); """) % (Name, PhoneNumber, Address, EmailAddress, BirthDate) ### Brace yourself: you're not going to like this. One of the parenthesis is misplaced. You meant to write: ### c.execute (""" INSERT INTO people (name, phone_number, address, email_address, birthdate) VALUES ('%s','%s','%s','%s','%s'); """ % (Name, PhoneNumber, Address, EmailAddress, BirthDate) ) ### Don't worry, we all do this sometimes. *grin* Which brings up the point: at the moment, you're doing explicit string interpolation, but there are some special cases that the code above isn't considering. In particular, what happens if one of the names that get entered looks like: "D'Artagnan" Then all of the quotes get unbalanced, and we get a really messed up SQL statement. *grin* Most database systems provide a system to automatically do robust interpolation of values into a statement. Here's your execute(), using the robust approach: ### c.execute (""" INSERT INTO people (name, phone_number, address, email_address, birthdate) VALUES (%s,%s,%s,%s,%s); """, (Name, PhoneNumber, Address, EmailAddress, BirthDate) ) ### Not much changes here syntactically, but semanically, this is nicer: the cursor's execute() statement itself takes the tuple of values, and does the interpolation itself. Notice that there's no more quotes around the string values: the execute() will add them in for you. If you have more questions, please feel free to ask. Good luck to you! From kraus at hagen-partner.de Wed Feb 9 09:00:52 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 09:01:06 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <20050209053656.60027.qmail@web20326.mail.yahoo.com> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: Ron Nixon wrote: > Can anyone tell me what I've done wrong in this > script. > > I'm trying to get only the lines that start with > "This" for a text file. > > Here's what I wrote: > > >>>>import re >>>>f = open('c:/lines.txt').readlines() >>>>for line in f: > > match = re.search('^This',f) > if line == match: > print match > > Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they faster? What about good ol' startswith(): http://docs.python.org/lib/string-methods.html#l2h-204 Untested: f = open('c:/lines.txt').readlines() for line in f: if line.startswith('This'): print line # Or whatever match is, no regexp-expert here, sorry Wondering, Wolfram From cyresse at gmail.com Wed Feb 9 09:05:00 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 09:05:03 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: regexes are common across a lot of languages, even Java has them. Though the pain that would be I daren't not imagine. So the syntax is familiar, whereas string methods may not be. On Wed, 09 Feb 2005 09:00:52 +0100, Wolfram Kraus wrote: > Ron Nixon wrote: > > Can anyone tell me what I've done wrong in this > > script. > > > > I'm trying to get only the lines that start with > > "This" for a text file. > > > > Here's what I wrote: > > > > > >>>>import re > >>>>f = open('c:/lines.txt').readlines() > >>>>for line in f: > > > > match = re.search('^This',f) > > if line == match: > > print match > > > > > Pardon my ignorance, but why is everybody fond of regexps ;-) ? Are they > faster? What about good ol' startswith(): > http://docs.python.org/lib/string-methods.html#l2h-204 > Untested: > > f = open('c:/lines.txt').readlines() > for line in f: > if line.startswith('This'): > print line # Or whatever match is, no regexp-expert here, sorry > > Wondering, > Wolfram > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Wed Feb 9 09:30:09 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 09:30:24 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: Liam Clarke wrote: > regexes are common across a lot of languages, even Java has them. > Though the pain that would be I daren't not imagine. So the syntax is > familiar, whereas string methods may not be. But IMHO string methods are (more) explicit and readable, the name tells you what the method is doing. I know that sometimes regexp are really fine, e.g. extracting something from html or maybe speed issues (can anyone enlighten me on that one?), but for simple task like the OP's problem I'd always use string methods. Wolfram From pierre.barbier at cirad.fr Wed Feb 9 09:44:15 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed Feb 9 09:42:19 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: <4209CD5F.3090705@cirad.fr> Wolfram Kraus a ?crit : > Liam Clarke wrote: > >> regexes are common across a lot of languages, even Java has them. >> Though the pain that would be I daren't not imagine. So the syntax is >> familiar, whereas string methods may not be. > > But IMHO string methods are (more) explicit and readable, the name tells > you what the method is doing. I know that sometimes regexp are really > fine, e.g. extracting something from html or maybe speed issues (can > anyone enlighten me on that one?), but for simple task like the OP's > problem I'd always use string methods. > > Wolfram I completely agree ! Then, it will very probably be more efficient. And the methods (or functions) like "startwith" are avalaible in almost every string library ! Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 From cyresse at gmail.com Wed Feb 9 10:42:34 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 10:42:38 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: <4209CD5F.3090705@cirad.fr> References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <4209CD5F.3090705@cirad.fr> Message-ID: >>> x= ["Dude", 'How is it going man', ' '] >>> print x ['Dude', 'How is it going man', ' '] >>> j=[] >>> for item in x: ... if re.search('\S+',item): ... j.append(item) >>> print j ['Dude', 'How is it going man'] Now, I first did that in a Perl script, but it easily comes across to Python. \S+ will usually mean 'one or more non-whitespace characters'. Brilliant for when your first Perl script accidentally appended \n to everything, even \n and \t. *embarassed* Whereas, while I'm sure there is a string method that can do that, I'm not sure what it is. Also - say you have a list of words - j = " bag apple tomato cheese *marmite* sausages *scones*" and you wanted to pick up each word that was asterisked. I did this as a string method then a regex. >>> try: ... indexes=[] ... lastIndex = 0 ... while 1: ... x = j.index("*", lastIndex + 1) ... indexes.append(x) ... lastIndex = x ... except ValueError: ... pass ... >>> print indexes [4, 10] >>>myString = j[5:10] Now the regular expression - >>> x = re.finditer("\*(?P.*?)\*", j) >>> a = x.next() >>> print a.group('myString') apple Now, while the regEx syntax is a big harsh to begin with, once you get the hang of it, it's OK, and the string method version I used felt too 'hacky' for me. Of course, both only work with pairs of asterisks, so I guess that makes them both hacky. : ) That's my 2c, I use string methods for stuff like that .startswith, .endswith, if 'foo' in x stuff is good as well. But sometimes, a regex is the right tool for the job. Regards, Liam Clarke PS Pierre, my wife asked if you could write something in French so that she could try and read it, as she's trying to pick up her French again. If you don't mind. On Wed, 09 Feb 2005 09:44:15 +0100, Pierre Barbier de Reuille wrote: > Wolfram Kraus a ?crit : > > Liam Clarke wrote: > > > >> regexes are common across a lot of languages, even Java has them. > >> Though the pain that would be I daren't not imagine. So the syntax is > >> familiar, whereas string methods may not be. > > > > But IMHO string methods are (more) explicit and readable, the name tells > > you what the method is doing. I know that sometimes regexp are really > > fine, e.g. extracting something from html or maybe speed issues (can > > anyone enlighten me on that one?), but for simple task like the OP's > > problem I'd always use string methods. > > > > Wolfram > > I completely agree ! Then, it will very probably be more efficient. And > the methods (or functions) like "startwith" are avalaible in almost > every string library ! > > Pierre > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP > Botanique et Bio-informatique de l'Architecture des Plantes > TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Wed Feb 9 11:08:40 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 11:08:56 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <4209CD5F.3090705@cirad.fr> Message-ID: Liam Clarke wrote: >>>>x= ["Dude", 'How is it going man', ' '] >>>>print x > > ['Dude', 'How is it going man', ' '] > > >>>>j=[] >>>>for item in x: > > ... if re.search('\S+',item): > ... j.append(item) > > >>>>print j > > ['Dude', 'How is it going man'] What about: x= ["Dude", 'How is it going man', ' '] print [a for a in x if a.strip()] > Now, I first did that in a Perl script, but it easily comes across to > Python. \S+ will usually mean 'one or more non-whitespace characters'. > Brilliant for when your first Perl script accidentally appended \n to > everything, even \n and \t. *embarassed* > > Whereas, while I'm sure there is a string method that can do that, I'm > not sure what it is. Well the documentation on that is not sooo big ;-) > Also - say you have a list of words - > j = " bag apple tomato cheese *marmite* sausages *scones*" > > and you wanted to pick up each word that was asterisked. > I did this as a string method then a regex. > > > >>>>try: > > ... indexes=[] > ... lastIndex = 0 > ... while 1: > ... x = j.index("*", lastIndex + 1) > ... indexes.append(x) > ... lastIndex = x > ... except ValueError: > ... pass > ... > >>>>print indexes > > [4, 10] > >>>>myString = j[5:10] > That gives me [25, 33, 45, 52], propably a C&P bug? > Now the regular expression - > > >>>>x = re.finditer("\*(?P.*?)\*", j) >>>>a = x.next() >>>>print a.group('myString') > > apple Same error as above? And you said you want _all_ asteriksed words! How about this cute lil list comprehension: print [w for w in j.split() if words[0] == '*' and words[-1] == '*'] > Now, while the regEx syntax is a big harsh to begin with, once you get > the hang of it, it's OK, and the string method version I used felt too > 'hacky' for me. Of course, both only work with pairs of asterisks, so > I guess that makes them both hacky. : ) > > That's my 2c, I use string methods for stuff like that .startswith, .endswith, > if 'foo' in x stuff is good as well. But sometimes, a regex is the > right tool for the job. I didn't say that they are useless (and don't wanna troll or start a flameware), but IMHO they are a PITA when it comes to debugging. Ever touched a regexp after one year ;-)? > Regards, > > > Liam Clarke Greetings, Wolfram From kraus at hagen-partner.de Wed Feb 9 11:26:40 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 11:28:08 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <4209CD5F.3090705@cirad.fr> Message-ID: Damn! C&P-bug here to! Is this a virus? ;-) > print [w for w in j.split() if words[0] == '*' and words[-1] == '*'] Should be: print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] From cyresse at gmail.com Wed Feb 9 11:32:51 2005 From: cyresse at gmail.com (Liam Clarke) Date: Wed Feb 9 11:32:54 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <4209CD5F.3090705@cirad.fr> Message-ID: print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] Wouldn't that only work if it was bug *car* jeff? I can imagine bug*car*jeff would throw it. Cheers, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Wed Feb 9 11:48:23 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed Feb 9 11:48:36 2005 Subject: [Tutor] Re: print out lines that start with a word In-Reply-To: References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> <4209CD5F.3090705@cirad.fr> Message-ID: Liam Clarke wrote: > print [w for w in j.split() if w[0] == '*' and w[-1] == '*'] > > > Wouldn't that only work if it was bug *car* jeff? > > I can imagine bug*car*jeff would throw it. > > Cheers, > > Liam Clarke x = 'bug*car*jeff*foo*bar' [x.split('*')[a] for a in range(1,len(x.split('*')), 2)] When you mix * and spaces I will give up ;-)! Wolfram From WilliTf at dshs.wa.gov Wed Feb 9 16:49:55 2005 From: WilliTf at dshs.wa.gov (Williams, Thomas) Date: Wed Feb 9 16:50:11 2005 Subject: [Tutor] executing SAS and passing parameters Message-ID: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC34@dshs-exch2.dshs.wa.lcl> Here is the code I am using to invoke SAS: import os import sys shell = os.environ.get('COMSPEC') if shell is None: shell = os.environ.get('SHELL') if shell is None: shell = 'an unknown command processor' print 'Running under', shell os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') However, the program in question is c:\work\run_ratios.sas, with 2 parameters: incov, and outcov. This program was initially invoked from an aml program. The code that invoked SAS from this aml is: &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ %.ARCLOC%\sas_code\ratios\new_ratio.sas %.SASLOC%: the SAS executable file ('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') %sas_parm%: the list of parameters to be passed onto SAS %.file%: the name of the log file that is generated during the execution of the SAS program. %.ARCLOC%: directory of the SAS program (c:\work) I think this is an excellent forum to share ideas and solve problems. Thank you ever so much for your assistance with this. From bgailer at alum.rpi.edu Wed Feb 9 19:56:24 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 9 19:50:47 2005 Subject: [Tutor] help In-Reply-To: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> References: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> Message-ID: <6.1.2.0.0.20050209115519.0335a370@mail.mric.net> At 09:35 PM 2/8/2005, james middendorff wrote: >I want to use mysqldb to add people into a database, >but when I ask for the certain fields like Name, >PhoneNumber and such, I cannot get it to put them in >as a string? You can increase your chances of getting help by telling us what happens when you execute this code. >I am not sure what I am doing wrong but >here is my code thanks to anyone who helps: >import MySQLdb > >username = raw_input("what is your username? ") >password = raw_input("what is the password? ") >database = raw_input("what database do you want to >enter? ") >conn = MySQLdb.connect(host='127.0.0.1', >user=username, passwd=password, db=database) > >c = conn.cursor() > >Name = raw_input("what is the name you want to add? ") >PhoneNumber = input("what is the phone number for the >person you are adding? ") >Address = raw_input("what is the address for the >person you are adding? ") >EmailAddress = raw_input("what is the email address of >the person you are adding? ") >BirthDate = raw_input("what is the birthdate of the >person you are adding? year-month-day") > > >c.execute (""" > INSERT INTO people () > VALUES > ('%s','%s','%s','%s','%s'); > """)% (Name, PhoneNumber, Address, >EmailAddress, BirthDate) > >print "%d rows were inserted" % c.rowcount > >===== >"I would kill everyone in this room > for a drop of sweet beer." > ----Homer Simpson---- > > > >__________________________________ >Do you Yahoo!? >The all-new My Yahoo! - What will yours do? >http://my.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jfs.world at gmail.com Wed Feb 9 21:14:05 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 21:14:10 2005 Subject: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept Message-ID: <4b3125cc050209121418102fbb@mail.gmail.com> hey folks, i'm a relative newbie to python itself, and I am currently learning by making my way through the tutorial found within the docs of 2.4 (http://www.python.org/doc/2.4/tut/tut.html). I am currently having a problem dealing with the concept of the "default argument value" in python functions, and just how python handles this. Now http://www.python.org/doc/2.4/tut/node6.html#SECTION006710000000000000000 makes the statement that "the default value is evaluated only once". While that is fine, what I don't really get is how the solution given can even make sense - either syntactically, or conceptually. First of all, let me quote what the doc says: =========== Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L ======== This leads me to at first conclude several things: 1. 'L' in this case (or by extension, all function arguments for which a default is given in the function definition) is "static" (see 'C' language definition). This is my conclusion, seeing as how 'L' can seem to retain its value even though it has gone out of scope after the 'f' function returns. Correct me if i'm wrong here, guys. 2. (*Now this is where I start to get confused. I think the best way to illustrate how I am having problems is to illustrate with a few examples. The basic problem that I am having is, "Which L is which L?") My examples... Example 1 >>> def f(a,L=[]): ... if L==[5]: ... print 'L==[5] caught' ... print L ... print 'resetting L...' ... L=[] ... L.append(a) ... return L ... >>> f(5) [5] >>> f(5) L==[5] caught [5] resetting L... [5] >>> f(2) L==[5] caught [5] resetting L... [2] Example 2 >>> def f(a,L=None): ... if L==[5]: ... print 'caught, printing, resetting' ... print L ... L=[] ... else: ... L=[] ... L.append(a) ... return L ... >>> f(5) [5] >>> f(6) [6] >>> f(6) So when the default value for 'L' is an empty list, the test condition, _once triggered_, *always* catches? But when the default value for 'L' is none, the 'if' never catches? How is this possible? Or even consider the example given - def f(a, L=None): if L is None: L = [] L.append(a) return L How is 'L == None' even possible all the time, given that for def f(a, L=[]): L.append(a) return L , L isn't even [] except for the first call to 'f'? -jf From bgailer at alum.rpi.edu Wed Feb 9 22:12:30 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 9 22:06:51 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc050209121418102fbb@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> At 01:14 PM 2/9/2005, Jeffrey Lim wrote: >hey folks, i'm a relative newbie to python itself, and I am currently >learning by making my way through the tutorial found within the docs >of 2.4 (http://www.python.org/doc/2.4/tut/tut.html). > >I am currently having a problem dealing with the concept of the >"default argument value" in python functions, and just how python >handles this. > >Now http://www.python.org/doc/2.4/tut/node6.html#SECTION006710000000000000000 >makes the statement that "the default value is evaluated only once". >While that is fine, what I don't really get is how the solution given >can even make sense - either syntactically, or conceptually. > >First of all, let me quote what the doc says: > >=========== >Important warning: The default value is evaluated only once. This >makes a difference when the default is a mutable object such as a >list, dictionary, or instances of most classes. For example, the >following function accumulates the arguments passed to it on >subsequent calls: > >def f(a, L=[]): > L.append(a) > return L > >print f(1) >print f(2) >print f(3) > >This will print > >[1] >[1, 2] >[1, 2, 3] > >If you don't want the default to be shared between subsequent calls, >you can write the function like this instead: > >def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L >======== > >This leads me to at first conclude several things: > >1. 'L' in this case (or by extension, all function arguments for which >a default is given in the function definition) is "static" (see 'C' >language definition). This is my conclusion, seeing as how 'L' can >seem to retain its value even though it has gone out of scope after >the 'f' function returns. > >Correct me if i'm wrong here, guys. > >2. (*Now this is where I start to get confused. I think the best way >to illustrate how I am having problems is to illustrate with a few >examples. The basic problem that I am having is, "Which L is which >L?") > >My examples... > >Example 1 > >>> def f(a,L=[]): >... if L==[5]: >... print 'L==[5] caught' >... print L >... print 'resetting L...' >... L=[] >... L.append(a) >... return L >... > >>> f(5) >[5] > >>> f(5) >L==[5] caught >[5] >resetting L... >[5] > >>> f(2) >L==[5] caught >[5] >resetting L... >[2] That works as expected. I assume you are happy with the results. >Example 2 > >>> def f(a,L=None): >... if L==[5]: >... print 'caught, printing, resetting' >... print L >... L=[] >... else: >... L=[] >... L.append(a) >... return L >... > >>> f(5) >[5] > >>> f(6) >[6] > >>> f(6) That also works as expected. I assume you are happy with the results. >So when the default value for 'L' is an empty list, the test >condition, _once triggered_, *always* catches? No. What leads you to think that is happening? This code empties the list each time you invoke it. >But when the default value for 'L' is none, the 'if' never catches? > >How is this possible? > >Or even consider the example given - >def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L > >How is 'L == None' even possible all the time, given that for >def f(a, L=[]): > L.append(a) > return L >, L isn't even [] except for the first call to 'f'? From the 1st reference you cited above: 'The default values are evaluated at the point of function definition" Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From ternary at gmail.com Wed Feb 9 22:12:22 2005 From: ternary at gmail.com (Mike Bell) Date: Wed Feb 9 22:12:28 2005 Subject: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <4b3125cc050209121418102fbb@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <82975b0c050209131271b13ffa@mail.gmail.com> The function's local variable L is not static, but "default argument value" is, which is what the documentation means when it says that it will evaluate these only once. When the default value is a list (in your code, not "the empty list" but a list which happens to be empty when the default arguments are being evaluated), that same object is used every time the function is called. mike From jfs.world at gmail.com Wed Feb 9 22:19:11 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 22:19:14 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> Message-ID: <4b3125cc050209131917b2cfe7@mail.gmail.com> On Wed, 09 Feb 2005 14:12:30 -0700, Bob Gailer wrote: > At 01:14 PM 2/9/2005, Jeffrey Lim wrote: > > > >Example 1 > > >>> def f(a,L=[]): > >... if L==[5]: > >... print 'L==[5] caught' > >... print L > >... print 'resetting L...' > >... L=[] > >... L.append(a) > >... return L > >... > > >>> f(5) > >[5] > > >>> f(5) > >L==[5] caught > >[5] > >resetting L... > >[5] > > >>> f(2) > >L==[5] caught > >[5] > >resetting L... > >[2] > > That works as expected. I assume you are happy with the results. did you even read what i gave as an example properly? So tell me then - why are you happy with the results when 'f(2)' is called? I am not happy with the results. Calling function 'f' with argument 2 should not (unless u are satisfied with such a result) get caught in the 'if L==[5]' > >So when the default value for 'L' is an empty list, the test > >condition, _once triggered_, *always* catches? > > No. What leads you to think that is happening? This code empties the list > each time you invoke it. > pls read http://www.python.org/doc/2.4/tut/node6.html#SECTION006710000000000000000 for the whole context to my questions. Read also my quotes from the doc in my original post. I assume that you can cope with the level of the presentation of my questions. > > > >How is this possible? > > > >Or even consider the example given - > >def f(a, L=None): > > if L is None: > > L = [] > > L.append(a) > > return L > > > >How is 'L == None' even possible all the time, given that for > >def f(a, L=[]): > > L.append(a) > > return L > >, L isn't even [] except for the first call to 'f'? > > From the 1st reference you cited above: 'The default values are evaluated > at the point of function definition" > perhaps you might like to explain that further, seeing as how you seem to be adopting a "I am smarter than you" attitude. -jf From jfs.world at gmail.com Wed Feb 9 22:22:00 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 22:22:05 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc050209131917b2cfe7@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> <4b3125cc050209131917b2cfe7@mail.gmail.com> Message-ID: <4b3125cc05020913227e0c5e88@mail.gmail.com> and have the Common Courtesy to stop hijacking or rewriting other people's thread titles unnecessarily pls. (Like when was this thread ever about the change of email address change on your part???) -jf From bgailer at alum.rpi.edu Wed Feb 9 22:51:42 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Feb 9 22:46:02 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc05020913227e0c5e88@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> <4b3125cc050209131917b2cfe7@mail.gmail.com> <4b3125cc05020913227e0c5e88@mail.gmail.com> Message-ID: <6.1.2.0.0.20050209144944.0331dd48@mail.mric.net> At 02:22 PM 2/9/2005, Jeffrey Lim wrote: >and have the Common Courtesy to stop hijacking or rewriting other >people's thread titles unnecessarily pls. (Like when was this thread >ever about the change of email address change on your part???) I have no idea how this happened. My computer started acting funny. I had to reboot it.. First I knew of the problem was when I saw the posting you are referring to. Perhaps my box has a virus. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jfs.world at gmail.com Wed Feb 9 22:56:01 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 22:56:49 2005 Subject: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <82975b0c050209131271b13ffa@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <82975b0c050209131271b13ffa@mail.gmail.com> Message-ID: <4b3125cc0502091356730da149@mail.gmail.com> On Wed, 9 Feb 2005 13:12:22 -0800, Mike Bell wrote: > The function's local variable L is not static, but "default argument > value" is, which is what the documentation means when it says that it > will evaluate these only once. When the default value is a list (in > your code, not "the empty list" but a list which happens to be empty > when the default arguments are being evaluated), that same object is > used every time the function is called. > ah, thanks for the clarification! I more or less get it now (the key was to think of everything in terms of object references). Would you mind explaining to me in a bit more detail about how the '==['a list']' operation works then? Frankly, the code and results i get below nearly stumbled me... >>> def f(a,L=[]): ... if L==[5]: ... print "'if L==[5]' caught - printing, and then resetting L..." ... print L ... L = [] ... L.append(a) ... return L ... >>> f(5) [5] >>> f(34) 'if L==[5]' caught - printing, and then resetting L... [5] [34] >>> f('fjskl') 'if L==[5]' caught - printing, and then resetting L... [5] ['fjskl'] >>> My questions: - is the '==' operation a 'list' comparison - rather than a pointer comparison? (my experiments seem to indicate that it is a 'list' comparison) - if this is the case, then why does the 'if L==[5]' test still catch later on, when the 'L' should no longer be a '[5]' list? - if this is *not* the case then, then how do you determine the '==' is supposed to match? - or is this a matter of 'compare by value' first, then after we get a match, we 'compare by reference' later on??? thanks for your time, -jf From alan.gauld at freenet.co.uk Wed Feb 9 23:05:15 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:05:05 2005 Subject: [Tutor] help References: <20050209043539.36808.qmail@web31004.mail.mud.yahoo.com> Message-ID: <078801c50ef3$700477f0$68b78851@xp> > PhoneNumber and such, I cannot get it to put them in > as a string? I can't help in general but I did notice... > PhoneNumber = input("what is the phone number for the > person you are adding? ") You shouldn't store phone numbers as numbers. People often include spaces or hyphens or parentheses etc when entering them, eg: +44 (0) 1234 567890 (542) 123 4567 0121-553-2609 etc etc... And of course you get the alpha numerics: 0172 TAXICAB So strings are the best solution (and they should be 24 characters long to handle the worst case international standard phone number!) Alan G. Who works for the phone company! :-) From dyoo at hkn.eecs.berkeley.edu Wed Feb 9 23:05:23 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 9 23:05:33 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <4b3125cc050209131917b2cfe7@mail.gmail.com> Message-ID: On Thu, 10 Feb 2005, Jeffrey Lim wrote: > > > > > >Example 1 > > > >>> def f(a,L=[]): > > >... if L==[5]: > > >... print 'L==[5] caught' > > >... print L > > >... print 'resetting L...' > > >... L=[] > > >... L.append(a) > > >... return L > > >... Hi Jeffery, At the beginning of a function call, if a function has default parameter values, then the parameters get aimed at those default values. So every time through the call to f() here, L will initially refer to that list value. I liked your experiments in your earlier post. Let's run through your example, and see if our explanation matches with reality. *grin* To make talking abou this a little less confusing, do you mind if I change the definition slightly, to this? ### initialList = [] def f(a,L=initialList): if L==[5]: print 'L==[5] caught' print L print 'resetting L...' L=[] L.append(a) return L ### It should have about the same effect as your previous code, but with the advantage of letting us poke around at the list that's being used as the default value. Ok, let's try this out. ### >>> f(5) [5] ### Ok, at this point, the 'default value' that initialList refers to should also be [5]. Let's check this. ### >>> initialList [5] ### Ok, good. Now we call f(5) again: ### >>> f(5) L==[5] caught [5] resetting L... [5] ### The reassignment to L in the 'if' block: if L==[5]: print 'L==[5] caught' print L print 'resetting L...' L=[] doesn't do any mutation on the actual default value. L is just a name that can be aimed at values: rebinding L through assignment doesn't "mutate" the list value. We'll talk about this again later in this post. We can look at the default value again by peeking at it through initialValue again: ### >>> initialList [5] ### So if we call f() again, since L is always bound to the default value, Let's call f(2) one more time. ### >>> f(2) L==[5] caught [5] resetting L... [2] ### Yup. The reassignment of L still doesn't do anything to the value that L is referring to, so subsequent calls to f() should continue to say "resetting L". Does this make sense so far? Please feel free to ask questions on any part that seems wacky, and we'll try to make sense out of it. *grin* Looking back at the program, I think that you meant to write: ### initialList = [] def f(a,L=initialList): if L==[5]: print 'L==[5] caught' print L print 'resetting L...' del L[:] ## Resets the initial value to the empty list L.append(a) return L ### The change here is the commented line: del L[:] ## Resets the initial value to the empty list which causes the list that we refer to as "L" to shrink down to the empty list. There are a few tricky subtleties here, and we have to keep in mind the distinction between a "name" and a "value". 'names' are like fingers that point at 'values'. Python handles default parameters by pointing the parameter name to a default value when it enters a function. So if we want to do things that make the default parameter appear to "change", we have to mutate the value that the parameter is pointed at. Hope this helps! From alan.gauld at freenet.co.uk Wed Feb 9 23:07:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:07:14 2005 Subject: [Tutor] print out lines that start with a word References: <20050209053656.60027.qmail@web20326.mail.yahoo.com> Message-ID: <078f01c50ef3$b89a02f0$68b78851@xp> > I'm trying to get only the lines that start with > "This" for a text file. > > Here's what I wrote: > > >>> import re > >>> f = open('c:/lines.txt').readlines() > >>> for line in f: > match = re.search('^This',f) > if line == match: > print match try if line.startwith('This'): its easier! But your problem above is that match returns a match object which is not a string. So you can't compare directly you need to extract the string from inside the match object! HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bvande at po-box.mcgill.ca Wed Feb 9 23:05:44 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Feb 9 23:07:22 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? Message-ID: <420A8938.5040604@po-box.mcgill.ca> Hi all, I have data files with a format that can be scheamatized as: File Header Contents . . . File Header End Tag Node Header Contents . . . Node Header End Tag Node Contents . . . Node End Tag [Repeat Node elements until end of file] I'm refactoring the heck out of a file conversion utility I wrote for this format back when I knew even less than I do now =:-0 The main change in refactoring is moving it to OOP. I have a method that serves as the entry point for parsing the files. It separates the file header content and the nodes (or body content), sending them each to appropriate methods to be processed. I want the body parser to accept a list of lines corresponding to the nodes portions of my file, separate out each node (everything between node end tags, the bottommost end tag included in the node), and send each node's contents to a further method for processing. What I have now works and is a big improvement on what I had before. But, I know that I tend to employ while loops more than I perhaps ought, and much of the style of OOP has yet to sink in. So, any suggestions on how to make this method more Pythonic would be most welcome. (body_contents is a list of file lines, with all file header lines removed.) . def body_parser(self, body_contents): . . while body_contents: . . count = 0 . current_node_contents = [] . . for line in body_contents: . current_node_contents.append(line) . count += 1 . if line == node_end_tag: # node_end_tag elsewhere . break # defined and includes '\n' . . self.node_parser(current_node_contents) . body_contents = body_contents[count:] Another alternative has occurred to me, but seems to compensate for the avoidance of while by being ugly. Untested code: . def alt_body_parser(self, body_contents): . . body_contents = ''.join(body_contents) . body_contents = body_contents.split(node_end_tag) . . # ugly lives here -- having removed node_end_tag's . # with split, I need to put them back on: . count = 0 . for i in body_contents: . body_contents[count] = i + node_end_tag . count += 1 . # (The sub-alternative of having the node_parser method . # put them back, while easier, also seems a dangerous . # separation of responsibility for the integrity of the data . # format.) . . for i in body_contents: . self.node_parser(i) So, which of these 2 (and a half) ways seems most Pythonic to the more experienced? Any better ways I've overlooked? Thanks, and best to all, Brian vdB From jfs.world at gmail.com Wed Feb 9 23:03:36 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 23:11:08 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <6.1.2.0.0.20050209144944.0331dd48@mail.mric.net> References: <4b3125cc050209121418102fbb@mail.gmail.com> <6.1.2.0.0.20050209140553.026fc810@mail.mric.net> <4b3125cc050209131917b2cfe7@mail.gmail.com> <4b3125cc05020913227e0c5e88@mail.gmail.com> <6.1.2.0.0.20050209144944.0331dd48@mail.mric.net> Message-ID: <4b3125cc050209140354a1ec83@mail.gmail.com> On Wed, 09 Feb 2005 14:51:42 -0700, Bob Gailer wrote: > At 02:22 PM 2/9/2005, Jeffrey Lim wrote: > >and have the Common Courtesy to stop hijacking or rewriting other > >people's thread titles unnecessarily pls. (Like when was this thread > >ever about the change of email address change on your part???) > > I have no idea how this happened. My computer started acting funny. I had > to reboot it.. First I knew of the problem was when I saw the posting you > are referring to. Perhaps my box has a virus. > I will let all of posterity decide this for themselves (they will, anyway). I have never seen a virus act this way, nor should i think it would ever have reason to - without at least an attachment of itself. As it is, I will be so kind enough as to give you the benefit of the doubt, and to be courteous and friendly enough, and "equal-level footing perspective enough" to you in answering your implied question. -jf From alan.gauld at freenet.co.uk Wed Feb 9 23:18:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:18:00 2005 Subject: [Tutor] executing SAS and passing parameters References: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC34@dshs-exch2.dshs.wa.lcl> Message-ID: <07c301c50ef5$3c180270$68b78851@xp> > os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') You might find that os.system() is all you need here, but if execl works don't worry too much. > However, the program in question is c:\work\run_ratios.sas, with 2 > parameters: incov, and outcov. This program was initially invoked from an > aml program. The code that invoked SAS from this aml is: Wacky stuff it remindss me of JCL on an MVS mainframe. What exactly is AML? Is it a SAS specific thing? > &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ > %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ > %.ARCLOC%\sas_code\ratios\new_ratio.sas I'm assuming the ~ characters are line continuations? So the above is effectively one long line? If so translating it becomes: /sas.exe - -log /%file%.log -f(?) new_ratio.sas If so, you could try that from your command prompt. If it works just build the string and insert it into an os.system() call. I think the real issue here is extracting the actuial command line from the AML code (and probably the SAS documentation for startup parameters). Once you've got it working from an interactive command line (ie Cmd.exe Box in NT) then getting Python to replicate that should be straighforward. Alan G. From alan.gauld at freenet.co.uk Wed Feb 9 23:32:07 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:33:11 2005 Subject: [Tutor] python's default argument value handling in functions -weird syntax? problem grappling with the concept References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <07ca01c50ef7$30c70ef0$68b78851@xp> > This leads me to at first conclude several things: > > 1. 'L' in this case (or by extension, all function arguments for which > a default is given in the function definition) is "static" Pretty close, yes. Especially if the parameter is mutable. > language definition). This is my conclusion, seeing as how 'L' can > seem to retain its value even though it has gone out of scope after > the 'f' function returns. Thats right, the default value is evaluated once only, it keeps that initial value for all future invocations. But if it is mutable the list object(in the example) is the same list but the content of the list can be changed on each invocation. > 2. (*Now this is where I start to get confused. I think the best way > to illustrate how I am having problems is to illustrate with a few > examples. The basic problem that I am having is, "Which L is which > L?") > > My examples... > > Example 1 > >>> def f(a,L=[]): > ... if L==[5]: > ... print 'L==[5] caught' > ... print L > ... print 'resetting L...' > ... L=[] Here you reassign L to a completely new list, but the original default one is still lurking i the background complete with the changes you made earlier. > ... L.append(a) > ... return L You now return your new list. > >>> f(5) > [5] > >>> f(5) > L==[5] caught > [5] > resetting L... > [5] > >>> f(2) > L==[5] caught So we go back to the original default > [5] > resetting L... And you create another new list > [2] And return it. > Example 2 > >>> def f(a,L=None): > ... if L==[5]: > ... print 'caught, printing, resetting' > ... print L Should never happen unless you call f(a,[5]) that is never triggered for the default value. > ... L=[] but now creates a brand new L regardless of what was passed in > ... else: > ... L=[] Create another new L > ... L.append(a) > ... return L And modify and return the new list. > ... > >>> f(5) > [5] > >>> f(6) > [6] So in both cases you return a new list, the original default None is still there but you ignore it! > So when the default value for 'L' is an empty list, the test > condition, _once triggered_, *always* catches? No, it only catches if you pass in a value otherwise the default will still be None. Notice your if branch was not executed in either case above, only the return value is shown. > But when the default value for 'L' is none, the 'if' never catches? Because the default is None, the if only catches if you override the default with a matching list. > Or even consider the example given - > def f(a, L=None): > if L is None: > L = [] > L.append(a) > return L > > How is 'L == None' even possible all the time, given that for Because the value is only evaluated *once*. The default is set forever to None which is *immutable* - you cant change it, only overwrite it. > def f(a, L=[]): > L.append(a) > return L > , L isn't even [] except for the first call to 'f'? The value is set only once, the list is created and the same list object is used each time. But because list objects are *mutable* you can change the *contents* of the list, but you can never change the default list itself. Its just as the docs say. BUt don;t try to hard to think in terms of C. This is Python not C and it works differently. In C parameters etc are locations on the memory stack. In Python they are entries in a dictionary. Very different concepts and they result in very different behaviour! HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Feb 9 23:38:20 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Feb 9 23:38:23 2005 Subject: [Tutor] python's default argument value handling in functions -weird syntax? problem grappling with the concept References: <4b3125cc050209121418102fbb@mail.gmail.com><82975b0c050209131271b13ffa@mail.gmail.com> <4b3125cc0502091356730da149@mail.gmail.com> Message-ID: <07df01c50ef8$0f972890$68b78851@xp> > > My questions: > - is the '==' operation a 'list' comparison - rather than a pointer > comparison? (my experiments seem to indicate that it is a 'list' > comparison) Forget pointers and all you ever knew of them from C. Trying to think of Python in terms of Pointers is ultimately an excercise in frustration. Python uses dictionaries for its indirection not memory addresses. > - if this is the case, then why does the 'if L==[5]' test still catch > later on, when the 'L' should no longer be a '[5]' list? It shouldn't! Are you absolutely sue about that? I didn't see a case in your examples where the [5] case would fail... > - if this is *not* the case then, then how do you determine the '==' > is supposed to match? It should match if both are [5] > - or is this a matter of 'compare by value' first, then after we get a > match, we 'compare by reference' later on??? The actual semanics of omparisons for all Pythons types are described in the Language reference. But mostly you can ignore it and it will just work... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From jfs.world at gmail.com Wed Feb 9 23:30:59 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 23:49:49 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: References: <4b3125cc050209131917b2cfe7@mail.gmail.com> Message-ID: <4b3125cc0502091430eba2810@mail.gmail.com> On Wed, 9 Feb 2005 14:05:23 -0800 (PST), Danny Yoo wrote: > > [snip] > > Does this make sense so far? YES!!! Most perfectly!!! Thanks for your detailed step-by-step analysis man - it was very helpful, and much appreciated... > > Looking back at the program, I think that you meant to write: > > ### > initialList = [] > def f(a,L=initialList): > if L==[5]: > print 'L==[5] caught' > print L > print 'resetting L...' > del L[:] ## Resets the initial value to the empty list > L.append(a) > return L > ### > yeah man - i guess i was just still stuck in the "non-object-oriented" thinking rut... I believe you have just about clarified all the doubts that i've had about the whole thing which prompted my question to the list in the first place! thanks a lot... -jf From abli at freemail.hu Wed Feb 9 23:50:49 2005 From: abli at freemail.hu (Abel Daniel) Date: Wed Feb 9 23:50:24 2005 Subject: [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <4b3125cc050209121418102fbb@mail.gmail.com> (Jeffrey Lim's message of "Thu, 10 Feb 2005 04:14:05 +0800") References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: quoted lines are from Jeffrey Lim [... I have rearranged the order of the quotes ...] > How is 'L == None' even possible all the time, given that for > def f(a, L=[]): > L.append(a) > return L > , L isn't even [] except for the first call to 'f'? This is the important point. You see, its true that L != [] for those calls, but despite this, L _is_ []. I guess this sounds wierd, so I'll clarify it: Lets try it with a little modification. Instead of "def f(a, L=[])", we will use "def f(a, L=l)", where l is an empty list. This surely shouldn't cause any difference, should it? >>> l=[] >>> def f(a, L=l): ... L.append(a) ... return L ... >>> f(1) [1] >>> f(2) [1, 2] >>> f(3) [1, 2, 3] So far, so good. Now lets see whether L is [] or not: >>> a=f(4) # so now a is whatever L was inside the function >>> a == l True and: >>> a is l True So L _is_ [], isn't it? How can this happen? After all, by now L is [1,2,3,4], right? And l is an empty list, right? Well, wrong: >>> l [1, 2, 3, 4] So the strange thing is that even though L is _not_ [] (as in, its not an empty list) it _is_ [] in some sence. That is, it is the _same_ list which was [] once. This second sentence might sound pretty wierd. You have to keep in mind, that every time you type [], python will create a _new_, empty list. This means that: >>> [] is [] False The big difference between the "def f(a, L=[])" and "def f(a, L=None)" cases is that in the first, L is a list, and lists are mutable. In the second, L is None and obviously, None is not mutable. In both cases you give an object as a default value. In both cases, L will _allways_ be this object at the first line of the function when you call the function. The difference is that in the first case, although you can't change the _identity_ of the default value, you can change its _content_ . And thats what you do with the line "L.append(a)". Keep in mind that L=[] does _not_ copy the list. In fact, in python even a=5 does not copy anything. In C, variables might be thought of as little drawers that have something in them. When you say a=b, the contents of b get copied to a. In python, however, variables are better thought of as labels. When you say a=5, you put a label on the number 5 object. Its like saying "I want to be able to call that number a". When doing a=b, there is no copying, what happens is that the label 'a' gets moved to the object which has the label 'b' on it. In the previous paragraph, I have written "when you say a=5, you put a label on the number 5 object". Maybe I should have written "you put a label on a number 5 object". Notice the difference? For numbers, one could claim that there is no difference. After all, there is only one number 5, right? However, as we have seen above, for lists, you can't claim the same. There is no _the_ []. Every '[]' will create a new one. If you think of variables as labels on objects, and objects as having content and identity, everything should become clear. ('==' compares by value, that is, by content, 'is' compares by identity. Make sure not to mix identity with eguality.) Recommended reading: http://www.effbot.org/zone/python-objects.htm (understanding python objects, pretty short) http://starship.python.net/crew/mwh/hacks/objectthink.html ("variables as labels", a bit longer) ps. For extra wierdness, in python "there is only one number 5" isn't true for large numbers: >>> a=100 >>> b=100 >>> a is b False Using a large number is important: integers up to 99 are cached, so they _are_ unique (we would get True above). For larger numbers, the cacheing is more subtle, for example: >>> a, b = 100, 100 >>> a is b True -- Abel Daniel From jfs.world at gmail.com Wed Feb 9 23:57:54 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Wed Feb 9 23:57:56 2005 Subject: [Tutor] python's default argument value handling in functions -weird syntax? problem grappling with the concept In-Reply-To: <07df01c50ef8$0f972890$68b78851@xp> References: <4b3125cc050209121418102fbb@mail.gmail.com> <82975b0c050209131271b13ffa@mail.gmail.com> <4b3125cc0502091356730da149@mail.gmail.com> <07df01c50ef8$0f972890$68b78851@xp> Message-ID: <4b3125cc0502091457f1eedd9@mail.gmail.com> On Wed, 9 Feb 2005 22:38:20 -0000, Alan Gauld wrote: > > > > My questions: > > > > [snip] > > [snip] > > HTH, yes it did! I've already gotten it - but your explanation was just simply beautiful (it really is). Thanks for the note about "not in think in terms of C" as well - I'll have to remember that! Appreciate it, -jf ps. sorry for the double send, Alan - i forgot to send to the list as well. From jfs.world at gmail.com Thu Feb 10 00:22:02 2005 From: jfs.world at gmail.com (Jeffrey Lim) Date: Thu Feb 10 00:28:49 2005 Subject: [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: References: <4b3125cc050209121418102fbb@mail.gmail.com> Message-ID: <4b3125cc0502091522316346aa@mail.gmail.com> On Wed, 09 Feb 2005 23:50:49 +0100, Abel Daniel wrote: > > quoted lines are from Jeffrey Lim > [... I have rearranged the order of the quotes ...] > thanks, Abel! Especially for the part on the 'C' concept of variables, vs that of Python's (and the links, as well). appreciated it, and thanks, all, for such a great "first-time tutor list experience" already, -jf From dyoo at hkn.eecs.berkeley.edu Thu Feb 10 00:58:39 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 10 00:58:43 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <420A8938.5040604@po-box.mcgill.ca> Message-ID: On Wed, 9 Feb 2005, Brian van den Broek wrote: > Hi all, > > I have data files with a format that can be scheamatized as: > > File Header Contents > . . . > File Header End Tag > Node Header Contents > . . . > Node Header End Tag > Node Contents > . . . > Node End Tag > [Repeat Node elements until end of file] [some text cut] > . def body_parser(self, body_contents): > . while body_contents: > . count = 0 > . current_node_contents = [] > . for line in body_contents: > . current_node_contents.append(line) > . count += 1 > . if line == node_end_tag: # node_end_tag elsewhere > . break # defined and includes '\n' > . self.node_parser(current_node_contents) > . body_contents = body_contents[count:] Hi Brian, Ah, this looks like the perfect place for helper functions. *grin* Conceptually, the code applies the method 'self.node_parser'() on a sequence of nodes. We can reshape the code above so it works like this: ### def partition_node_content(body_contents): """Returns a sequence of node-element content.""" pass ## FIXME: fill me in def body_parser(self, body_contents): for node_content in partition_node_content(body_contents): self.node_parser(node_content) ### Helper functions are key to making this look nicer. We let our 'partition_node_content()' function handle the bundling up of lines for us. We can yank out part of the original code to write partition_node_content(), like this: ### def partition_node_content(body_contents): partitions = [] while body_contents: count = 0 current_node_contents = [] for line in body_contents: current_node_contents.append(line) count += 1 if line == node_end_tag: # node_end_tag elsewhere break # defined and includes '\n' partitions.append(current_node_content) body_contents = body_contents[count:] return partitions ### But we can make this even nicer; some of the stuff that deals with 'count' --- and the while loop too! --- can dissolve if we iterate directly across the elements of body_contents: ### def partition_node_content(self, body_contents): """Splits apart body_contents into a bunch of node_content lists.""" partitions = [] current_node_contents = [] for line in body_contents: if line == node_end_tag: partitions.append(current_node_contents) current_node_contents = [] return partitions ### If we want to be fancy, we can also take advantage of Python's generator support to avoid constructing an explicit list: ### def partition_node_content(self, body_contents): """Returns an iterator whose contents are a bunch of node_content lists.""" current_node_contents = [] for line in body_contents: if line == node_end_tag: yield current_node_contents current_node_contents = [] ### This generator behaves similarly, and can potentially save on memory use, since it streams chunks of node content back. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Thu Feb 10 01:06:25 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 10 01:06:30 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: Message-ID: > If we want to be fancy, we can also take advantage of Python's generator > support to avoid constructing an explicit list: > > ### > def partition_node_content(self, body_contents): > """Returns an iterator whose contents are a bunch of > node_content lists.""" > current_node_contents = [] > for line in body_contents: > if line == node_end_tag: > yield current_node_contents > current_node_contents = [] > ### Hi Brian, Oh good grief. *grin* That last snippet won't work; I had forgotten about appending lines into current_node_contents. Here's a revision of the silly code: ### def partition_node_content(self, body_contents): """Returns an iterator whose contents are a bunch of node_content lists.""" current_node_contents = [] for line in body_contents: current_node_contents.append(line) if line == node_end_tag: yield current_node_contents current_node_contents = [] ### I wanted to add that the generator approach should have the same performance characteristic as your original code. Your original code's approach interleaved the bundling of the body_content with calls to the node parser. The approach with the separate list bundling behaves a little bit differently: it tries to build a list of all the node_content chunks, and then processes that list element by element. The generator approach, like your original code, interleaves the bundling with the node_content parsing. My apologies! From bvande at po-box.mcgill.ca Thu Feb 10 01:52:18 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 10 01:52:37 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: References: Message-ID: <420AB042.1070300@po-box.mcgill.ca> Danny Yoo said unto the world upon 2005-02-09 19:06: >>If we want to be fancy, we can also take advantage of Python's generator >>support to avoid constructing an explicit list: >> > > Hi Brian, > > > Oh good grief. *grin* > > That last snippet won't work; I had forgotten about appending lines into > current_node_contents. Here's a revision of the silly code: > > > ### > def partition_node_content(self, body_contents): > """Returns an iterator whose contents are a bunch of > node_content lists.""" > current_node_contents = [] > for line in body_contents: > current_node_contents.append(line) > if line == node_end_tag: > yield current_node_contents > current_node_contents = [] > ### > > > I wanted to add that the generator approach should have the same > performance characteristic as your original code. > > Your original code's approach interleaved the bundling of the body_content > with calls to the node parser. The approach with the separate list > bundling behaves a little bit differently: it tries to build a list of all > the node_content chunks, and then processes that list element by element. > The generator approach, like your original code, interleaves the bundling > with the node_content parsing. > > > My apologies! Hi Danny, Apologies, while nice, aren't needed; catching your small thinko was the easy part of the generator code. :-) (Of the parts of Python about which I am still fuzzy, generators are among the fuzziest.) And thank you for the replies. Given that in my application, neither performance nor memory use matter too much, are there are grounds (beyond bare personal preference) to choose amongst the approaches? (Having rejected personal preference and performance as criterion, one might well wonder what's left? I mean something like community consensus about which is more elegant, etc. where there is enough agreement to take it out of the realm of pure personal preference. And, seeing how I've phrased it, I think `that's unanswerable' might well be a perfectly acceptable answer. :-) ) Alternatively, of the two ways you gave (the generator above and the helper function route), which seems better? All I have to guide me is unfamiliarity with generators, and that isn't the best compass. Thanks again, Brian vdB From carroll at tjc.com Thu Feb 10 02:41:33 2005 From: carroll at tjc.com (Terry Carroll) Date: Thu Feb 10 02:41:37 2005 Subject: [Tutor] executing SAS and passing parameters In-Reply-To: <592E8923DB6EA348BE8E33FCAADEFFFC0B13DC34@dshs-exch2.dshs.wa.lcl> Message-ID: I'd echo what Alan said. It sounds more like you're having trouble finding out what the command line to SAS should look like, rather than invoking it with Python. (I'm going to quote some of your message out-of-order to better facilitate my approach to this. I will, I trust, not misrepresent the context.) On Wed, 9 Feb 2005, Williams, Thomas wrote: > However, the program in question is c:\work\run_ratios.sas, with 2 > parameters: incov, and outcov. This program was initially invoked from an > aml program. The code that invoked SAS from this aml is: > > &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ > %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ > %.ARCLOC%\sas_code\ratios\new_ratio.sas > > %.SASLOC%: the SAS executable file ('C:\Program Files\SAS > Institute\SAS\V8\SAS.exe') > %sas_parm%: the list of parameters to be passed onto SAS > %.file%: the name of the log file that is generated during the execution of > the SAS program. > %.ARCLOC%: directory of the SAS program (c:\work) First, something's not jibing here: you say the program to run is c:\work\run_ratios.sas , but none of the variables under AML appear to have "run_ratios" in it. (Not that I know what AML is). My expectation is that this code: > &SYSTEM %.SASLOC% -SYSPARM %sas_parm% -log ~ > %.ARCLOC%\ratios\log\%.file%.log -SYSIN ~ > %.ARCLOC%\sas_code\ratios\new_ratio.sas Expands to an invocation of this: """ C:\Program Files\SAS Institute\SAS\V8\SAS.exe -SYSPARM incov outcov -log c:\work\ratios\log\[logfilename].log -SYSIN c:\work\sas_code\ratios\new_ratio.sas """ (where [logfilename] is actually replaced with the name of your logfile.) As I said, no reference to "c:\work\run_ratios.sas" in this; so confirm this. My suggestion is that you open up an MSDOS window, and try variations on this until you find one that works. Once you find one that works, you know your command; and that's going to be 95% of the battle. In your Python code: > os.execl('C:\Program Files\SAS Institute\SAS\V8\SAS.exe') First, as Alan points out, try os.system() instead. I would also very much encourage a piece of advice he gave that might have slipped through, which is: build a string, first, and pass that string to os.system(). That way, you can do some debugging by making sure your string represents the command you cane up with earlier. I'd also recommend using forward slashes rather than backslashes, which saves you some escape heartache. Forward slashes should still work. You can also do something along the same lines your AML took, if you like: SAS_location = "C:/Program Files/SAS Institute/SAS/V8/SAS.exe" sas_parm = "incov outcov" ARC_location = "c:/work/" logfile = "ratios/mylog.log" SAS_SYSIN = "sas_code/ratios/new_ratio.sas" command_line = "%s -SYSPARM %s -log %s%s -SYSIN %s%s" % (SAS_location, sas_parm, ARC_location, logfile, ARC_location, SAS_SYSIN) print command_line # above line verifies the command matches what you determined from the # earlier testing from the MS-DOS command line os.system(command_line) # invoke SAS From ismaelgf at adinet.com.uy Thu Feb 10 04:07:11 2005 From: ismaelgf at adinet.com.uy (Ismael Garrido) Date: Thu Feb 10 04:06:47 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: References: Message-ID: <420ACFDF.2080402@adinet.com.uy> Danny Yoo wrote: >### > >def f(a,L=[]): > if L==[5]: > print 'L==[5] caught' > print L > print 'resetting L...' > L=[] > L.append(a) > return L > > >### > Now I'm dizzy... I can't understand why there are two "L"! L is a local variable of the function, right? (I can't imagine it being anything else) Then if I reassign L to something, why doesn't it keep that change till next run? At least, it keeps the values in the list.. so it should keep the reassignation, no? I'm completly puzzled :-S Ismael From maxnoel_fr at yahoo.fr Thu Feb 10 04:26:06 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 10 04:26:13 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <420ACFDF.2080402@adinet.com.uy> References: <420ACFDF.2080402@adinet.com.uy> Message-ID: <022b560bc49cafd2091f0ea260eb08c6@yahoo.fr> On Feb 10, 2005, at 03:07, Ismael Garrido wrote: > Danny Yoo wrote: > >> ### >> >> def f(a,L=[]): >> if L==[5]: >> print 'L==[5] caught' >> print L >> print 'resetting L...' >> L=[] >> L.append(a) >> return L >> >> ### >> > Now I'm dizzy... I can't understand why there are two "L"! > L is a local variable of the function, right? (I can't imagine it > being anything else) Then if I reassign L to something, why doesn't it > keep that change till next run? At least, it keeps the values in the > list.. so it should keep the reassignation, no? > I'm completly puzzled :-S It's not L you have to look at but the default value itself. L is local to the function and recreated each time you run it. The default value, however (which has no name, so I'm gonna call it "defVal"), is static (in the Java/C++ sense of the word -- it's only created once). The first time you run the function, defVal is set to [] and then it is assigned to L (as in, L = defVal). Since defVal is a list, L and defVal are actually two names for the same variable. Thus, when you append something to L, it is appended to defVal as well. However, when you do L = [], you're binding the name L to another variable (which you create on the spot). But the name defVal is still bound to the same variable! Thus, when you run the function again, you get defVal as you left it. # Let's consider that defVal == [5] (say, you've already called f(5)) and call f(10): if L == [5]: # L == defVal == [5] (they are the same variable) L = [] # Re-binding the name: a new var is created. L == []; defVal == [5] L.append(a) # L == [10]; defVal == [5]. See what I mean? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From johan at accesstel.co.za Thu Feb 10 06:43:04 2005 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu Feb 10 06:45:01 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <42089086.8010407@cirad.fr> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> Message-ID: <1108014184.4623.1.camel@KMA.accesstel> I am not so clued up on the 'base 2' and 'base 8' stuff. Care to explain that a little? Johan On Tue, 2005-02-08 at 12:12, Pierre Barbier de Reuille wrote: > MMmmhh ... no ! > > The number you wrote is equivalent to '010' and any number beginning by > '0' and not followed by "x" will be considered octal. So "10" in base 8 > is ... 8 :) > > If you want to convert a number from base 2 to base 10 write : > > >>> int("0000000010", 2) > 2 > > Pierre > > Johan Geldenhuys a ?crit : > > Hi everybody, > > I used binary.py and is a bit puzzled by the results I get when > > comparing the binary of decimal 2 and the value I get when I convert the > > binary to an int. > > > > > >>>>binary(2) > > > > '00000000000000000000000000000010' > > > >>>>int(00000000000000000000000000000010) > > > > 8 > > > > > > Isn't the int value of this binary string supposd to be '2' and not '8'? > > > > Johan > > On Sat, 2005-02-05 at 17:48, Kent Johnson wrote: > > > > > >>Liam, > >> > >>I think you misunderstand what endianness is. > >> > >>Big-endian and little-endian refer to the way a number is stored as bytes in the underlying memory > >>of the computer. This is not something you generally need to worry about in a Python program. > >> > >>For example, consider the number 0x12345678. On most modern computers this will be stored in four > >>consecutive bytes of computer memory. The individual bytes will contain the values 0x12, 0x34, 0x56, > >>0x78. The question is, what is the order of those bytes in memory? On a big-endian computer, the > >>most significant byte - 0x12 - is stored at the lowest memory address, so the sequence of bytes will > >>be 0x12, 0x34, 0x56, 0x78. On a little-endian computer, the least-significant byte is stored at the > >>lowest address, and the order will be reversed: 0x78, 0x56, 0x34, 0x12. > >> > >>Most programming languages will hide this detail from you most of the time. Even in assembly > >>language, you generally load and store integers without worrying about endianness. Math operations > >>just do the right thing so you don't have to worry about it. > >> > >>Endianness becomes an issue when you want to convert between representations, and when binary data > >>is shared between computers which may have different endianness. > >> > >>For example in a C program you might want to get the high byte of an integer when you know the > >>address of the integer. The desired byte will be at (address+0) or (address+3) depending on the > >>endianness of the hardware. > >> > >>Similarly, if an array of integers is written to a file in a binary representation (not as ASCII > >>strings representing the integers, but as 32-bit values), then to correctly read the file you have > >>to know the endianness of the data in the file. > >> > >> > >>OK, so what does this have to do with converting a number to binary in Python? Well, nothing, > >>actually. First, note that 'binary representation' can mean two different things. In the description > >>above, I was talking about the actual bit pattern stored in the computer. Python works with binary > >>numbers all the time, in this sense, but it is under the hood. The other meaning of 'binary > >>representation' is that of a base-2 string representation of a number. > >> > >>So if you ask, "How do I convert a number to binary?" you can mean either of these. > >> > >>The first one is trivial. If you have a decimal string representation of the number, use int() to > >>convert it to binary. If you have an integer already, it's already *in* binary, so you don't have to > >>do anything! > >> > >>So, "How do I convert a number to binary?", to be interesting, must mean "How do I convert an > >>integer to a base-2 string representation?" And how do you do this? Well, you figured out one way > >>using the mathematical properties of integers. These operations are independent of endianness, and > >>so is the desired result. > >> > >>The base-2 string representation of the number (whose base-16 string representation is) 0x1234 is > >>'0001001000110100'. The order of digits here is determined by our convention of writing the most > >>significant digits on the left, not by the endianness of the underlying computer. > >> > >>OK, this is long enough, I hope I have shed some light... > >>Kent > >> > >> > >> > >>Liam Clarke wrote: > >> > >>>Jacob - just for you, begin your agitation for the next release please ;) > >>> > >>>binstring.py, as attached. > >>>(also pasted up - http://www.rafb.net/paste/results/5feItM57.html) > >>> > >>>Creating this, was just a brain teaser, but I was thinking 'what if I > >>>wanted to make this for the standard library.' > >>> > >>>And so you can see, I had to include a flag for endianess. But that > >>>was really a cheap trick. If this was going into a standard library, > >>>I'd want to query the OS for endianess. As for the bits, once again, > >>>32 bit is the norm, but 64 bit is here and spreading. > >>> > >>>Also, should it display 11111111 as 255 or 256? Both are valid, > >>>depending on context. > >>> > >>>Thirdly, if I can do it in 2 minutes, (well, the main part), then > >>>should they bother putting it in the standard library considering > >>>also, > >>> > >>>- How often, really, are you going to need to present a decimal or hex > >>>as a binary string. > >>> > >>>Lastly - this only does base 10 to base 2. Should I include a base 6 > >>>to base 2, base 8 to base 2, base 10 to 6, 10 to 8, 8 to 6? > >>> > >>>I wouldn't like to write for the standard library, because you can > >>>never please everyone. > >>> > >>>But yeah, feel free to use the above, just keep my doc strings and comments. > >>> > >>>Regards, > >>> > >>>Liam Clarke > >>> > >>>On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. wrote: > >>> > >>> > >>>>>The binary value is the same as the hex value. > >>>>>The binary representation is 000111110100, but > >>>>>unfortunately Python doesn't support binary in > >>>>>its string formatting(although it does in int()! > >>>> > >>>>Uh, question. Why not? It seems that all simple types should be included. > >>>>Since the computer stores it as binary, why shouldn't python be able to > >>>>display a > >>>>string of it in binary? That seems to be a short coming that should be added > >>>>to the > >>>>next release... IMHO of course. > >>>>Jacob Schmidt > >>>> > >>>>_______________________________________________ > >>>>Tutor maillist - Tutor@python.org > >>>>http://mail.python.org/mailman/listinfo/tutor > >>>> > >>> > >>> > >>> > >>> > >>>------------------------------------------------------------------------ > >>> > >>>###### > >>># binString.py > >>># by Liam Clarke > >>>#(Let me know when it's included in the standard library ;-)) > >>>###### > >>> > >>>"""Converts a integer base 10 to a string base 2""" > >>> > >>>def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): > >>> """ > >>>Integer to be converted is essential, Endianess is an optional flag; > >>>me being a Win32 user, Endianess is big by default, defaults to a 32-bit > >>>representation, most integers in Python being 32 bit. truncExcess will > >>>strip place-holder zeros for succintness. > >>> > >>>Oh, and it will represent 11111111 as 256, as I'm not sure whether you want > >>>to start counting for zero with this. It's a simple matter to change.""" > >>> tempList = ['0' for x in range(bits)] > >>> > >>> for bitPlace in range(bits, -1, -1): > >>> if decimalInt - 2**bitPlace >= 0: > >>> tempList[bitPlace] = '1' > >>> decimalInt = decimalInt - 2**bitPlace > >>> if bigEndian: > >>> tempList.reverse() > >>> > >>> outPut = ''.join(tempList) > >>> > >>> if truncExcess: > >>> if bigEndian: > >>> outPut=outPut.lstrip('0') > >>> else: > >>> outPut=outPut.rstrip('0') > >>> > >>> return outPut > >>> > >>> > >>>------------------------------------------------------------------------ > >>> > >>>_______________________________________________ > >>>Tutor maillist - Tutor@python.org > >>>http://mail.python.org/mailman/listinfo/tutor > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > > > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Pierre Barbier de Reuille > > INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP > Botanique et Bio-informatique de l'Architecture des Plantes > TA40/PSII, Boulevard de la Lironde > 34398 MONTPELLIER CEDEX 5, France > > tel : (33) 4 67 61 65 77 fax : (33) 4 67 61 56 68 -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050210/2fbaef82/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Feb 10 07:26:38 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 10 07:26:44 2005 Subject: e-mail address change (was Re: [Tutor] python's default argument value handling in functions - weird syntax? problem grappling with the concept) In-Reply-To: <420ACFDF.2080402@adinet.com.uy> Message-ID: On Thu, 10 Feb 2005, Ismael Garrido wrote: > Danny Yoo wrote: > > >### > > > >def f(a,L=[]): > > if L==[5]: > > print 'L==[5] caught' > > print L > > print 'resetting L...' > > L=[] > > L.append(a) > > return L > >### > > > Now I'm dizzy... I can't understand why there are two "L"! Hi Ismael, Ok, let's ignore the default argument stuff for the moment. Let's change the program slightly, to the following: ### someList = [] def f(a): L = someList if L == [5]: print "L == [5] caught" print L print "Resetting L..." L = [] L.append(a) return L ### Try out Jeffrey's experiments, and see if you see anything unusual. Does what you see make sense to you, or is it still baffling? Please feel free to ask questions, and we'll go from there. Best of wishes to you! From alan.gauld at freenet.co.uk Thu Feb 10 08:58:58 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 08:58:48 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? References: <420A8938.5040604@po-box.mcgill.ca> Message-ID: <07fe01c50f46$60d84240$68b78851@xp> > The main change in refactoring is moving it to OOP. I have a method > that serves as the entry point for parsing the files. Not an object? If you are thinking terms of what the methods do its probably not OOP... I would expect to see an object for the File, another for the Header, a third for the Body and another for the Node. The first (containing a header and bosdy object) is responsible for cracking open the file and reading the lines, recognising where it has a header and sending those lines to the header object and the rest to the bosy object. The body object then reades those lines and creates a Node object per node feeding it lines as appropriate... > I want the body parser to accept a list of lines corresponding to the > nodes portions of my file, separate out each node (everything between > node end tags, the bottommost end tag included in the node), and > send each node's contents to a further method for processing. Or to another object? Nouns are objects, verbs are methods. > . def body_parser(self, body_contents): Pseudo code: class Body: def __init__(self,content): self.contents = contents self.nodes = [] def parse(self): for line in self.contents: if line == NodeStartTag: node = Node() if line == NodeEndTag: self.nodes.append(node) node.append(line) def __del__(self): del self.nodes > . self.node_parser(current_node_contents) class Node: def __init__(self,lines=[]): self.lines = lines def append(self,item): self.lines.append(item) def parse(self): # your parsing method here. Whats the advantage? If you have different node types you can easily subclass Node and not change the File or Body classes, just write a slightl'y different line parser. That way your code remains more stable - you never need to change working code to add a new node type... Just an alternative to consider.... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Feb 10 09:14:04 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 09:13:45 2005 Subject: e-mail address change (was Re: [Tutor] python's default argumentvalue handling in functions - weird syntax? problem grappling withthe concept) References: <420ACFDF.2080402@adinet.com.uy> Message-ID: <083101c50f48$7ce065b0$68b78851@xp> > >def f(a,L=[]): > > if L==[5]: > > print 'L==[5] caught' > > print L > > print 'resetting L...' > > L=[] > > L.append(a) > > return L > > > > > >### > > > Now I'm dizzy... I can't understand why there are two "L"! > L is a local variable of the function, right? L is a parameter if the function with a default value. That means its a special type of local variable that has a life outside the function. But while inside the function it acts just like a local variable. > anything else) Then if I reassign L to something, why doesn't it keep > that change till next run? Because local variables die and their contents are garbage collected at the end of the function. L goes back to its external life which points at the original default L. > so it should keep the reassignation, no? No, the whole point of this thread is that Python, as the documentation said, only evaluates the default value once, at function definition time, you *cannot* change it. After each function invocation all local changes are lost and it reverts to the ioriginal value. Alan G. From alan.gauld at freenet.co.uk Thu Feb 10 09:24:24 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 09:24:30 2005 Subject: [Tutor] Hex to Str - still an open issue References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com><041401c50ae9$63c21a50$68b78851@xp><00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net><1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <084b01c50f49$ee57d510$68b78851@xp> > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? base 2 is binary, base 8 is octal. We normally use base 10 decimal. The base refers to the biggest number that can be represented by a single digit. (Actually one less than the base because we start with zero!) Thus in base 10 we have digits 0,1,2...,8,9 In base 8 we have 0,1,2...,6,7 and in binary 0,1 When we need a number bigger than a single digit can represent we add another column, so 9+1 = 10, that is 1 ten plus zero units. Similarly in base 8 & + 1 = 10 ie one eight and no units and in base 2, 1+1 = 10 ie one two and zero units. So the same principles hold as we are used to in decimal but they just kick in at different points. But these are just representational issues, the underlying value is the same in each of the following cases: 9 - base 10 11 - base 8 1001 -base 2 You might also find base 16 - hexadecimal, or more commonly just hex. There the numbers between 10 and 15 are represented by letters: 0,1,....9,A,B,C,D,E,F So the decimal number 27 is represented in hex as 1B And to make it clear which base is being used computer languages adopt a simple convention of prefixing the digit in ambiguous cases: 012 = implies 12 in base 8 (because of the leading 0 0x12 = implies 12 in hex because of the leading 0x 12 = implies decimal 12, no prefix. HTH, A web search on 'number bases' or 'binary numbers' should throw up much more detailed info Alan G. From maxnoel_fr at yahoo.fr Thu Feb 10 09:27:38 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 10 09:28:37 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1108014184.4623.1.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <26038a44985aebb1c871c2272f25ebc4@yahoo.fr> On Feb 10, 2005, at 05:43, Johan Geldenhuys wrote: > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? Usually, we use base 10 numbers, that is, numbers that can be represented with 10 symbols (0, 1, 2, 3, 4, 5, 6, 7, 8, 9). Binary, or base 2, represents all the numbers with only 2 symbols (0 and 1), whereas octal (base 8) uses 8 (0 to 7) and hexadecimal (base 16) uses 16 (0 to 9 then A to F). In binary, 0b10 = 2, and 0b100 = 4. In octal, 010 = 8 and 0100 = 64. In hexadecimal, 0x10 = 16 and 0x100 = 256. Is that clearer now? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bvande at po-box.mcgill.ca Thu Feb 10 09:34:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 10 09:35:16 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1108014184.4623.1.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <420B1CA2.7080404@po-box.mcgill.ca> Johan Geldenhuys said unto the world upon 2005-02-10 00:43: > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? > > Johan > On Tue, 2005-02-08 at 12:12, Pierre Barbier de Reuille wrote: Hi Johan, here's a go: We have 10 fingers. Not coincidentally, we have a base 10 number system. OK, what's that mean? Well, we have 10 primitive numerical symbols {0,1,2,3,4,5,6,7,8,9}. So, say we have 7 widgets and then we get another. No problem -- 8 widgets. Another -- 9. One more? Well, we are out of primitive symbols. 9 means nine units. If we add another to 9, we end up with one tens and zero units: 10. Each additional place gives us a new multiple of 10. So 10342 is one ten-thousands, zero thousands, three hundreds, four tens and two units. And, you might be thinking `Jeeze! I know all that.' Fair enough. Here's the switch: Say we had a number system with only 8 numerical primitives: {0,1,2,3,4,5,6,7). That is a base 8 system. (It isn't really the reason, but you can think of `base' as "how many primitive symbols is the number system based upon" and not be too far off.) If we have seven widgets, that's 7 as before. Add one. Well, there is no '8' symbol. So, 7 + 1 is one eights and zero units or 10 (010 in Pythonic notation but put that aside for now). Twenty four is 30 in base 8 -- 3 eights and zero units. Likewise base 8 763 is 7 sixtyfours + 6 eights + 3 units or 499 in base 10 or decimal notation. Base 2 is where we have just the two primitive symbols 0 and 1. So, 11010 in binary notation is one sixteens+ one eights + zero fours + one twos + zero units or 26 in decimal. Likewise 14 is one eights and one fours and one twos and zero units or 1110. The general principle is in a base X number system, you have only X primitives. To represent more than X - 1 things ('0' being one of the primitives) you move a place to the left, and consider the symbols in that place as representing X times as many things as the previous place. I hope I've shed more light than shadows :-) Best, brian vdB From bvande at po-box.mcgill.ca Thu Feb 10 10:43:02 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Feb 10 10:46:32 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420B2CA6.50807@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-10 02:58: >>The main change in refactoring is moving it to OOP. I have a method >>that serves as the entry point for parsing the files. > > > Not an object? If you are thinking terms of what the methods > do its probably not OOP... Hi Alan, That may well be :-) What I've done is have a class File_in_the_format, and have all the parsing work going on in methods of the class. My class is called with a filepath, the __init__ method calls the _master_parser method which breaks things into head and body, calling appropriate methods and so on. I was thinking it was OOP even with just the one class as I am making use of encapsulation and the class namespace to avoid passing parameters about. > I would expect to see an object for the File, another for the Header, > a third for the Body and another for the Node. The first (containing > a header and bosdy object) is responsible for cracking open the file > and reading the lines, recognising where it has a header and sending > those lines to the header object and the rest to the bosy object. > > The body object then reades those lines and creates a Node object > per node feeding it lines as appropriate... I originally tried to see how to do it that way, but got stuck. I'll point to where by using your pseudo code below. > Pseudo code: > class Body: > def __init__(self,content): > self.contents = contents > self.nodes = [] > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node() # Stuck here -- BvdB > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > def __del__(self): del self.nodes > I got stuck at the place where I added a comment above. I didn't see how I could do that, since I didn't yet have all of the node lines in hand when it would be time to build a node. > class Node: > def __init__(self,lines=[]): > self.lines = lines > def append(self,item): # Bing! -- BvdB > self.lines.append(item) > def parse(self): > # your parsing method here. Well, that flipped a switch! I *knew in the abstract* that I can define interfaces [?] like .append and .__add__. The puzzle pieces just hadn't come together yet. They aren't all there yet either, but a half an hour in the interpreter has already cleared away much puzzlement over how to pull this off. So, thanks a lot for the push! > > Whats the advantage? If you have different node types you > can easily subclass Node and not change the File or Body > classes, just write a slightl'y different line parser. > That way your code remains more stable - you never need > to change working code to add a new node type... Well, I don't *think* these considerations are going to enter into my particular task. I'm working with a well documented text format for a shareware app I have where the developer has recently changed the file format to an undocumented binary format. So, I can be fairly confident that my particular target is one I have complete knowledge about. But, I absolutely see the point for the general case. I'm off to scrap the code that made me happy :-( and redo it this way to learn better habits :-) Thanks again, Brian vdB From kent37 at tds.net Thu Feb 10 11:52:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 10 11:52:56 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420B3D03.2020301@tds.net> Alan Gauld wrote: >>The main change in refactoring is moving it to OOP. I have a method >>that serves as the entry point for parsing the files. > > > Not an object? If you are thinking terms of what the methods > do its probably not OOP... > > I would expect to see an object for the File, another for the Header, > a third for the Body and another for the Node. The first (containing > a header and bosdy object) is responsible for cracking open the file > and reading the lines, recognising where it has a header and sending > those lines to the header object and the rest to the bosy object. > > The body object then reades those lines and creates a Node object > per node feeding it lines as appropriate... This is a reasonable approach. Having the Body and Node classes gives a handy place to put functions to do something with that data. But I tend to take the Extreme Programming position of You Aren't Going To Need It. I would probably stick with the list representation of Node, for example, until I had some real work for the Node class to do. It's definitely a judgement call when to introduce classes, there isn't a right way and a wrong way. Some problems cry out for classes, some clearly have no need, and then there is a gray area in the middle. > Pseudo code: > class Body: > def __init__(self,content): > self.contents = contents > self.nodes = [] > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node() > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > def __del__(self): del self.nodes Why is 'del self.nodes' needed? When the Body is del'ed the reference to self.nodes should be lost and the nodes list will be GC'd. Or am I missing something? > class Node: > def __init__(self,lines=[]): > self.lines = lines > def append(self,item): > self.lines.append(item) > def parse(self): > # your parsing method here. You might want to extend list so a Node automatically has the behavior of a list. Kent From amonroe at columbus.rr.com Thu Feb 10 12:45:41 2005 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Feb 10 12:46:18 2005 Subject: [Tutor] Hex to Str - still an open issue In-Reply-To: <1108014184.4623.1.camel@KMA.accesstel> References: <812D33B03107804389D6F4247B69EFAC3A2935@dfre2k03.itg.ti.com> <041401c50ae9$63c21a50$68b78851@xp> <00ae01c50b3b$6b55d390$215428cf@JSLAPTOP> <4204EAB1.2050206@tds.net> <1107856983.4603.6.camel@KMA.accesstel> <42089086.8010407@cirad.fr> <1108014184.4623.1.camel@KMA.accesstel> Message-ID: <150916134541.20050210064541@columbus.rr.com> > I am not so clued up on the 'base 2' and 'base 8' stuff. > Care to explain that a little? Easy. Imagine the numerals 2,3,4,5,6,7,8,9 were never invented. You'd start counting at 0. Next would come 1. Now you've maxed out your first column so you have to carry to the next column, so next would come 10. Alan From jsmith at medplus.com Thu Feb 10 16:22:51 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 10 16:22:54 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) Message-ID: To all those who talked about hating the symbology in Perl and the suggestion that it should be removed from a later version. I just remembered what you get for that symbology that I really do like about Perl: variable interpolation in strings: C: sprintf(newstr,"%s %d %f",s,n,r); Becomes a little nicer in Python with: newstr = '%s %d %f' % (s,n,r) Although it's worse with: newstr = s + ' ' + str(n) + ' ' + str(r) But in my mind nothing beats the Perl statement: newstr = "$s $n $r"; for clarity, ease of use, and maintainability. Jeff From bill.mill at gmail.com Thu Feb 10 16:43:28 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 16:43:32 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: References: Message-ID: <797fe3d40502100743651ad144@mail.gmail.com> Jeff, I get the impression that many pythonistas don't like string interpolation. I've never seen a clear definition of why. Anyway, it's easy enough to add with the Itpl [1] module: >>> import Itpl, sys >>> sys.stdout = Itpl.filter() >>> s, n, r = 0, 0, 0 >>> print "$s $n $r" 0 0 0 >>> x = Itpl.itpl("$s $n $r") >>> x '0 0 0' And, of course, you can give Itpl.itpl a nicer name; I usually call it pp(). If you don't need to change the behavior of the "print" statement, then you don't need the Itpl.filter() line. [1] http://lfw.org/python/Itpl.py Peace Bill Mill bill.mill at gmail.com On Thu, 10 Feb 2005 10:22:51 -0500, Smith, Jeff wrote: > To all those who talked about hating the symbology in Perl and the > suggestion that it should be removed from a later version. I just > remembered what you get for that symbology that I really do like about > Perl: variable interpolation in strings: > > C: > sprintf(newstr,"%s %d %f",s,n,r); > > Becomes a little nicer in Python with: > newstr = '%s %d %f' % (s,n,r) > > Although it's worse with: > newstr = s + ' ' + str(n) + ' ' + str(r) > > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; > > for clarity, ease of use, and maintainability. > > Jeff > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Thu Feb 10 16:46:43 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 16:46:47 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <797fe3d40502100743651ad144@mail.gmail.com> References: <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: <797fe3d405021007466c71f46c@mail.gmail.com> Sorry for the double post; I forgot one thing: On Thu, 10 Feb 2005 10:43:28 -0500, Bill Mill wrote: > Jeff, > > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. Anyway, it's > easy enough to add with the Itpl [1] module: > > >>> import Itpl, sys > >>> sys.stdout = Itpl.filter() > >>> s, n, r = 0, 0, 0 > >>> print "$s $n $r" > 0 0 0 > >>> x = Itpl.itpl("$s $n $r") > >>> x > '0 0 0' > This works with arbitrary data types too, to be truer to your example: >>> s, n, r = '0', 12, 3.4 >>> x = Itpl.itpl("$s $n $r") >>> x '0 12 3.4' Peace Bill Mill bill.mill at gmail.com From abli at freemail.hu Thu Feb 10 18:22:30 2005 From: abli at freemail.hu (Abel Daniel) Date: Thu Feb 10 18:21:59 2005 Subject: [Tutor] Re: Perl Symbology In-Reply-To: <797fe3d40502100743651ad144@mail.gmail.com> (Bill Mill's message of "Thu, 10 Feb 2005 10:43:28 -0500") References: <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: Bill Mill writes: > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. >From "import this": Explicit is better than implicit. And doesn't perl's method mean that you have to escape _every_ _single_ '$' in strings? I think having to escape '\' is bad enough. From bgailer at alum.rpi.edu Thu Feb 10 18:33:56 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Feb 10 18:28:16 2005 Subject: ****SPAM(10.2)**** [Tutor] Re: python's default argument value handling in functions - weird syntax? problem grappling with the concept In-Reply-To: <4b3125cc0502091522316346aa@mail.gmail.com> References: <4b3125cc050209121418102fbb@mail.gmail.com> <4b3125cc0502091522316346aa@mail.gmail.com> Message-ID: <6.1.2.0.0.20050210103104.0345bbb8@mail.mric.net> I regret my original answer since it led to frustration. I missed the point that the local variable is pointed to the once-created default object, and that reassigning to that name does NOT affect the once-created default object. I am glad for a community in which we can cover each other's blind spots. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bill.mill at gmail.com Thu Feb 10 19:04:48 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 19:32:06 2005 Subject: [Tutor] Re: Perl Symbology In-Reply-To: References: <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: <797fe3d405021010046d1710e7@mail.gmail.com> On Thu, 10 Feb 2005 18:22:30 +0100, Abel Daniel wrote: > Bill Mill writes: > > > I get the impression that many pythonistas don't like string > > interpolation. I've never seen a clear definition of why. > >From "import this": > > Explicit is better than implicit. > > And doesn't perl's method mean that you have to escape _every_ > _single_ '$' in strings? I think having to escape '\' is bad enough. Abel, You've provided me with what is approximately the eleventy-seventh explanation I've gotten as to why string interpolation is bad. I don't think that any of them are "stupid", per se, but neither do I think that any of them are strong enough to be convincing. In my perfect language, string interpolation would be on by default. That said, there are enough reasons to think that it's a bad idea that it is warranted to avoid turning it on by default. I don't mind typing pp("interpolate $mystring"), and although I do wish python standardized it before version 2.4 [1], I hardly even feel that it's a wart in the language. I just wanted to tell the person who wanted string interpolation that it's easy to add into the language and easy to use. One should not take python out of consideration if one feels that string interpolation is a killer feature. Peace Bill Mill bill.mill at gmail.com [1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 From kent37 at tds.net Thu Feb 10 19:43:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 10 19:43:22 2005 Subject: [Tutor] Perl Symbology In-Reply-To: <797fe3d40502100743651ad144@mail.gmail.com> References: <797fe3d40502100743651ad144@mail.gmail.com> Message-ID: <420BAB49.6070100@tds.net> Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl(): >>> from string import Template >>> s, n, r = '0', 12, 3.4 >>> x = Template("$s $n $r") >>> x.substitute(locals()) '0 12 3.4' If you want to bundle this up in a pp() function you have to do some magic to get the locals() of the caller. This seems to work: >>> import sys >>> def pp(s): ... loc = sys._getframe(1).f_locals ... print Template(s).substitute(loc) ... >>> pp("$s $n $r") 0 12 3.4 Kent Bill Mill wrote: > Jeff, > > I get the impression that many pythonistas don't like string > interpolation. I've never seen a clear definition of why. Anyway, it's > easy enough to add with the Itpl [1] module: > > >>>>import Itpl, sys >>>>sys.stdout = Itpl.filter() >>>>s, n, r = 0, 0, 0 >>>>print "$s $n $r" > > 0 0 0 > >>>>x = Itpl.itpl("$s $n $r") >>>>x > > '0 0 0' > > And, of course, you can give Itpl.itpl a nicer name; I usually call it > pp(). If you don't need to change the behavior of the "print" > statement, then you don't need the Itpl.filter() line. > > [1] http://lfw.org/python/Itpl.py > > Peace > Bill Mill > bill.mill at gmail.com > > > On Thu, 10 Feb 2005 10:22:51 -0500, Smith, Jeff wrote: > >>To all those who talked about hating the symbology in Perl and the >>suggestion that it should be removed from a later version. I just >>remembered what you get for that symbology that I really do like about >>Perl: variable interpolation in strings: >> >>C: >>sprintf(newstr,"%s %d %f",s,n,r); >> >>Becomes a little nicer in Python with: >>newstr = '%s %d %f' % (s,n,r) >> >>Although it's worse with: >>newstr = s + ' ' + str(n) + ' ' + str(r) >> >>But in my mind nothing beats the Perl statement: >>newstr = "$s $n $r"; >> >>for clarity, ease of use, and maintainability. >> >>Jeff >> >>_______________________________________________ >>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 jsmith at medplus.com Thu Feb 10 19:59:04 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Thu Feb 10 19:59:17 2005 Subject: [Tutor] Re: Perl Symbology Message-ID: Abel, No, you don't have to escape them all. Perl treats single and double quotes differently. Single-quoted strings don't do interpolation and double-quoted strings do. Jeff -----Original Message----- From: Abel Daniel [mailto:abli@freemail.hu] Sent: Thursday, February 10, 2005 12:23 PM To: tutor@python.org Subject: [Tutor] Re: Perl Symbology Bill Mill writes: > I get the impression that many pythonistas don't like string >interpolation. I've never seen a clear definition of why. From "import >this": Explicit is better than implicit. And doesn't perl's method mean that you have to escape _every_ _single_ '$' in strings? I think having to escape '\' is bad enough. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From bill.mill at gmail.com Thu Feb 10 19:59:58 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 20:00:02 2005 Subject: [Tutor] Perl Symbology In-Reply-To: <420BAB49.6070100@tds.net> References: <797fe3d40502100743651ad144@mail.gmail.com> <420BAB49.6070100@tds.net> Message-ID: <797fe3d405021010597afb4ff1@mail.gmail.com> Kent, On Thu, 10 Feb 2005 13:43:21 -0500, Kent Johnson wrote: > Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl(): > > >>> from string import Template > >>> s, n, r = '0', 12, 3.4 > >>> x = Template("$s $n $r") > >>> x.substitute(locals()) > '0 12 3.4' > > If you want to bundle this up in a pp() function you have to do some magic to get the locals() of > the caller. This seems to work: > > >>> import sys > >>> def pp(s): > ... loc = sys._getframe(1).f_locals > ... print Template(s).substitute(loc) > ... > >>> pp("$s $n $r") > 0 12 3.4 > I just didn't want to give an answer that only works in python 2.4, and one furthermore which I have not tested. You can also find a recipe to make pp() easy to make at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 . This function may or may not be better than yours; I haven't used either. the Itpl module has worked fine for me (and for the author of ipython) for quite a while. Peace Bill Mill bill.mill at gmail.com From kent37 at tds.net Thu Feb 10 20:22:52 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu Feb 10 20:22:53 2005 Subject: [Tutor] Perl Symbology In-Reply-To: <797fe3d405021010597afb4ff1@mail.gmail.com> References: <797fe3d40502100743651ad144@mail.gmail.com> <420BAB49.6070100@tds.net> <797fe3d405021010597afb4ff1@mail.gmail.com> Message-ID: <420BB48C.3020003@tds.net> Bill Mill wrote: > Kent, > > On Thu, 10 Feb 2005 13:43:21 -0500, Kent Johnson wrote: > >>Python 2.4 includes a string.Template class which does much the same thing as Itpl.itpl(): > > I just didn't want to give an answer that only works in python 2.4, > and one furthermore which I have not tested. > > You can also find a recipe to make pp() easy to make at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/335308 . This > function may or may not be better than yours; I haven't used either. It's better, it looks at locals() and globals() as well as allowing dict and keyword args do pp() directly. > the Itpl module has worked fine for me (and for the author of ipython) > for quite a while. I certainly didn't mean to cast any doubt on Itpl, I just thought it was worth pointing out that there is some support in the standard library now. Kent From alan.gauld at freenet.co.uk Thu Feb 10 20:28:26 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Feb 10 20:28:10 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) References: Message-ID: <087d01c50fa6$b1debec0$68b78851@xp> > Although it's worse with: > newstr = s + ' ' + str(n) + ' ' + str(r) You could try: newstr = s + ' ' + `n` + ' ' + `r` if you think thats better. But `` is different to str() for some types. Personally I prefer the formatting approach. > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; Perl is king of string processing in modern scripting, without a doubt. But even here the $ prefix could have been used for that specific purpose without insisting it be used everywhere else! BTW Anyone recall how Ruby does this? Alan G. Too lazy to look it up! From bill.mill at gmail.com Thu Feb 10 20:50:34 2005 From: bill.mill at gmail.com (Bill Mill) Date: Thu Feb 10 20:50:38 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <087d01c50fa6$b1debec0$68b78851@xp> References: <087d01c50fa6$b1debec0$68b78851@xp> Message-ID: <797fe3d40502101150552f5cf4@mail.gmail.com> On Thu, 10 Feb 2005 19:28:26 -0000, Alan Gauld wrote: > > Although it's worse with: > > newstr = s + ' ' + str(n) + ' ' + str(r) > > You could try: > > newstr = s + ' ' + `n` + ' ' + `r` > > if you think thats better. > But `` is different to str() for some types. > > Personally I prefer the formatting approach. > > > But in my mind nothing beats the Perl statement: > > newstr = "$s $n $r"; > > Perl is king of string processing in modern scripting, > without a doubt. But even here the $ prefix could have > been used for that specific purpose without insisting > it be used everywhere else! > > BTW Anyone recall how Ruby does this? I don't know ruby at all, but a quick google and 30 interpreter seconds later: irb(main):001:0> x = 12 => 12 irb(main):002:0> '$x' => "$x" irb(main):003:0> "$x" => "$x" irb(main):004:0> "#{$x}" => "" irb(main):005:0> "#{x}" => "12" irb(main):006:0> '#{x}' => "#{x}" so "#{} . Peace Bill Mill bill.mill at gmail.com From maxnoel_fr at yahoo.fr Thu Feb 10 20:58:55 2005 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Feb 10 20:59:02 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: <797fe3d40502101150552f5cf4@mail.gmail.com> References: <087d01c50fa6$b1debec0$68b78851@xp> <797fe3d40502101150552f5cf4@mail.gmail.com> Message-ID: <214aeeb0995e82517f33ca6c5895a688@yahoo.fr> On Feb 10, 2005, at 19:50, Bill Mill wrote: > so "#{ myriad of other ways, which I haven't even looked at. They all seem to > involve #{[symbol]} . Here, [symbol] refers to the scope(?) of the variable. See the discussion between me and Alan on this topic a while ago -- the use of these symbols being his main criticism of Ruby. foo is a local variable $foo is a global variable @foo is an instance variable @@foo is a class variable FOO is a constant (which can be modded into global, instance or class with the appropriate use of $, @ or @@) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From hugonz-lists at h-lab.net Thu Feb 10 18:31:50 2005 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu Feb 10 23:06:34 2005 Subject: [Tutor] Perl Symbology (was: Are you allowed to shoot camels?) In-Reply-To: References: Message-ID: <420B9A86.5000804@h-lab.net> Smith, Jeff wrote: > But in my mind nothing beats the Perl statement: > newstr = "$s $n $r"; > > for clarity, ease of use, and maintainability. Only a little ease of use is lost with the following in Python, clarity and maintainability are kept, and it even will let you format the output (as in # of decimal places) newstr = "%{s}s %(n)s %(r)s"%locals() If you cannot assume a type you can always just use %s... Hugo From cyresse at gmail.com Fri Feb 11 08:09:10 2005 From: cyresse at gmail.com (Liam Clarke) Date: Fri Feb 11 08:09:13 2005 Subject: [Tutor] Data storage, SQL? Message-ID: Hi, I'm looking to create a prog that will store disparate bits of info all linked together, i.e. address details for a person, transaction records, specific themes, and the ability to search by certain criteria, so I'm pretty sure I want a database. Can anyone recommend a useful database library for Python that's not too complex? Also, I keep hearing about SQL, would this be the best way to go? I don't know much about databases. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bvande at po-box.mcgill.ca Fri Feb 11 09:04:27 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Feb 11 09:06:03 2005 Subject: [Tutor] default argument frustration In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420C670B.4070209@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-10 02:58: > class Node: > def __init__(self,lines=[]): # here's the zowie BvdB > self.lines = lines > def append(self,item): > self.lines.append(item) > def parse(self): > # your parsing method here. Hi all, I've been following the general approach that Alan suggested and have been happily making much headway. (The code is about twice as long as before and does about 4 times as many things :-) ) At first, I ended up with every single node being a copy of the first one processed. A bit of weeping later, I realized that this is from the feature [?] of Python that default arguments are evaluated just once. (Note the comment added above.) Happily, I didn't need the default argument. And even if I did, there's the work around from the tutorial that's been under recent discussion in the python's default argument value handling in functions - weird syntax? problem grappling with the concept thread. I may have missed the discussion in that thread but: FOR THE LOVE OF MIKE can someone tell me even one reason why this isn't a misfeature?!?! Sorry for the shouting, but this issue seems to come up a lot. Officially, I do know about it, but it often takes me considerable frustration to realize it's what's ruining my day. I'd be far happier if I could see that there was a good reason for this behaviour. (There'd even be a chance that I'd remember more readily--I hope so, these keyboards are getting expensive.) I'm sure there is one, as I don't believe that Dutchman are particularly given to sadism. Thanks, and best to all, Brian vdB From kent37 at tds.net Fri Feb 11 12:00:34 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 12:00:41 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: References: Message-ID: <420C9052.2070009@tds.net> Liam Clarke wrote: > Hi, > > I'm looking to create a prog that will store disparate bits of info > all linked together, i.e. address details for a person, transaction > records, specific themes, and the ability to search by certain > criteria, so I'm pretty sure I want a database. > > Can anyone recommend a useful database library for Python that's not > too complex? Most Python database access modules implement the Python DB-API. This is a standard API created by the Python community. As a result most Python database libraries are pretty similar from the programmer's point of view. See the Database Topic Guide for the DB-API spec and links to modules that support it. http://www.python.org/topics/database/ > Also, I keep hearing about SQL, would this be the best way to go? I > don't know much about databases. SQL is a standardized language for giving commands to databases. Most (all?) industrial-strength databases use SQL as their command language. (DB-API is actually a wrapper around SQL - it standardizes the API to issue a SQL command and read the results.) SQL is kind of a strange beast and has a style and learning curve all its own. It is worth learning if you expect to be using databases much in your future. There are some light-weight databases that don't use SQL (KirbyBase and MetaKit are two) but all of the major ones do. A couple of pages that might help you make a choice: http://www.python.org/moin/DatabaseInterfaces http://www.python.org/moin/ChoosingDatabase Note that DB-API and SQL don't provide 100% portability between databases; there are differences in the details that can trip you up. Kent > > Regards, > > Liam Clarke From matthew.williams at cancer.org.uk Fri Feb 11 12:29:38 2005 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Fri Feb 11 12:29:45 2005 Subject: [Tutor] Database In-Reply-To: <20050211110157.8EB271E400E@bag.python.org> References: <20050211110157.8EB271E400E@bag.python.org> Message-ID: <1108121378.2916.14.camel@dhcp0320.acl.icnet.uk> I would recommend KirbyBase as a quick starter - it's nice and simple, and outputs text files, so you can always check things manually. http://www.netpromi.com/kirbybase.html Matt From kent37 at tds.net Fri Feb 11 13:34:41 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 13:34:45 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <420C9052.2070009@tds.net> References: <420C9052.2070009@tds.net> Message-ID: <420CA661.8080900@tds.net> Kent Johnson wrote: > SQL is a standardized language for giving commands to databases. Most > (all?) industrial-strength databases use SQL as their command language. > (DB-API is actually a wrapper around SQL - it standardizes the API to > issue a SQL command and read the results.) > > SQL is kind of a strange beast and has a style and learning curve all > its own. It is worth learning if you expect to be using databases much > in your future. There are some light-weight databases that don't use SQL > (KirbyBase and MetaKit are two) but all of the major ones do. I don't know any good on-line resources for learning SQL - maybe others have a recommendation. A book I like is "The Practical SQL Handbook" by Judith Bowman, Sandra Emerson, Marcy Darnovsky http://www.bookpool.com/ss?qs=Practical+SQL+Handbook&x=0&y=0 Kent From kent37 at tds.net Fri Feb 11 14:04:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 14:04:23 2005 Subject: [Tutor] default argument frustration In-Reply-To: <420C670B.4070209@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> Message-ID: <420CAD54.2020509@tds.net> Brian van den Broek wrote: > At first, I ended up with every single node being a copy of the first > one processed. A bit of weeping later, I realized that this is from the > feature [?] of Python that default arguments are evaluated just once. > (Note the comment added above.) > > > FOR THE LOVE OF MIKE can someone tell me even one reason why this isn't > a misfeature?!?! > I will guess...because historically it was useful, and because the alternative is problematic. Before Python 2.1, when nested scopes were introduced, default arguments were widely used as a way to bind values from the local environment into a function. For example, suppose I want to write a function of one argument that returns a function of one argument that adds the two arguments together. Today, I can write >>> def makeAdder(n): ... def f(x): ... return x+n ... return f ... >>> add5 = makeAdder(5) >>> add5(2) 7 In Python 2.0 this doesn't work, add5 will not know the value of n. The common workaround was to provide n as a default argument to f: >>> def makeAdder2(n): ... def f(x, n=n): ... return x+n ... return f Now n is bound as a default argument when f is created, and makeAdder2() works the same as makeAdder(). OK, now imagine what would happen to makeAdder2() if the default argument was evaluated at the point of call? It would use whatever value of n was in scope at the time. This could be confusing - n might well not even be defined! What this really does is make variables in default arguments be dynamically scoped. Since other variables in Python are lexically scoped, this would be kind of strange. http://en.wikipedia.org/wiki/Dynamic_scoping http://en.wikipedia.org/wiki/Lexical_variable_scoping Kent From kent37 at tds.net Fri Feb 11 14:05:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 14:05:31 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <420CA661.8080900@tds.net> References: <420C9052.2070009@tds.net> <420CA661.8080900@tds.net> Message-ID: <420CAD99.2030404@tds.net> Kent Johnson wrote: > I don't know any good on-line resources for learning SQL The Wikipedia entry for SQL has links to quite a few tutorials: http://en.wikipedia.org/wiki/Sql Kent From jsmith at medplus.com Fri Feb 11 15:28:35 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 11 15:28:38 2005 Subject: [Tutor] Simple question on creating a filter Message-ID: I'm sorry to both with such a simple question but I've looked in the normal places and don't see the quick and dirty answer I know must exist. I want to write a simple line selection filter that could be used like: filter < file In Perl I would do: while (<>) { print if line meets selection criteria; } I've tried what I thought would be the Python equivalent but it doesn't work: for line in sys.stdin: if line meets selection criteria: print line I get the following at runtime: Traceback (most recent call last): File "U:\TimeKeeper\mine.py", line 2, in ? for line in sys.stdin: IOError: [Errno 9] Bad file descriptor This is with Python 2.4 on Windows. Jeff From bill.mill at gmail.com Fri Feb 11 15:38:01 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 11 15:38:05 2005 Subject: [Tutor] Simple question on creating a filter In-Reply-To: References: Message-ID: <797fe3d405021106387fe92acf@mail.gmail.com> On Fri, 11 Feb 2005 09:28:35 -0500, Smith, Jeff wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > No worries; that's what this list is for. > I want to write a simple line selection filter that could be used like: > > filter < file > > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } > > I've tried what I thought would be the Python equivalent but it doesn't > work: > > for line in sys.stdin: > if line meets selection criteria: > print line > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor > I'm not quite sure how you're getting that "bad file dscriptor" error. My code, also on windows (and cygwin) with python2.4: /d/code/python$ cat test.py import sys for line in sys.stdin: if line.startswith('a'): print line.strip() /d/code/python$ cat test_in aline1 bline2 aline3 cline4 /d/code/python$ python test.py < test_in aline1 aline3 Try to run it like I did, and let me know if it gives you the same thing; that'll give us a common point of reference. Peace Bll Mill bill.mill at gmail.com > This is with Python 2.4 on Windows. > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maitj at vianet.ca Fri Feb 11 16:03:30 2005 From: maitj at vianet.ca (Jeffrey Maitland) Date: Fri Feb 11 16:03:37 2005 Subject: [Tutor] Might be a silly question! Message-ID: <20050211150330.24150.qmail@mail.vianet.ca> Hello all, I am drawing a blank right now and can't seem to find anything on it and I am sure this issue has been addressed before, so here is the question. Can and if you can how do you set a variable as a constant? Example of what I mean: (this is loose and not python since variable type declaration is not needed in python) CONST int gamma = 5 This would mean in my little mind that the variable gamma which is an integer of 5 can not be changed in the code and would throw an error if you tried. Just wondering if there is a way of doing this in Python. This is just to clear this up in my mind it means nothing to my code since the way I write variable names any variable I want to remain unchanged I use caps to help distinguish easily. Thanks. Jeff "They say the quickest way between to 2 points is a straight line, however where is the fun in that?" From jsmith at medplus.com Fri Feb 11 16:26:50 2005 From: jsmith at medplus.com (Smith, Jeff) Date: Fri Feb 11 16:26:55 2005 Subject: [Tutor] Simple question on creating a filter Message-ID: Good catch Bill, I was using assoc and ftype to allow me to run my filter.py directly as a command and using: filter < file Unfortunately, Windows doesn't handle this properly and I had to do C:\Python24\python filter.py < file To get it to work. Thanks, Jeff P.S. In retrospect, I've had the same problem with Perl but because of my newbie status I assumed I was doin' something wrong :-) -----Original Message----- From: Bill Mill [mailto:bill.mill@gmail.com] Sent: Friday, February 11, 2005 9:38 AM To: Smith, Jeff Cc: tutor@python.org Subject: Re: [Tutor] Simple question on creating a filter On Fri, 11 Feb 2005 09:28:35 -0500, Smith, Jeff wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > No worries; that's what this list is for. > I want to write a simple line selection filter that could be used > like: > > filter < file > > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } > > I've tried what I thought would be the Python equivalent but it > doesn't > work: > > for line in sys.stdin: > if line meets selection criteria: > print line > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor > I'm not quite sure how you're getting that "bad file dscriptor" error. My code, also on windows (and cygwin) with python2.4: /d/code/python$ cat test.py import sys for line in sys.stdin: if line.startswith('a'): print line.strip() /d/code/python$ cat test_in aline1 bline2 aline3 cline4 /d/code/python$ python test.py < test_in aline1 aline3 Try to run it like I did, and let me know if it gives you the same thing; that'll give us a common point of reference. Peace Bll Mill bill.mill at gmail.com > This is with Python 2.4 on Windows. > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill.mill at gmail.com Fri Feb 11 16:38:57 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri Feb 11 16:39:02 2005 Subject: [Tutor] Might be a silly question! In-Reply-To: <20050211150330.24150.qmail@mail.vianet.ca> References: <20050211150330.24150.qmail@mail.vianet.ca> Message-ID: <797fe3d405021107383f191157@mail.gmail.com> Jeff, On Fri, 11 Feb 2005 10:03:30 -0500, Jeffrey Maitland wrote: > > Hello all, > > I am drawing a blank right now and can't seem to find anything on it and I > am sure this issue has been addressed before, so here is the question. > > Can and if you can how do you set a variable as a constant? > > Example of what I mean: (this is loose and not python since variable type > declaration is not needed in python) > > CONST int gamma = 5 > > This would mean in my little mind that the variable gamma which is an > integer of 5 can not be changed in the code and would throw an error if you > tried. Just wondering if there is a way of doing this in Python. There is no real way to guarantee this in Python. > This is > just to clear this up in my mind it means nothing to my code since the way I > write variable names any variable I want to remain unchanged I use caps to > help distinguish easily. Constants are enforced by convention in Python. Any variable with a name in ALL CAPS is considered to be a constant, and it is considered bad programming style to change it. While it sounds like a weak system, and I'm sure there have been problems with it, I've never heard of one. Remember to only import the names you need from the classes you import, and you should be fine. Peace Bill Mill bill.mill at gmail.com From maitj at vianet.ca Fri Feb 11 16:47:42 2005 From: maitj at vianet.ca (Jeffrey Maitland) Date: Fri Feb 11 16:47:45 2005 Subject: [Tutor] Re: Might be a silly question! In-Reply-To: <797fe3d405021107383f191157@mail.gmail.com> References: <20050211150330.24150.qmail@mail.vianet.ca> <797fe3d405021107383f191157@mail.gmail.com> Message-ID: <20050211154742.30487.qmail@mail.vianet.ca> Thanks that's what I thought. Wasn't 100% sure that is what prompted me to ask the question in here. As for the CAPS thing for constants, I generally try and practice (to the best of my knowledge) proper programming consepts/styles/standards. However I have been reading code written before me (mind you it's C++) and the authors seemed to follow what ever style they wished to that day. Oh well that's the nature of the beast. Thanks again for clearing that up for me. Jeff Bill Mill writes: > Jeff, > > On Fri, 11 Feb 2005 10:03:30 -0500, Jeffrey Maitland wrote: >> >> Hello all, >> >> I am drawing a blank right now and can't seem to find anything on it and I >> am sure this issue has been addressed before, so here is the question. >> >> Can and if you can how do you set a variable as a constant? >> >> Example of what I mean: (this is loose and not python since variable type >> declaration is not needed in python) >> >> CONST int gamma = 5 >> >> This would mean in my little mind that the variable gamma which is an >> integer of 5 can not be changed in the code and would throw an error if you >> tried. Just wondering if there is a way of doing this in Python. > > There is no real way to guarantee this in Python. > >> This is >> just to clear this up in my mind it means nothing to my code since the way I >> write variable names any variable I want to remain unchanged I use caps to >> help distinguish easily. > > Constants are enforced by convention in Python. Any variable with a > name in ALL CAPS is considered to be a constant, and it is considered > bad programming style to change it. While it sounds like a weak > system, and I'm sure there have been problems with it, I've never > heard of one. Remember to only import the names you need from the > classes you import, and you should be fine. > > Peace > Bill Mill > bill.mill at gmail.com From mark.brown at rogers.com Fri Feb 11 16:52:03 2005 From: mark.brown at rogers.com (Mark Brown) Date: Fri Feb 11 16:52:13 2005 Subject: [Tutor] Negative IF conditions Message-ID: <420CD4A3.6040105@rogers.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/f769586e/attachment.html From zanesdad at bellsouth.net Fri Feb 11 17:04:11 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri Feb 11 17:05:45 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <420CD77B.2050106@bellsouth.net> Mark Brown wrote: > Hi, > I'm a newbie and was wondering which of these IF conditions is better > structure: > > 1. if not os.path.exists('filename'): > 2. if os.path.exists('filename') == False: > My preference would be the first (if not os.path.exists). os.path.exists returns a boolean (I think), so the "if" will directly check that rather than having to setup a second truth statement (== False) for "if" to check. It's more readable to me and just "feels better." > They both work so if one preferred over the other? > Thanks > Mark Brown > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/97fb3f68/attachment.htm From bvande at po-box.mcgill.ca Fri Feb 11 17:15:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Feb 11 17:16:32 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <07fe01c50f46$60d84240$68b78851@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> Message-ID: <420CDA1D.5040204@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-10 02:58: > Pseudo code: > class Body: > def __init__(self,content): > self.contents = contents > self.nodes = [] > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node() > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > class Node: > def __init__(self,lines=[]): > self.lines = lines > def append(self,item): > self.lines.append(item) > def parse(self): > # your parsing method here. Hi all, YAQ (Yet Another Question): Following the general pattern, I end up with a Body object which has an attribute .nodes that consists of a list of Node objects. So, something like: My Example Body Node List Node the first Node the second Is there any way to make methods of the Node class access attributes of `parents' of instances? I would like a Node instance such as Node the first above to be aware just what it is a node of and what its siblings are. Does this make sense? Best to all, Brian vdB PS Thanks for the reply to my venting question, Kent. From zanesdad at bellsouth.net Fri Feb 11 17:27:37 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri Feb 11 17:29:05 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <420CDA1D.5040204@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> Message-ID: <420CDCF9.8000603@bellsouth.net> Brian van den Broek wrote: > Alan Gauld said unto the world upon 2005-02-10 02:58: > >> Pseudo code: >> class Body: >> def __init__(self,content): >> self.contents = contents >> self.nodes = [] >> >> def parse(self): >> for line in self.contents: >> if line == NodeStartTag: >> node = Node() >> if line == NodeEndTag: >> self.nodes.append(node) >> node.append(line) >> >> class Node: >> def __init__(self,lines=[]): >> self.lines = lines >> def append(self,item): >> self.lines.append(item) >> def parse(self): >> # your parsing method here. > > > Hi all, > > YAQ (Yet Another Question): > > Following the general pattern, I end up with a Body object which has > an attribute .nodes that consists of a list of Node objects. > > So, something like: > > My Example Body > Node List > Node the first > Node the second > > Is there any way to make methods of the Node class access attributes > of `parents' of instances? I would like a Node instance such as Node > the first above to be aware just what it is a node of and what its > siblings are. > > Does this make sense? I think so. I haven't tested this (pseudo) code which I took from your above post and just modified it, but I think you want something like this: Pseudo code: class Body: def __init__(self,content): self.contents = contents self.nodes = [] def parse(self): for line in self.contents: if line == NodeStartTag: node = Node(self) #when you create a node, pass in the parent object like this if line == NodeEndTag: self.nodes.append(node) node.append(line) class Node: def __init__(self, parent, lines=[]): self.lines = lines self.parent = parent #and store the parent like this def append(self,item): self.lines.append(item) def parse(self): # your parsing method here. def show_siblings(self): print self.parent.nodes # and you can access the parent kinda like this. You don't want to get too carried away with something like this, though. You may want to read up on the Law of Demeter. This (in my opinion) is fine, though. > > Best to all, > > Brian vdB > > PS Thanks for the reply to my venting question, Kent. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Jeremy Jones From kent37 at tds.net Fri Feb 11 17:34:02 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 17:34:07 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <420CDA1D.5040204@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> Message-ID: <420CDE7A.3010408@tds.net> Brian van den Broek wrote: > Alan Gauld said unto the world upon 2005-02-10 02:58: > >> Pseudo code: >> class Body: >> def __init__(self,content): >> self.contents = contents >> self.nodes = [] >> >> def parse(self): >> for line in self.contents: >> if line == NodeStartTag: >> node = Node() >> if line == NodeEndTag: >> self.nodes.append(node) >> node.append(line) >> >> class Node: >> def __init__(self,lines=[]): >> self.lines = lines >> def append(self,item): >> self.lines.append(item) >> def parse(self): >> # your parsing method here. > > > Hi all, > > YAQ (Yet Another Question): > > Following the general pattern, I end up with a Body object which has an > attribute .nodes that consists of a list of Node objects. > > So, something like: > > My Example Body > Node List > Node the first > Node the second > > Is there any way to make methods of the Node class access attributes of > `parents' of instances? I would like a Node instance such as Node the > first above to be aware just what it is a node of and what its siblings > are. You have to tell it the parent. ("Explicit is better than implicit.") For example you could pass a reference to Body to the Node in the constructor: def parse(self): for line in self.contents: if line == NodeStartTag: node = Node(self) # HERE if line == NodeEndTag: self.nodes.append(node) node.append(line) In general I think this is a bad design. I try to avoid telling components about their parents in any kind of containment hierarchy. If the component knows about its parent, then the component can't be reused in a different context and it can't be tested without creating the expected context. Is there another way you could accomplish what you want? Kent > > Does this make sense? > > Best to all, > > Brian vdB > > PS Thanks for the reply to my venting question, Kent. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ryan at acceleration.net Fri Feb 11 18:39:40 2005 From: ryan at acceleration.net (Ryan Davis) Date: Fri Feb 11 18:39:46 2005 Subject: [Tutor] Larger program organization Message-ID: <20050211173944.07AAC1E4008@bag.python.org> I'm starting to make a code-generation suite in python, customized to the way we ASP.NET at my company, and I'm having some trouble finding a good way to organize all the code. I keep writing it, but it feels more and more spaghetti-ish every day. I'm going to look at the other stuff in site-packages to see if I can glean any wisdom, and have googled a bit, coming up mostly blank or with trivial examples. Are there any helpful links or advice anyone has for building larger systems? My background is mostly C#, so I'm used to the ridiculous rigidity of strongly-typed languages. I have been using python for helper apps for a few months now, so am pretty familiar with the syntax now, but I don't know any of the patterns yet. My nefarious goal is to supplant C#/ASP.NET with Python, but I need to figure out how to make programs clients want to pay for before I can make any reasonable argument. Thanks, Ryan ---- Ryan Davis Director of Programming Services http://www.acceleration.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/05b2eaec/attachment.html From alan.gauld at freenet.co.uk Fri Feb 11 19:21:25 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:20:44 2005 Subject: [Tutor] Data storage, SQL? References: Message-ID: <001901c51066$80ad0b20$31d78751@xp> > I'm looking to create a prog that will store disparate bits of info > all linked together, i.e. address details for a person, transaction > records, specific themes, and the ability to search by certain > criteria, so I'm pretty sure I want a database. Sounds a lot like it! > Can anyone recommend a useful database library for Python that's not > too complex? MYSql gets a lot of fans. PostGres is also popular and both are free. My personal favourite although I'm not sure the free version is still available is Borland's Interbase (and there was an open source spinoff too - Firebird - not to be confused with the mail tool! I just checked and Interbvase is still free to download. A comparison of all 3 can be found here: http://www.skippingdot.net/2002/02/01 > Also, I keep hearing about SQL, would this be the best way to go? I > don't know much about databases. You should learn SQL. Its a very powerful and useful tool for any kind of serious data work and is fairly portable between databases from MS Access on a PC to IBMs DB2 on a mainframe. Basic use is very easy: SELECT FIELD1,FIELD2,... FROM TABLE1,TABLE2 WHERE TABLE.FIELD VALUE ORDER BY FIELD And you can abbreviate it as needed and add extra complexity too. Here is a more concrete example: SELECT Name, Age FROM Student WHERE Age > 30 ORDER by Name Will return a tuple of Name, Age pairs for all records in the Student table where the age is greater than 30 and sorted by student name. Now think about how much Python code youd need to do that from a flat file... Doable but much harder work. Now lets start linking data together: SELECT Name, Age, Course.Name FROM Student, Course WHERE Age > 30 AND Student.CourseID = Course.CourseID ORDER BY Name Here we are linking the course table with the student table so we can see which courses our mature students are studying. There are lots of other things you can do including nesting select statements, only having unique values output etc. The other advantage is that if you just want to explore your data most databases will provide an interactive prompt (like Pythons >>>) where you can interactively type SQL queries so the development style is very like Python and the two can be used together very easily and naturally. (Maybe I could do a SQL primer as part of my advanced topics section in the tutorial... hmm. An intro to SQL then the next topic showing how to use the Python DBAPI to link SQL and Python - any takers for that idea?) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Feb 11 19:30:17 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:29:35 2005 Subject: [Tutor] default argument frustration References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> Message-ID: <001e01c51067$bd0478f0$31d78751@xp> > > FOR THE LOVE OF MIKE can someone tell me even one reason why this > isn't a misfeature?!?! > :-) Its the only sane way to implement default arguments. The whole point of function definitions is that they provide a single concise interface. The function should return the same result each time you call it with the same input. The only way to achieve that is to have the default calculated once. The problem is that the default value can be a mutable object (and that aspect could be argued as a mis-feature) which leads to apparently different behaviour for the same input as the recent thread illustrated. But in fact the same object is being returnd its just the internal content that changes... And of course this behaviour is exploited regularly in Python in the same way that static variables are exploited in C. But I agree that it can be confusing when the default is mutable but since the only reasonable option would have been to restrict default values to immutable types I think I prefer the confusion... Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:35:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:35:18 2005 Subject: [Tutor] Data storage, SQL? References: <420C9052.2070009@tds.net> <420CA661.8080900@tds.net> Message-ID: <003501c51068$85c32890$31d78751@xp> > I don't know any good on-line resources for learning SQL I like http://www.sqlcourse.com/ Its got a live SQL prompt so you can practice with their database and see the results. It seems fairly clearly written too. Caveat: I'#ve only gone through a few of the pages to check it out, I haven't followeed it to completion - and I already know SQL which always helps! But its best to get a book that focuses on the specific dialect used by your database in the longer term. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:39:27 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:39:40 2005 Subject: [Tutor] Simple question on creating a filter References: Message-ID: <004401c51069$254904c0$31d78751@xp> > In Perl I would do: > > while (<>) > { > print if line meets selection criteria; > } You may want to check out the fileinput module. It takes care of multiple files being passed as input and such like too. > for line in sys.stdin: > if line meets selection criteria: > print line > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor Sorry, I'm stumped - you did import sys I assume? Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:42:02 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:41:24 2005 Subject: [Tutor] Might be a silly question! References: <20050211150330.24150.qmail@mail.vianet.ca> Message-ID: <004501c51069$60abf5e0$31d78751@xp> > Can and if you can how do you set a variable as a constant? Only by resorting to tricks involving classes and properties. There is a cookbook recipe if I recall correctly. Vanilla Python doesn't have the concept of constants other than as a naming convention (all uppercase). Its part of the "we are all consenting adults" approach. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:44:18 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:43:40 2005 Subject: [Tutor] Re: Might be a silly question! References: <20050211150330.24150.qmail@mail.vianet.ca><797fe3d405021107383f191157@mail.gmail.com> <20050211154742.30487.qmail@mail.vianet.ca> Message-ID: <005901c51069$b1d08350$31d78751@xp> > I have been reading code written before me (mind you it's C++) and the > authors seemed to follow what ever style they wished to that day. And that's C++ style, it has no single standard approach... > that's the nature of the beast. How very true. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:45:51 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:50:26 2005 Subject: [Tutor] Negative IF conditions References: <420CD4A3.6040105@rogers.com> Message-ID: <005e01c51069$e92f0330$31d78751@xp> > I'm a newbie and was wondering which of these IF conditions is better structure: > 1.. if not os.path.exists('filename'): > 2.. if os.path.exists('filename') == False: Which one reads easiest? I'd say the first one personally. But both are OK. Alan G. From alan.gauld at freenet.co.uk Fri Feb 11 19:51:19 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Feb 11 19:50:47 2005 Subject: [Tutor] help with refactoring needed -- which approach ismorePythonic? References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> Message-ID: <006d01c5106a$ad0bb2d0$31d78751@xp> > My Example Body > Node List > Node the first > Node the second > > Is there any way to make methods of the Node class access attributes > of `parents' of instances? I would like a Node instance such as Node > the first above to be aware just what it is a node of and what its > siblings are. Pass a reference to the container into the constructor of Node class Body: .... def parse(self): for line in self.contents: if line == NodeStartTag: node = Node(self) if line == NodeEndTag: self.nodes.append(node) node.append(line) And modify the Node constructor to accept and assign the value to self.parent. This is the same approach used in Tkinter to navigate between GUI components such as buttons and theor containing frame. (And to pick up on someone else's question this is why you should put in a __del__ to tidy up the Node list when Body is destructed - otherwise you get circular references which can cause memory leaks by confusing the garbage collector! HTH Alan G. From kent37 at tds.net Fri Feb 11 20:19:14 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 20:19:14 2005 Subject: [Tutor] help with refactoring needed -- which approach ismorePythonic? In-Reply-To: <006d01c5106a$ad0bb2d0$31d78751@xp> References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <006d01c5106a$ad0bb2d0$31d78751@xp> Message-ID: <420D0532.9050800@tds.net> Alan Gauld wrote: > (And to pick up on someone else's question this is why you should > put in a __del__ to tidy up the Node list when Body is destructed > - otherwise you get circular references which can cause memory > leaks by confusing the garbage collector! CPython has been able to GC cycles since version 2.0. http://www.amk.ca/python/2.0/index.html#SECTION000900000000000000000 AFAIK Java has always been able to GC cycles so Jython should be OK too. Kent From billk at fastmail.fm Fri Feb 11 20:29:51 2005 From: billk at fastmail.fm (Bill Kranec) Date: Fri Feb 11 20:29:46 2005 Subject: [Tutor] Data storage, SQL? In-Reply-To: <001901c51066$80ad0b20$31d78751@xp> References: <001901c51066$80ad0b20$31d78751@xp> Message-ID: <420D07AF.3050505@fastmail.fm> I also recommend learning SQL. It is not very hard to learn, and sometimes it may be advantageous to do data manipulation directly in the database, rather than with Python. As far as databases go, I would recommend Firebird, as I have found that it has a good number of features, is free, and yet is also fairly easy to install and run, even on Windows (I could never get MySQL to work quite right). FlameRobin (http://flamerobin.sourceforge.net/) is a nice GUI interface for Firebird. >(Maybe I could do a SQL primer as part of my advanced >topics section in the tutorial... hmm. An intro to SQL then >the next topic showing how to use the Python DBAPI to >link SQL and Python - any takers for that idea?) > >Alan G > I would love to read an in depth explanation of the Python DBAPI. The only thing preventing me from connecting my Python and SQL programs is a lack of understanding of the API, which boils down to ( I think ): 1. How to actually pass SQL code to the database using the API (A good example is all I really need). 2. Why does the API use cursor objects to pass commands to the database? Isn't this inefficient from the SQL point of view? 3. What is the best way to deal with the returned result set? Can I assign it to a list or dictionary? I apologize if any of these questions are overly ignorant, and would be very appreciative for any help. Bill From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 20:35:41 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 20:35:49 2005 Subject: [Tutor] Simple question on creating a filter In-Reply-To: Message-ID: On Fri, 11 Feb 2005, Smith, Jeff wrote: > I'm sorry to both with such a simple question but I've looked in the > normal places and don't see the quick and dirty answer I know must > exist. > > I want to write a simple line selection filter that could be used like: > > filter < file > > I get the following at runtime: > > Traceback (most recent call last): > File "U:\TimeKeeper\mine.py", line 2, in ? > for line in sys.stdin: > IOError: [Errno 9] Bad file descriptor Hi Jeff, Ok there might be a problem with Windows; I see: http://mail.python.org/pipermail/python-list/2002-May/104962.html which sounds really similar to the problem you're seeing. here appears to be a bug in the Windows shell that you may need to work around. The most common workaround I see is wrapping the program with a 'cmd' file. So you can do write a "mine.cmd" program with the following content: ### mine.cmd @python mine.py %* ### After which, you should be able to say: mine < file and things should work again. There's a thread about this issue here: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c5c687b31434a168/e6e6da312e7b18c6#e6e6da312e7b18c6 Best of wishes to you! From zen45800 at zen.co.uk Sat Feb 12 05:21:12 2005 From: zen45800 at zen.co.uk (Lobster) Date: Fri Feb 11 21:21:00 2005 Subject: [Tutor] Idle needles Message-ID: <420D8438.7050208@zen.co.uk> Hi Just started with Idle and Python :-) The tutorials I am accessing with Firefox and there seems to be a conflict in which the Idle editor is trying to (or reported as accessing the Net but does not (according to the literature and warning) More seriously I can not run Idle and Firefox together Not quite sure what to do other than download the whole web sites? Any help or solutions most welcome. Very pleased with what I have learned so far :-) I am using Win98 Python 2.4 and Zone Alarm Ed Jason From bgailer at alum.rpi.edu Fri Feb 11 21:28:34 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 21:23:08 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <6.1.2.0.0.20050211132646.03558d68@mail.mric.net> At 08:52 AM 2/11/2005, Mark Brown wrote: >Hi, >I'm a newbie and was wondering which of these IF conditions is better >structure: if not os.path.exists('filename'): IMHO the above is preferable to the below. It is much more "intuitive". if os.path.exists('filename') == False: Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/5d0a0236/attachment.htm From bgailer at alum.rpi.edu Fri Feb 11 21:34:14 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 21:32:35 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> At 10:39 AM 2/11/2005, Ryan Davis wrote: >I'm starting to make a code-generation suite in python, customized to the >way we ASP.NET at my company, and I'm having some trouble finding a good >way to organize all the code. My take on doing that in Python: Organize things into modules. Especially with an eye to potential reuse. Look at the module index in the docs to see how most of the "standard" modules focus on doing one thing well. Within a module create classes for every conceivable object. Whenever you find yourself writing an if statement ask whether this would be better handled by subclasses. Whenever you find yourself about to write a global statement, consider making the variables properties of a class. Within classes create methods applicable to those classes. Within subclasses create methods applicable to those subclasses. >I keep writing it, but it feels more and more spaghetti-ish every day. > >I'm going to look at the other stuff in site-packages to see if I can >glean any wisdom, and have googled a bit, coming up mostly blank or with >trivial examples. Are there any helpful links or advice anyone has for >building larger systems? > >My background is mostly C#, so I'm used to the ridiculous rigidity of >strongly-typed languages. I have been using python for helper apps for a >few months now, so am pretty familiar with the syntax now, but I don't >know any of the patterns yet. My nefarious goal is to supplant C#/ASP.NET >with Python, but I need to figure out how to make programs clients want to >pay for before I can make any reasonable argument. > >Thanks, >Ryan >---- >Ryan Davis >Director of Programming Services >http://www.acceleration.net/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/cea801ea/attachment.html From project5 at redrival.net Fri Feb 11 20:07:23 2005 From: project5 at redrival.net (Andrei) Date: Fri Feb 11 21:34:05 2005 Subject: [Tutor] Re: Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: Mark Brown wrote: > I'm a newbie and was wondering which of these IF conditions is better > structure: > > 1. if not os.path.exists('filename'): > 2. if os.path.exists('filename') == False: I prefer the "if not" variety. Yours, Andrei From kent37 at tds.net Fri Feb 11 21:38:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 21:38:15 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420CD4A3.6040105@rogers.com> References: <420CD4A3.6040105@rogers.com> Message-ID: <420D17BA.80909@tds.net> Mark Brown wrote: > Hi, > I'm a newbie and was wondering which of these IF conditions is better > structure: > > 1. if not os.path.exists('filename'): I prefer the above. > 2. if os.path.exists('filename') == False: > > They both work so if one preferred over the other? Note that in Python in general, 'not x' and 'x == False' are not equivalent; 'not x' will be true for many more values than just False. For example not 0 not 0.0 not [] not {} are all True. Kent > Thanks > Mark Brown > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Fri Feb 11 22:09:00 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 22:03:24 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420D17BA.80909@tds.net> References: <420CD4A3.6040105@rogers.com> <420D17BA.80909@tds.net> Message-ID: <6.1.2.0.0.20050211140749.0337a438@mail.mric.net> At 01:38 PM 2/11/2005, Kent Johnson wrote: >Mark Brown wrote: >>Hi, >>I'm a newbie and was wondering which of these IF conditions is better >>structure: >> 1. if not os.path.exists('filename'): > >I prefer the above. > >> 2. if os.path.exists('filename') == False: >>They both work so if one preferred over the other? > >Note that in Python in general, 'not x' and 'x == False' are not >equivalent; 'not x' will be true for many more values than just False. For >example >not 0 >not 0.0 >not [] >not {} > >are all True. Oops. 0 and 0.0 do == False. Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Fri Feb 11 22:11:05 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri Feb 11 22:11:02 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <6.1.2.0.0.20050211140749.0337a438@mail.mric.net> References: <420CD4A3.6040105@rogers.com> <420D17BA.80909@tds.net> <6.1.2.0.0.20050211140749.0337a438@mail.mric.net> Message-ID: <420D1F69.2020805@tds.net> Bob Gailer wrote: > At 01:38 PM 2/11/2005, Kent Johnson wrote: >> Note that in Python in general, 'not x' and 'x == False' are not >> equivalent; 'not x' will be true for many more values than just False. >> For example >> not 0 >> not 0.0 >> not [] >> not {} >> >> are all True. > > > Oops. 0 and 0.0 do == False. Uh, right. Thanks! Kent From bgailer at alum.rpi.edu Fri Feb 11 22:06:26 2005 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Feb 11 22:24:06 2005 Subject: [Tutor] Negative IF conditions In-Reply-To: <420D17BA.80909@tds.net> References: <420CD4A3.6040105@rogers.com> <420D17BA.80909@tds.net> Message-ID: <6.1.2.0.0.20050211140608.036243d0@mail.mric.net> At 01:38 PM 2/11/2005, Kent Johnson wrote: >Mark Brown wrote: >>Hi, >>I'm a newbie and was wondering which of these IF conditions is better >>structure: >> 1. if not os.path.exists('filename'): > >I prefer the above. > >> 2. if os.path.exists('filename') == False: >>They both work so if one preferred over the other? > >Note that in Python in general, 'not x' and 'x == False' are not >equivalent; 'not x' will be true for many more values than just False. For >exampl >not 0 >not 0.0 >not [] >not {} > >are all True. > >Kent > >>Thanks >>Mark Brown >> >>------------------------------------------------------------------------ >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor Bob Gailer mailto:bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 22:36:37 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 22:36:41 2005 Subject: [Tutor] Idle needles In-Reply-To: <420D8438.7050208@zen.co.uk> Message-ID: On Fri, 11 Feb 2005, Lobster wrote: > The tutorials I am accessing with Firefox and there seems to be a > conflict in which the Idle editor is trying to (or reported as accessing > the Net but does not (according to the literature and warning) Hello! IDLE does use network connections to talk to itself --- namely, whenever we execute a program in IDLE, it creates a new program process and runs our program in that new process. The IDLE environment talks to that new process through a network socket, so all the communication is in-house, but you might still see something from ZoneAlarm warning about that communication. There's a note about this here: http://www.python.org/2.4/bugs.html It's not really a bug; but it is something unexpected for folks who are using ZoneAlarm. > More seriously I can not run Idle and Firefox together Not quite sure > what to do other than download the whole web sites? What happens if you try running both of them together? Do either of them fail to start up? Firefox and IDLE should not conflict; if you can tell us more details, we'll try to figure out what's going wrong. Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 22:38:47 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 22:38:54 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> Message-ID: > >way we ASP.NET at my company, and I'm having some trouble finding a good > >way to organize all the code. > > My take on doing that in Python: > > Organize things into modules. Especially with an eye to potential reuse. > Look at the module index in the docs to see how most of the "standard" > modules focus on doing one thing well. Hi Ryan, And just making sure; are you using packages? http://www.python.org/doc/tut/node8.html#SECTION008400000000000000000 Most large Python programs that I've seen will first partition their functionality into modules, and if that's not enough, then they further break themselves down into packages. Best of wishes to you! From sigurd at 12move.de Fri Feb 11 22:44:30 2005 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Fri Feb 11 22:47:25 2005 Subject: [Tutor] default argument frustration In-Reply-To: <001e01c51067$bd0478f0$31d78751@xp> (Alan Gauld's message of "Fri, 11 Feb 2005 18:30:17 -0000") References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> <001e01c51067$bd0478f0$31d78751@xp> Message-ID: On 11 Feb 2005, alan.gauld@freenet.co.uk wrote: >> FOR THE LOVE OF MIKE can someone tell me even one reason why this >> isn't a misfeature?!?! > Its the only sane way to implement default arguments. The whole > point of function definitions is that they provide a single concise > interface. The function should return the same result each time > you call it with the same input. The only way to achieve that > is to have the default calculated once. IBTD. With full lexical scope you only need to calculate the default argument in the lexical scope it was defined in. Look at a languale like Common Lisp. Here is first an example in Python: .>>> def mutate_list (L=list()): .... L.append(1) .... return L .... .>>> mutate_list() .[1] .>>> mutate_list() .[1, 1] .>> Now the same in Common Lisp: [17]> (defun dont-mutate (&optional (L (list))) (push 1 L)) DONT-MUTATE [18]> (dont-mutate) (1) [19]> (dont-mutate) (1) As you can see here I defined an optional argument L and as default value a list (the same as in Python). But the difference is: each call of that function evaluates the default argument in the lexical environment it was defined in (`push' is a destructive function). To make that clearer here is a second version where I shadow the definition of `list' (with labels I can shadow the lexical function binding of a symbol (here the symbol `list')). After the labels form is closed the old binding of `list' is restored. [20]> (labels ((list (&optional &rest args) (apply 'list 'shadow args))) (defun dont-mutate-with-shadowed-list (&optional (L (list))) (push 1 L))) DONT-MUTATE-WITH-SHADOWED-LIST [21]> (dont-mutate-with-shadowed-list) (1 SHADOW) [22]> (dont-mutate-with-shadowed-list) (1 SHADOW) [23]> (list 1 2) (1 2) So these functions return the same result each time you call them with the same arguments (even with mutable default arguments). [...] > But I agree that it can be confusing when the default is mutable > but since the only reasonable option would have been to restrict > default values to immutable types I think I prefer the confusion... You see it can be done different (I'm not sure which version is better; both will have their advantages). Karl -- Please do *not* send copies of replies to me. I read the list From reg at plaguerats.net Fri Feb 11 22:52:20 2005 From: reg at plaguerats.net (Matt Dimmic) Date: Fri Feb 11 22:52:40 2005 Subject: [Tutor] References in loops Message-ID: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> In Python, one bug that often bites me is this: (example A) aList = [1,2,3] for i in aList: i += 1 print aList --> [1,2,3] This goes against my intuition, which is that aList == [2,3,4], probably because so much in Python is passed by reference and not by value. Of course I can always use range() or enumerate(): (example B) aList = [1,2,3] for i in range(len(aList)): aList[i] += 1 print aList --> [4,5,6] But example A seems more elegant, if only it did what I wanted it to do. :) So pardon my ignorance if the answer is obvious, but what is the simplest way in Python to get a reference to an element in a list? Is it really Example B? Thanks, Matt (My apologies if this double-posts; I accidentally sent it previously from a non-subscribed address. Moderator, please deny the other copy.) From tegmine at gmail.com Fri Feb 11 22:53:40 2005 From: tegmine at gmail.com (Luis N) Date: Fri Feb 11 22:53:43 2005 Subject: [Tutor] elementtree, lists, and dictionaries Message-ID: <77bfa81a050211135376b1843f@mail.gmail.com> Hi, This code works, but I don't like it much: def authenticateAuthor(author, password): authorxml = 'author.xml' path = os.path.join(xml, authorxml) try: if not os.path.exists(path): authorfile = False else: authorfile = True tree = E.ElementTree(file=path) u = tree.getiterator('user') p = tree.getiterator('password') ul = [] pl = [] for unode in u: ul.append(unode.text) for pnode in p: pl.append(pnode.text) d = {} for i in range(len(ul)): d[ul[i]] = pl[i] if d.has_key(author): if d.get(author) == password: auth = True else: auth = False return auth, authorfile It assumes a great deal, such as that there is no chance that there will be more users then there are passwords, etc. given an xml document format such as: authorname authorpassword I don't like how I'm making two lists and then turning them into a dictionary. It seems unpythonic. Suggestions are appreciated. From dyoo at hkn.eecs.berkeley.edu Fri Feb 11 23:32:49 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 11 23:32:57 2005 Subject: [Tutor] References in loops In-Reply-To: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> Message-ID: On Fri, 11 Feb 2005, Matt Dimmic wrote: > In Python, one bug that often bites me is this: > > (example A) > aList = [1,2,3] > for i in aList: > i += 1 > print aList > --> [1,2,3] > > This goes against my intuition, which is that aList == [2,3,4], probably > because so much in Python is passed by reference and not by value. Hi Matt, Yes. If we "unroll" the loop, we can better see what's going on: ### aList = [1, 2, 3] i = aList[0] i += 1 i = aList[1] i += 1 i = aList[2] i += 1 print aList ### This has the same meaning as Example A, and it should be clearer why the assignment to 'i' has no affect. 'i' is just a regular local variable, just like any other local variable. Assignment is not the same thing as value mutation; it's actually the same issue that we talked about earlier with the default argument thread. *grin* When I see something like: ### x = 42 y = x y = y + 1 ### My visual model of this is that variable names are "arrows" to values: -------------------------------------------------- x -----------> 42 ## x = 42 ---------------------------------------------------- x -----------> 42 ## y = x ^ / y -----------/ ---------------------------------------------------- x -----------> 42 ## y = y + 1 y -----------> 43 ---------------------------------------------------- That being said, we can do something here with a little indirection: ### >>> def box(x): ... """Put a mutable wrapper around the value x.""" ... return [x] ... >>> def unbox(boxedValue): ... """Grab the value in the box.""" ... return boxedValue[0] ... >>> def incr(boxedValue): ... """Increment the value in the box.""" ... boxedValue[0] += 1 ... >>> >>> >>> aList = [box(1), box(2), box(3)] >>> map(unbox, aList) [1, 2, 3] >>> for b in aList: ... incr(b) ... >>> map(unbox, aList) [2, 3, 4] ### This might be overkill, though. *grin* But this shows that, if we really needed to, we could "box" everything in some kind of mutable container. I don't recommend this for normal Python programming, though. > Of course I can always use range() or enumerate(): > > (example B) > aList = [1,2,3] > for i in range(len(aList)): > aList[i] += 1 > print aList > --> [4,5,6] > > But example A seems more elegant, if only it did what I wanted it to do. > :) So pardon my ignorance if the answer is obvious, but what is the > simplest way in Python to get a reference to an element in a list? Is it > really Example B? A variation of Example B, with enumerate(), is probably the most straightforward way to do in-place mutation on the list in Python: ### aList = [1, 2, 3] for i, x in enumerate(aList): aList[i] = x + 1 print aList ### There are languages that magically allow us to do mutation on a list without making it look like list mutation. Perl is one of those languages that adds magic syntactic sugar for doing in-place list stuff. But Python has no special mechanisms for doing this. The main issue that I think people are running against is that, in Python, numeric values are "immutable" --- they can't be changed. When we do things like addition: ### >>> x = 7 >>> x = x + 1 ### we are not changing the value of '7': we're just "re-aiming" or directing 'x' to the new value '8'. If you have more questions, please feel free to ask! From alan.gauld at freenet.co.uk Sat Feb 12 00:50:54 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 00:50:13 2005 Subject: [Tutor] help with refactoring needed -- whichapproach ismorePythonic? References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca><006d01c5106a$ad0bb2d0$31d78751@xp> <420D0532.9050800@tds.net> Message-ID: <00a201c51094$87226670$31d78751@xp> > > - otherwise you get circular references which can cause memory > > leaks by confusing the garbage collector! > > CPython has been able to GC cycles since version 2.0. Yep but it takes a lot longer. The cycle detection sweep only occurs periodically if I remember rightly, and if you are doing a lot of processing you can still get process growth. So as a matter of course I tend to add a __del__ any time I create a list of objects inside another object. Maybe its just my C++ paranoia showing through! :-) Alan G. From cyresse at gmail.com Sat Feb 12 01:05:52 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 12 01:05:55 2005 Subject: [Tutor] Re: Might be a silly question! In-Reply-To: <005901c51069$b1d08350$31d78751@xp> References: <20050211150330.24150.qmail@mail.vianet.ca> <797fe3d405021107383f191157@mail.gmail.com> <20050211154742.30487.qmail@mail.vianet.ca> <005901c51069$b1d08350$31d78751@xp> Message-ID: I suppose, you could do it like this - gamma = 5, and access with gamma[0]. But, there'd be nothing to stop you reassigning gamma. On Fri, 11 Feb 2005 18:44:18 -0000, Alan Gauld wrote: > > I have been reading code written before me (mind you it's C++) and > the > > authors seemed to follow what ever style they wished to that day. > > And that's C++ style, it has no single standard approach... > > > that's the nature of the beast. > > How very true. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From project5 at redrival.net Sat Feb 12 01:38:18 2005 From: project5 at redrival.net (Andrei) Date: Sat Feb 12 01:38:37 2005 Subject: [Tutor] Re: References in loops In-Reply-To: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> References: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> Message-ID: Matt Dimmic wrote: > In Python, one bug that often bites me is this: > > (example A) > aList = [1,2,3] > for i in aList: > i += 1 > print aList > --> [1,2,3] Numbers are immutable, so the element 1 can't change into a 2 inside the list. If 1 was not immutable, e.g. a list you could modify it and then it would be "updated" in the original list too. > This goes against my intuition, which is that aList == [2,3,4], probably > because so much in Python is passed by reference and not by value. Of > course I can always use range() or enumerate(): I tend to use list comprehensions for this: aList = [elem+1 for elem in aList] but it's barely shorter than the explicit loop, so not necessarily an improvement from that point of view. But at least it prevents the bug from biting :). Yours, Andrei From keridee at jayco.net Sat Feb 12 03:13:13 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 12 03:14:03 2005 Subject: [Tutor] References in loops References: Message-ID: <004401c510a8$8246b7f0$105428cf@JSLAPTOP> Of all the odd quirks of python, this is the only thing that has bitten be in the butt. And several, several times. List comprehensions have similar limitations as python lambdas, however, so I guess the only way to execute several expressions on the item in the list would be to pass the item to a function and return the changed item? Thoughts, Jacob > On Fri, 11 Feb 2005, Matt Dimmic wrote: > >> In Python, one bug that often bites me is this: >> >> (example A) >> aList = [1,2,3] >> for i in aList: >> i += 1 >> print aList >> --> [1,2,3] >> >> This goes against my intuition, which is that aList == [2,3,4], probably >> because so much in Python is passed by reference and not by value. > > > Hi Matt, > > > Yes. If we "unroll" the loop, we can better see what's going on: > > ### > aList = [1, 2, 3] > i = aList[0] > i += 1 > i = aList[1] > i += 1 > i = aList[2] > i += 1 > print aList > ### > > This has the same meaning as Example A, and it should be clearer why the > assignment to 'i' has no affect. 'i' is just a regular local variable, > just like any other local variable. > > Assignment is not the same thing as value mutation; it's actually the same > issue that we talked about earlier with the default argument thread. > *grin* > > > > When I see something like: > > ### > x = 42 > y = x > y = y + 1 > ### > > > My visual model of this is that variable names are "arrows" to values: > > -------------------------------------------------- > > x -----------> 42 ## x = 42 > > ---------------------------------------------------- > > x -----------> 42 ## y = x > ^ > / > y -----------/ > > ---------------------------------------------------- > > x -----------> 42 ## y = y + 1 > > y -----------> 43 > > ---------------------------------------------------- > > > > That being said, we can do something here with a little indirection: > > ### >>>> def box(x): > ... """Put a mutable wrapper around the value x.""" > ... return [x] > ... >>>> def unbox(boxedValue): > ... """Grab the value in the box.""" > ... return boxedValue[0] > ... >>>> def incr(boxedValue): > ... """Increment the value in the box.""" > ... boxedValue[0] += 1 > ... >>>> >>>> >>>> aList = [box(1), box(2), box(3)] >>>> map(unbox, aList) > [1, 2, 3] >>>> for b in aList: > ... incr(b) > ... >>>> map(unbox, aList) > [2, 3, 4] > ### > > This might be overkill, though. *grin* > > But this shows that, if we really needed to, we could "box" everything in > some kind of mutable container. I don't recommend this for normal Python > programming, though. > > > >> Of course I can always use range() or enumerate(): >> >> (example B) >> aList = [1,2,3] >> for i in range(len(aList)): >> aList[i] += 1 >> print aList >> --> [4,5,6] >> >> But example A seems more elegant, if only it did what I wanted it to do. >> :) So pardon my ignorance if the answer is obvious, but what is the >> simplest way in Python to get a reference to an element in a list? Is it >> really Example B? > > A variation of Example B, with enumerate(), is probably the most > straightforward way to do in-place mutation on the list in Python: > > ### > aList = [1, 2, 3] > for i, x in enumerate(aList): > aList[i] = x + 1 > print aList > ### > > There are languages that magically allow us to do mutation on a list > without making it look like list mutation. Perl is one of those languages > that adds magic syntactic sugar for doing in-place list stuff. But Python > has no special mechanisms for doing this. > > > The main issue that I think people are running against is that, in Python, > numeric values are "immutable" --- they can't be changed. When we do > things like addition: > > ### >>>> x = 7 >>>> x = x + 1 > ### > > we are not changing the value of '7': we're just "re-aiming" or directing > 'x' to the new value '8'. > > > If you have more questions, please feel free to ask! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From nbbalane at gmail.com Sat Feb 12 03:17:01 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sat Feb 12 03:17:04 2005 Subject: [Tutor] What does this mean Message-ID: <2cad2090050211181719a6834e@mail.gmail.com> what does (*args, **kwargs) mean??? i'm sort of a bit confused... thanks. From zanesdad at bellsouth.net Sat Feb 12 03:39:46 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Sat Feb 12 03:38:43 2005 Subject: [Tutor] What does this mean In-Reply-To: <2cad2090050211181719a6834e@mail.gmail.com> References: <2cad2090050211181719a6834e@mail.gmail.com> Message-ID: <420D6C72.4030404@bellsouth.net> jrlen balane wrote: >what does (*args, **kwargs) mean??? i'm sort of a bit confused... thanks. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > *args is notation for list of arguments. **kwargs is notation for keyword arguments. Here is an example: ####################### In [1]: def foo(bar, *args, **kwargs): ...: print "bar", bar ...: print "args", args ...: print "kwargs", kwargs ...: In [2]: foo('1') bar 1 args () kwargs {} In [3]: foo('1', 1, 2, 3) bar 1 args (1, 2, 3) kwargs {} In [4]: foo('1', 1, 2, 3, bam=1, baz=2, boo=3) bar 1 args (1, 2, 3) kwargs {'bam': 1, 'baz': 2, 'boo': 3} ####################### In the definition (at prompt [1]), I only stated 3 arguments to pass in: bar, args, and kwargs. At prompt [2], I pass in a "1" string as my only argument, which gets assigned to "bar". At prompt [3], I pass in "1", 1, 2, 3. "1" gets assigned to foo as in the previous example. (1,2,3) gets assigned to args. The *args notations says, "Assign any following arguments to the args variable." At prompt [4], I pass in the same thing as at [3], but pass in keyword arguments (bam=1, baz=2, boo=3). Everything gets assigned as it did at [3] except kwargs is a dictionary with keys 'bam', 'baz', and 'boo' with respective values 1,2,3. The **kwargs notations says, "Assign any subsequent keyword arguments to kwargs." NOTE - you don't have to use *args and **kwargs. You just have to use the * and **. Jeremy Jones From kent37 at tds.net Sat Feb 12 04:28:55 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 04:28:59 2005 Subject: [Tutor] elementtree, lists, and dictionaries In-Reply-To: <77bfa81a050211135376b1843f@mail.gmail.com> References: <77bfa81a050211135376b1843f@mail.gmail.com> Message-ID: <420D77F7.6090609@tds.net> If you iterate over the author nodes you can check the user name and password of each in turn. Not tested code! def authenticateAuthor(author, password): authorxml = 'author.xml' path = os.path.join(xml, authorxml) if not os.path.exists(path): return False, False else: tree = E.ElementTree(file=path) for authorNode in tree.getiterator('author'): user = authorNode.find('user').text pass = authorNode.find('password').text if author == user: if password == pass: return True, True else: return False, True return False, True Luis N wrote: > Hi, > > This code works, but I don't like it much: > > def authenticateAuthor(author, password): > authorxml = 'author.xml' > path = os.path.join(xml, authorxml) > try: if not os.path.exists(path): > authorfile = False > else: > authorfile = True > tree = E.ElementTree(file=path) > u = tree.getiterator('user') > p = tree.getiterator('password') Here you could say d = dict( (unode.text, pnode.text) for unode, pnode in zip(u, p)) > ul = [] > pl = [] > for unode in u: > ul.append(unode.text) > for pnode in p: > pl.append(pnode.text) > d = {} > for i in range(len(ul)): > d[ul[i]] = pl[i] > if d.has_key(author): > if d.get(author) == password: > auth = True > else: > auth = False or try: if d[author] == password: auth = True except KeyError: auth = False or, if you are sure password will not be None, just skip the has_key(): if d.get(author) == password: ... (I hate using has_key() followed by a get()... > return auth, authorfile > > It assumes a great deal, such as that there is no chance that there > will be more users then there are passwords, etc. given an xml > document format such as: > > > > authorname > authorpassword > > > > I don't like how I'm making two lists and then turning them into a > dictionary. It seems unpythonic. > > Suggestions are appreciated. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From zen45800 at zen.co.uk Sat Feb 12 13:29:48 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 05:29:34 2005 Subject: [Tutor] Idle needles In-Reply-To: References: Message-ID: <420DF6BC.1040701@zen.co.uk> Danny Yoo wrote: >>More seriously I can not run Idle and Firefox together Not quite sure >>what to do other than download the whole web sites? thanks for the info Danny :-) >What happens if you try running both of them together? Do either of them >fail to start up? > >Firefox and IDLE should not conflict; if you can tell us more details, >we'll try to figure out what's going wrong. > > >Best of wishes to you! They load up. This is the error message I get from IDLE when trying to compile the program ========= Idols subprocess didn't make connection Either Idle can't start or personal firewall is blocking the connection ========= I am allowing the connection from zonealarm. Even tried allowing IDLE to be a server. Would I be better off using the windows only editor (do not want to as I will also be working in Linux)? I tried from a fresh boot and everything seemed OK - then after looking at some email in thunderbird - tried to compile a new program and got the above message. So maybe it is time loop based? Appreciate the help :-) Ed Jason From zen45800 at zen.co.uk Sat Feb 12 13:40:01 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 05:39:46 2005 Subject: [Tutor] Idle needles In-Reply-To: References: Message-ID: <420DF921.1010605@zen.co.uk> Danny Yoo wrote: More Info ========= Idols subprocess didn't make connection Either Idle can't start or personal firewall is blocking the connection ========= Now I am getting the added message that the "socket connection is refused" (recently updated to the latest Zone Alarm) Ed Jason From javier at ruere.com.ar Sat Feb 12 05:55:06 2005 From: javier at ruere.com.ar (Javier Ruere) Date: Sat Feb 12 05:51:56 2005 Subject: [Tutor] Re: Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: Ryan Davis wrote: > I'm starting to make a code-generation suite in python, customized to > the way we ASP.NET at my company, and I'm having some trouble finding a > good way to organize all the code. I keep writing it, but it feels more > and more spaghetti-ish every day. > > I'm going to look at the other stuff in site-packages to see if I can > glean any wisdom, and have googled a bit, coming up mostly blank or with > trivial examples. Are there any helpful links or advice anyone has for > building larger systems? > > My background is mostly C#, so I'm used to the ridiculous rigidity of > strongly-typed languages. I have been using python for helper apps for a > few months now, so am pretty familiar with the syntax now, but I don't > know any of the patterns yet. My nefarious goal is to supplant > C#/ASP.NET with Python, but I need to figure out how to make programs > clients want to pay for before I can make any reasonable argument. I have worked with C# + ASP.NET and liked it very much. It felt more similar to Python than Java; and ASP.NET rules! :) WRT your original question: Organize the code as you would in a C# project unless it feels unnatural. Sorry about that last condition but it's the best I can do[1]. :) Get Bicycle Repair Man[2] or another refactoring browser and hack away! Javier [1] Some usefull links: http://dirtsimple.org/2005/01/courage-to-do-things-simply.html http://dirtsimple.org/2004/12/python-is-not-java.html http://dirtsimple.org/2004/12/java-is-not-python-either.html [2] http://bicyclerepair.sourceforge.net/ From nbbalane at gmail.com Sat Feb 12 06:36:18 2005 From: nbbalane at gmail.com (jrlen balane) Date: Sat Feb 12 06:36:23 2005 Subject: [Tutor] what is wrong with this? Message-ID: <2cad209005021121365aee64a5@mail.gmail.com> this code is for a MDIChildFrame, It has a MDIParentFrame and when I run the MDIPrentFrame, there seems to be no problem, but when I attempt to edit the MDIChildFrame using the designer mode in BOA (i'm using BOA by the way), an error occurs that says: TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given) please help. here is the code: from wxPython.wx import * from wxPython.grid import * from wxPython.lib.mixins.grid import wxGridAutoEditMixin def create(parent): return wxMDIChildFrame1(parent) [wxID_WXMDICHILDFRAME1, wxID_WXMDICHILDFRAME1GRID1, ] = map(lambda _init_ctrls: wxNewId(), range(2)) class wxMDIChildFrame1(wxMDIChildFrame): def _init_ctrls(self, prnt): # generated method, don't edit wxMDIChildFrame.__init__(self, id=wxID_WXMDICHILDFRAME1, name='WXMDICHILDFRAME1', parent=prnt, pos=wxPoint(70, 147), size=wxSize(748, 331), style=wxDEFAULT_FRAME_STYLE, title='Table') self.SetClientSize(wxSize(740, 297)) self.grid1 = wxGrid(id=wxID_WXMDICHILDFRAME1GRID1, name='grid1', parent=self, pos=wxPoint(0, 0), size=wxSize(740, 297), style=0) self.grid1.CreateGrid(100,6) self.grid1.SetColLabelValue(0, "Time") self.grid1.SetColLabelValue(1, "Irradiance") self.grid1.SetColLabelValue(2, "Module Temperature") self.grid1.SetColLabelValue(3, "Ambient Temperature") self.grid1.SetColLabelValue(4, "Voltage") self.grid1.SetColLabelValue(5, "Current") self.grid1.SetColSize(2, 125) self.grid1.SetColSize(3, 127) self.grid1.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) def __init__(self, parent): self._init_ctrls(parent) From dyoo at hkn.eecs.berkeley.edu Sat Feb 12 08:03:31 2005 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 12 08:03:37 2005 Subject: [Tutor] Idle needles In-Reply-To: <420DF921.1010605@zen.co.uk> Message-ID: On Sat, 12 Feb 2005, Lobster wrote: > Idols subprocess didn't make connection Either Idle can't start or > personal firewall is blocking the connection ========= > > Now I am getting the added message that the "socket connection is > refused" (recently updated to the latest Zone Alarm) Hi Ed, That's further evidence that suggests that Zone Alarm is fighting IDLE. Let me see... here's a section of the IDLE documentation README that talks about this issue: """ IDLE displays a new message upon startup: some "personal firewall" kinds of programs (for example, ZoneAlarm) open a dialog of their own when any program opens a socket. IDLE does use sockets, talking on the computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. So, if you get such a dialog when opening IDLE, asking whether to let pythonw.exe talk to address 127.0.0.1, say yes, and rest assured no communication external to your machine is taking place. If you don't allow it, IDLE won't be able to start. """ Just to nail this issue down: try turning ZoneAlarm off, just for a moment, and then start up IDLE. (You can always turn ZoneAlarm back on after this experiment.) If you don't see any problems with IDLE, then it's almost certainly a ZoneAlarm vs. IDLE confrontation, and we can focus on that. Good luck to you! From ejp at zomething.com Sat Feb 12 08:31:45 2005 From: ejp at zomething.com (EJP) Date: Sat Feb 12 08:31:54 2005 Subject: [Tutor] Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <20050211233145.2130185092.ejp@zomething.com> "Ryan Davis" ryan@acceleration.net wrote My background is mostly C#, so I'm used to the ridiculous rigidity of strongly-typed languages. I have been using python for helper apps for a few months now, so am pretty familiar with the syntax now, but I don't know any of the patterns yet. My nefarious goal is to supplant C#/ASP.NET with Python, but I need to figure out how to make programs clients want to pay for before I can make any reasonable argument. without trying to make this one of those classic threads of great, do you feel you could develop fairly complex applications faster in Python than in C#/ASP.NET? It's a rhetorical question (but I'm interested in your answer as a single data point) Speed to market and hours/dollars of programming might resonate with some of your customers. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20050211/b534cb94/attachment-0001.html From zen45800 at zen.co.uk Sat Feb 12 16:34:03 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 08:33:48 2005 Subject: [Tutor] Idle needles In-Reply-To: References: Message-ID: <420E21EB.4000908@zen.co.uk> Danny Yoo wrote: >On Sat, 12 Feb 2005, Lobster wrote: > > > >>Idols subprocess didn't make connection Either Idle can't start or >>personal firewall is blocking the connection ========= >> >>Now I am getting the added message that the "socket connection is >>refused" (recently updated to the latest Zone Alarm) >> >> > >Hi Ed, > >That's further evidence that suggests that Zone Alarm is fighting IDLE. > > >Let me see... here's a section of the IDLE documentation README that talks >about this issue: > >""" >IDLE displays a new message upon startup: some "personal firewall" > kinds of programs (for example, ZoneAlarm) open a dialog of their > own when any program opens a socket. IDLE does use sockets, talking > on the computer's internal loopback interface. This connection is not > visible on any external interface and no data is sent to or received > from the Internet. So, if you get such a dialog when opening IDLE, > asking whether to let pythonw.exe talk to address 127.0.0.1, say yes, > and rest assured no communication external to your machine is taking > place. If you don't allow it, IDLE won't be able to start. >""" > > > Yes I did read that Danny - many thanks >Just to nail this issue down: try turning ZoneAlarm off, just for a >moment, and then start up IDLE. (You can always turn ZoneAlarm back on >after this experiment.) If you don't see any problems with IDLE, then >it's almost certainly a ZoneAlarm vs. IDLE confrontation, and we can focus >on that. > >Good luck to you! > Turned off Zone Alarm and closed down IDLE on opening IDLE - I got the socket error message and the other error message - so not zone alarm (it seems) - closing down IDLE and pressing ctrl alt and del I notice that 3 copies of pythonw are in memory I closed these down and IDLE is working again What I am going to do next is download the excellent Byte of Python tutorial and work offline with firefox and see what happens - any other ideas welcome (the only other thing I have different in IDLE is I store my Python docs in my docs rather than the default - probably irrelevant but . . .) Thank you very much for helping with this - it is holding me up and I am rearing to "go with the snake. . ." :-) Ed Jason (aka Dragon Shrimp - aka Lobster) PS - had a look at Crimson Editor and PSpad - very good but not quite for me I rather like IDLE - it is specific - focussed From alan.gauld at freenet.co.uk Sat Feb 12 09:41:22 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 09:45:32 2005 Subject: [Tutor] default argument frustration References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp><420C670B.4070209@po-box.mcgill.ca><001e01c51067$bd0478f0$31d78751@xp> Message-ID: <00ef01c510de$a203f680$31d78751@xp> > > interface. The function should return the same result each time > > you call it with the same input. The only way to achieve that > > is to have the default calculated once. > > IBTD. > With full lexical scope you only need to calculate the default argument > in the lexical scope it was defined in. Look at a languale like Common > Lisp. Sorry, you are quite right. I meant its the only sane way to do it given the way Python works. Lisp and others implement closures and defered evaluation quite nicely, but I don't think it would be easy to build that into Python. Although it might be easier now with nested functions etc... Alan G. From alan.gauld at freenet.co.uk Sat Feb 12 09:52:28 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 09:52:37 2005 Subject: [Tutor] Larger program organization References: <20050211173944.07AAC1E4008@bag.python.org> <20050211233145.2130185092.ejp@zomething.com> Message-ID: <012401c510e0$2ec72910$31d78751@xp> > without trying to make this one of those classic threads of great, > do you feel you could develop fairly complex applications faster > in Python than in C#/ASP.NET? It's a rhetorical question > (but I'm interested in your answer as a single data point) To be honest it wouldn't make a great deal of difference. For a complex application (by which I assume you mean large as well as being technically difficult) you spend most of your time thinking not physically coding so the language becomes less significant. On a typical "big" project the actual coding time is likely to be less than 10% of the total time so even if Python were twice as fast you only save 5% overall. Python may improve time to fix however since it will be easier to read later and therefore easier to debug and spot errors etc. But on big projects analysis, design and testing will be the big contributers, actually typing in the code is a trivial element. Alan G. From sandip at lug-delhi.org Sat Feb 12 10:27:21 2005 From: sandip at lug-delhi.org (Sandip Bhattacharya) Date: Sat Feb 12 10:43:28 2005 Subject: [Tutor] Re: Data storage, SQL? References: Message-ID: On Fri, 11 Feb 2005 20:09:10 +1300, Liam Clarke wrote: > Hi, > > I'm looking to create a prog that will store disparate bits of info > all linked together, i.e. address details for a person, transaction > records, specific themes, and the ability to search by certain > criteria, so I'm pretty sure I want a database. > > Can anyone recommend a useful database library for Python that's not > too complex? > Also, I keep hearing about SQL, would this be the best way to go? I > don't know much about databases. You can take a look at sqlite (http://www.sqlite.org/). It doesn't require a client server setup, and offers you the same sql syntax for manipulating data on it. Some amazing facts about this from the website: [...] SQLite is a small C library that implements a self-contained, embeddable, zero-configuration SQL database engine. Features include: * Transactions are atomic, consistent, isolated, and durable (ACID) even after system crashes and power failures. * Zero-configuration - no setup or administration needed. * Implements most of SQL92. * A complete database is stored in a single disk file. * Database files can be freely shared between machines with different byte orders. * Supports databases up to 2 terabytes (2^41 bytes) in size. * Sizes of strings and BLOBs limited only by available memory. * Small code footprint: less than 30K lines of C code, less than 250KB code space (gcc on i486) * Faster than popular client/server database engines for most common operations. * Simple, easy to use API. * Well-commented source code with over 95% test coverage. * Self-contained: no external dependencies. * Sources are in the public domain. Use for any purpose. The SQLite distribution comes with a standalone command-line access program (sqlite) that can be used to administer an SQLite database and which serves as an example of how to use the SQLite library. [...] - Sandip -- Sandip Bhattacharya * Puroga Technologies * sandip@puroga.com Work: http://www.puroga.com * Home/Blog: http://www.sandipb.net/blog PGP/GPG Signature: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3 From bvande at po-box.mcgill.ca Sat Feb 12 10:56:37 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 10:59:07 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <420CDE7A.3010408@tds.net> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> Message-ID: <420DD2D5.2060708@po-box.mcgill.ca> Kent Johnson said unto the world upon 2005-02-11 11:34: > Brian van den Broek wrote: > >> Alan Gauld said unto the world upon 2005-02-10 02:58: >> >>> Pseudo code: >>> class Body: >>> def __init__(self,content): >>> self.contents = contents >>> self.nodes = [] >>> >>> def parse(self): >>> for line in self.contents: >>> if line == NodeStartTag: >>> node = Node() >>> if line == NodeEndTag: >>> self.nodes.append(node) >>> node.append(line) >>> >>> class Node: >>> def __init__(self,lines=[]): >>> self.lines = lines >>> def append(self,item): >>> self.lines.append(item) >>> def parse(self): >>> # your parsing method here. >> >> >> >> Hi all, >> >> YAQ (Yet Another Question): >> >> Following the general pattern, I end up with a Body object which has >> an attribute .nodes that consists of a list of Node objects. >> >> So, something like: >> >> My Example Body >> Node List >> Node the first >> Node the second >> >> Is there any way to make methods of the Node class access attributes >> of `parents' of instances? I would like a Node instance such as Node >> the first above to be aware just what it is a node of and what its >> siblings are. > > > You have to tell it the parent. ("Explicit is better than implicit.") > For example you could pass a reference to Body to the Node in the > constructor: > > def parse(self): > for line in self.contents: > if line == NodeStartTag: > node = Node(self) # HERE > if line == NodeEndTag: > self.nodes.append(node) > node.append(line) > > In general I think this is a bad design. I try to avoid telling > components about their parents in any kind of containment hierarchy. If > the component knows about its parent, then the component can't be reused > in a different context and it can't be tested without creating the > expected context. > > Is there another way you could accomplish what you want? > > Kent Hi, thanks to everyone for responding. It hadn't occurred to me I could pass self to a class instantiation. So, that solves my issue given my original design intent: thanks. As for Kent's question: I may have a better way now. I'd appreciate help deciding. So, if I may, I'll say a bit more about the problem domain. I've made the description as short as I know how. The file format I am working with is from a `folding notebook' style of application ( if anyone is interested). It's a 2-pane editor/outliner. There is a tree of nodes with each with a (not necessarily unique) title, a unique id number, other metadata and an associated article (in plain text, html, or RTF [ugh!]). The file format also defines a header for the entire file. I have a class TP_file, which, when instantiated, creates an Head object and, for each node, a Node object. The program supports hyperlinks in the article text, both to other nodes (by unique id) and to external objects. Before posting this most recent question, I'd planed for the Node class to have a method that would scan the node's article, looking for text strings that match any node title and linkifying them. (I already know how to deal with already linkified instances of the string and cases where one string is the title of multiple nodes.) Since this method needs to know the titles of all Node objects, I thought I needed to make each Node aware of its TP_file object to fetch its nodes. (Hence my most recent question.) And, since it alters the article text of a Node, I thought it needed to be a method of the Node class. But, while reflecting on Kent's question and thinking of how to describe my problem domain, I think I have a better idea now :-) It still seems to me that the actual updating of the article should be a Node method (it is the Node object's article that is being updated, after all). Call it node_linkify. The new thought is to create two new methods for the TP_file class: - One to build a dictionary with Node titles as keys and a list of the corresponding unique ids as values. - Another to pass that list into a the node_linkify Node method, once for each Node object of the TP_file. Does this seem like a reasonable approach given my description of the problem? Thanks for the continued help -- it is most appreciated. I might just become an OOP programmer yet! ;-) Best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Feb 12 10:10:45 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 10:59:20 2005 Subject: [Tutor] Idle needles In-Reply-To: <420E21EB.4000908@zen.co.uk> References: <420E21EB.4000908@zen.co.uk> Message-ID: <420DC815.4000900@po-box.mcgill.ca> Lobster said unto the world upon 2005-02-12 10:34: > Danny Yoo wrote: > >> On Sat, 12 Feb 2005, Lobster wrote: > >> Just to nail this issue down: try turning ZoneAlarm off, just for a >> moment, and then start up IDLE. (You can always turn ZoneAlarm back on >> after this experiment.) If you don't see any problems with IDLE, then >> it's almost certainly a ZoneAlarm vs. IDLE confrontation, and we can >> focus >> on that. >> >> Good luck to you! >> > > Turned off Zone Alarm > and closed down IDLE > on opening IDLE - I got the socket error message > and the other error message > - so not zone alarm (it seems) > > - closing down IDLE and pressing ctrl alt and del > I notice that 3 copies of pythonw are in memory > > I closed these down and IDLE is working again Hi, for what it's worth, I've never had issues with Firefox and IDLE when running Zone Alarm. (Currently running ZoneAlarm version:5.5.062.004) But the multiple copies of pythonw seems key, and also the sort of thing that better Python minds than most seem to accept they have to live with too: > :-) > > Ed Jason (aka Dragon Shrimp - aka Lobster) > > PS - had a look at Crimson Editor and PSpad - very good but not quite > for me > I rather like IDLE - it is specific - focussed I've been pretty happy using IDLE supplemented by SciTe when wanting a better editor than that provided by IDLE. Best, Brian vdB From cyresse at gmail.com Sat Feb 12 11:58:30 2005 From: cyresse at gmail.com (Liam Clarke) Date: Sat Feb 12 11:58:32 2005 Subject: [Tutor] what is wrong with this? In-Reply-To: <2cad209005021121365aee64a5@mail.gmail.com> References: <2cad209005021121365aee64a5@mail.gmail.com> Message-ID: Can you post the whole stack trace? On Sat, 12 Feb 2005 13:36:18 +0800, jrlen balane wrote: > this code is for a MDIChildFrame, It has a MDIParentFrame and when I > run the MDIPrentFrame, there seems to be no problem, but when I > attempt to edit the MDIChildFrame using the designer mode in BOA (i'm > using BOA by the way), an error occurs that says: > > TypeError: wxGrid_CreateGrid() takes at least 3 arguments (2 given) > > please help. here is the code: > > from wxPython.wx import * > from wxPython.grid import * > from wxPython.lib.mixins.grid import wxGridAutoEditMixin > > def create(parent): > return wxMDIChildFrame1(parent) > > [wxID_WXMDICHILDFRAME1, wxID_WXMDICHILDFRAME1GRID1, > ] = map(lambda _init_ctrls: wxNewId(), range(2)) > > class wxMDIChildFrame1(wxMDIChildFrame): > def _init_ctrls(self, prnt): > # generated method, don't edit > wxMDIChildFrame.__init__(self, id=wxID_WXMDICHILDFRAME1, > name='WXMDICHILDFRAME1', parent=prnt, pos=wxPoint(70, 147), > size=wxSize(748, 331), style=wxDEFAULT_FRAME_STYLE, > title='Table') > self.SetClientSize(wxSize(740, 297)) > > self.grid1 = wxGrid(id=wxID_WXMDICHILDFRAME1GRID1, name='grid1', > parent=self, pos=wxPoint(0, 0), size=wxSize(740, 297), style=0) > > self.grid1.CreateGrid(100,6) > self.grid1.SetColLabelValue(0, "Time") > self.grid1.SetColLabelValue(1, "Irradiance") > self.grid1.SetColLabelValue(2, "Module Temperature") > self.grid1.SetColLabelValue(3, "Ambient Temperature") > self.grid1.SetColLabelValue(4, "Voltage") > self.grid1.SetColLabelValue(5, "Current") > > self.grid1.SetColSize(2, 125) > self.grid1.SetColSize(3, 127) > self.grid1.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) > > def __init__(self, parent): > self._init_ctrls(parent) > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From zen45800 at zen.co.uk Sat Feb 12 21:18:20 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 13:18:05 2005 Subject: [Tutor] Idle + Firefox solution - hopefully In-Reply-To: <20050212110109.06ED01E403F@bag.python.org> References: <20050212110109.06ED01E403F@bag.python.org> Message-ID: <420E648C.1000100@zen.co.uk> >> - closing down IDLE and pressing ctrl alt and del >> I notice that 3 copies of pythonw are in memory >> >> I closed these down and IDLE is working again > > >Hi, > >for what it's worth, I've never had issues with Firefox and IDLE when >running Zone Alarm. (Currently running ZoneAlarm version:5.5.062.004) > >But the multiple copies of pythonw seems key, and also the sort of >thing that better Python minds than most seem to accept they have to >live with too: > > > ======= Thanks Brian and Danny Yep - I found closing down the extra versions was a solution I also ran spybot and found a browser hijacker (just returned from a month in Linux without such hindrances) and it may be somehow related to that - the problem SEEMS to have gone . . . ======= I've been pretty happy using IDLE supplemented by SciTe when wanting a better editor than that provided by IDLE. Best, Brian vdB ====== Will have a look at SciTe thanks for your help - appreciate it . . . Ed Jason ======= From kent37 at tds.net Sat Feb 12 13:50:48 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 13:50:52 2005 Subject: [Tutor] help with refactoring needed -- which approach is more Pythonic? In-Reply-To: <420DD2D5.2060708@po-box.mcgill.ca> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> <420DD2D5.2060708@po-box.mcgill.ca> Message-ID: <420DFBA8.6020802@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 2005-02-11 11:34: >> In general I think this is a bad design. I try to avoid telling >> components about their parents in any kind of containment hierarchy. >> If the component knows about its parent, then the component can't be >> reused in a different context and it can't be tested without creating >> the expected context. >> >> Is there another way you could accomplish what you want? >> >> Kent > > > Hi, > > thanks to everyone for responding. It hadn't occurred to me I could pass > self to a class instantiation. So, that solves my issue given my > original design intent: thanks. > > As for Kent's question: I may have a better way now. I'd appreciate help > deciding. So, if I may, I'll say a bit more about the problem domain. > I've made the description as short as I know how. > > The file format I am working with is from a `folding notebook' style of > application ( if anyone is interested). It's a 2-pane > editor/outliner. There is a tree of nodes with each with a (not > necessarily unique) title, a unique id number, other metadata and an > associated article (in plain text, html, or RTF [ugh!]). The file format > also defines a header for the entire file. > > I have a class TP_file, which, when instantiated, creates an Head object > and, for each node, a Node object. > > The program supports hyperlinks in the article text, both to other nodes > (by unique id) and to external objects. Before posting this most recent > question, I'd planed for the Node class to have a method that would scan > the node's article, looking for text strings that match any node title > and linkifying them. (I already know how to deal with already linkified > instances of the string and cases where one string is the title of > multiple nodes.) Since this method needs to know the titles of all Node > objects, I thought I needed to make each Node aware of its TP_file > object to fetch its nodes. (Hence my most recent question.) And, since > it alters the article text of a Node, I thought it needed to be a method > of the Node class. > > But, while reflecting on Kent's question and thinking of how to describe > my problem domain, I think I have a better idea now :-) > > It still seems to me that the actual updating of the article should be a > Node method (it is the Node object's article that is being updated, > after all). Call it node_linkify. The new thought is to create two new > methods for the TP_file class: > > - One to build a dictionary with Node titles as keys and > a list of the corresponding unique ids as values. > > - Another to pass that list into a the node_linkify Node method, > once for each Node object of the TP_file. > > Does this seem like a reasonable approach given my description of the > problem? Yes. This is the kind of solution I look for - instead of having the Node class look 'outside' itself to find what it needs - and therefore have the Node class dependent on a particular context - have something poke the Node from the outside and give it the information it needs to do its job. Do you see how this makes the Node more self-contained? For example you could write a unit test for node_linkify() that would just have to create a Node with some text and a helper dictionary. With the old design you would have to create several nodes and connect them in a Body. It may not seem like a big deal, but in a larger program these cross-dependencies grow and knit the whole thing into an inseparable whole. I worked on a program where the data model was dependent on the GUI implementation classes (*very* bad idea). So to reuse the data model (to be able to access the data in a different program) you had to include the GUI classes! A couple of notes about the general rule, though: - In tree-structured data I often need the node objects to know about their parent. Navigating up the tree is often handy. - In a GUI it can be challenging to figure out how to avoid telling the GUI classes about each other. For example if a button in one panel has to influence another panel. Usually I find a way but it gets a bit convoluted sometimes. > Thanks for the continued help -- it is most appreciated. I might just > become an OOP programmer yet! ;-) You're on your way! Kent > > Best to all, > > Brian vdB > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Feb 12 13:51:42 2005 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Feb 12 13:51:43 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? References: <420A8938.5040604@po-box.mcgill.ca><07fe01c50f46$60d84240$68b78851@xp><420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> <420DD2D5.2060708@po-box.mcgill.ca> Message-ID: <013c01c51101$9a276640$31d78751@xp> > It still seems to me that the actual updating of the article should be > a Node method (it is the Node object's article that is being updated, > after all). Yes, the owner of the data should update it. > Call it node_linkify. The new thought is to create two new > methods for the TP_file class: > > - One to build a dictionary with Node titles as keys and > a list of the corresponding unique ids as values. Which saves searching the node list each time, good idea. This dictionary would of course be part of the Head or Body object which manages the Nodes? > - Another to pass that list into a the node_linkify Node method, > once for each Node object of the TP_file. Since the node knows its own ID and shouldn't know about the other nodes I wonder if it would be better for the Body/Head object to pass only what the node needs to create the links. Or do the links go to *all* the other related nodes? In which case the dictionary entry is fine. Alan G. From kent37 at tds.net Sat Feb 12 13:55:31 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 13:55:36 2005 Subject: [Tutor] Idle needles In-Reply-To: <420DC815.4000900@po-box.mcgill.ca> References: <420E21EB.4000908@zen.co.uk> <420DC815.4000900@po-box.mcgill.ca> Message-ID: <420DFCC3.4070801@tds.net> Brian van den Broek wrote: > But the multiple copies of pythonw seems key, and also the sort of thing > that better Python minds than most seem to accept they have to live with > too: Make sure you read the next message in the thread which gives a possible cause of the problem and a patch that might help. http://mail.python.org/pipermail/edu-sig/2005-January/004366.html Kent From exogen at gmail.com Sat Feb 12 14:07:05 2005 From: exogen at gmail.com (Brian Beck) Date: Sat Feb 12 14:22:35 2005 Subject: [Tutor] Re: References in loops In-Reply-To: References: <000a01c51083$f9ef0ac0$8eaaec84@CuriousGeorge> Message-ID: Andrei wrote: > Numbers are immutable, so the element 1 can't change into a 2 inside the > list. If 1 was not immutable, e.g. a list you could modify it and then > it would be "updated" in the original list too. It doesn't have anything to do with mutability, only the scope of i. Consider a list of lists (lists are mutable): py> l = [[1], [2], [3]] py> for i in l: i = [0] py> print l [[1], [2], [3]] Notice that even though each i (list) is mutable, rebinding the name i in the loop has no effect on the list. > I tend to use list comprehensions for this: > > aList = [elem+1 for elem in aList] This is probably the best solution, provided that the operation you want to perform on each element is simple enough to fit in an expression. Even then, just put the operation into a function. -- Brian Beck Adventurer From mark.kels at gmail.com Sat Feb 12 15:12:56 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 12 15:13:00 2005 Subject: [Tutor] Downloading from http Message-ID: Hi list. How can I download a file from an HTTP server ? I checked the documentation but couldn't find what I need. Thanks! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From keridee at jayco.net Sat Feb 12 15:25:10 2005 From: keridee at jayco.net (Jacob S.) Date: Sat Feb 12 15:24:53 2005 Subject: [Tutor] Downloading from http References: Message-ID: <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> urllib or urllib2 or maybe httplib maybe? urlopen( url[, data]) Open the URL url, which can be either a string or a Request object. data should be a string, which specifies additional data to send to the server. In HTTP requests, which are the only ones that support data, it should be a buffer in the format of application/x-www-form-urlencoded, for example one returned from urllib.urlencode(). This function returns a file-like object with two additional methods: a.. geturl() -- return the URL of the resource retrieved b.. info() -- return the meta-information of the page, as a dictionary-like object Raises URLError on errors. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). This is taken from the docs on urllib2. I think that's what you want, right? The tutorial or whatever, called "Dive into python", goes into accessing web pages a little more in depth than the docs do, I think. You can google for it, I believe. HTH, Jacob > Hi list. > > How can I download a file from an HTTP server ? > I checked the documentation but couldn't find what I need. > > Thanks! > -- > 1. The day Microsoft makes something that doesn't suck is probably the > day they start making vacuum cleaners. > 2. Unix is user friendly - it's just picky about it's friends. > 3. Documentation is like sex: when it is good, it is very, very good. > And when it is bad, it is better than nothing. - Dick Brandon > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sat Feb 12 17:28:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat Feb 12 17:28:50 2005 Subject: [Tutor] Larger program organization In-Reply-To: <20050211173944.07AAC1E4008@bag.python.org> References: <20050211173944.07AAC1E4008@bag.python.org> Message-ID: <420E2EBD.3000101@tds.net> Ryan Davis wrote: > I'm starting to make a code-generation suite in python, customized to > the way we ASP.NET at my company, and I'm having some trouble finding a > good way to organize all the code. I keep writing it, but it feels more > and more spaghetti-ish every day. Organize your code into packages. Give each package a clear responsibility and clear dependencies on other packages. For example my current (Jython) project has these packages: app - top-level application objects data - database access - all the SQL code and database objects dbload - helpers for initial database load gui - gui classes importer - classes to implement an import function main - misc. main programs, not really part of the main app server - embedded web server tree - support for the Swing TreeModel that is a major part of the app writer - generation of output files I also use some packages that are not specific to the application: db - generic database support swing - generic Swing widgets and support classes util - misc helpful stuff In total there are 121 Python files (including test modules) and 49 Java files. For a smaller project you might just have a few modules in one package, or just a couple of packages. HTH Kent From mark.kels at gmail.com Sat Feb 12 20:47:49 2005 From: mark.kels at gmail.com (Mark Kels) Date: Sat Feb 12 20:47:54 2005 Subject: [Tutor] Downloading from http In-Reply-To: <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> References: <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> Message-ID: On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. wrote: > urllib or urllib2 or maybe httplib maybe? > > urlopen( url[, data]) > > Open the URL url, which can be either a string or a Request object. > data should be a string, which specifies additional data to send to the > server. In HTTP requests, which are the only ones that support data, it > should be a buffer in the format of application/x-www-form-urlencoded, for > example one returned from urllib.urlencode(). > > This function returns a file-like object with two additional methods: > > a.. geturl() -- return the URL of the resource retrieved > b.. info() -- return the meta-information of the page, as a > dictionary-like object > Raises URLError on errors. > > Note that None may be returned if no handler handles the request (though > the default installed global OpenerDirector uses UnknownHandler to ensure > this never happens). > > This is taken from the docs on urllib2. I think that's what you want, right? > The tutorial or whatever, called "Dive into python", goes into accessing web > pages a little more in depth than the docs do, I think. You can google for > it, I believe. > > HTH, > Jacob > I'm sorry, but I didn't understood a thing (maybe its because of my bad english, and mybe its because I'm just dumb :). Anyway, can you give me a code example or a link to a tutorial that talks about this ? Thanks alot. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From zen45800 at zen.co.uk Sun Feb 13 05:25:50 2005 From: zen45800 at zen.co.uk (Lobster) Date: Sat Feb 12 21:25:34 2005 Subject: [Tutor] Idle needles In-Reply-To: <20050212194822.0281D1E4012@bag.python.org> References: <20050212194822.0281D1E4012@bag.python.org> Message-ID: <420ED6CE.5060103@zen.co.uk> tutor-request@python.org wrote: >Brian van den Broek wrote: > > >>But the multiple copies of pythonw seems key, and also the sort of thing >>that better Python minds than most seem to accept they have to live with >>too: >> >> > >Make sure you read the next message in the thread which gives a possible cause of the problem and a >patch that might help. >http://mail.python.org/pipermail/edu-sig/2005-January/004366.html > >Kent > > > Great advice Kent - have downloaded the IDLE patch :-) the address for the URL is wrong http://mcsp.wartburg.ed/zelle/python it should be http://mcsp.wartburg.edu/zelle/python Ed Jason From bvande at po-box.mcgill.ca Sat Feb 12 22:34:09 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 23:07:13 2005 Subject: [Tutor] help with refactoring needed -- which approach is morePythonic? In-Reply-To: <013c01c51101$9a276640$31d78751@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420CDA1D.5040204@po-box.mcgill.ca> <420CDE7A.3010408@tds.net> <420DD2D5.2060708@po-box.mcgill.ca> <013c01c51101$9a276640$31d78751@xp> Message-ID: <420E7651.5090100@po-box.mcgill.ca> Alan Gauld said unto the world upon 2005-02-12 07:51: Thanks Alan and Kent for the replies. I'm responding to a couple of questions Alan asked me about my problem. I don't think I have any further questions of my own (yet), though. :-) >>Call it node_linkify. The new thought is to create two new >>methods for the TP_file class: >> >>- One to build a dictionary with Node titles as keys and >> a list of the corresponding unique ids as values. > > > Which saves searching the node list each time, good idea. > This dictionary would of course be part of the Head or Body > object which manages the Nodes? That's the plan, yes. >>- Another to pass that list into a the node_linkify Node method, >> once for each Node object of the TP_file. > > Since the node knows its own ID and shouldn't know about > the other nodes I wonder if it would be better for the > Body/Head object to pass only what the node needs to > create the links. Or do the links go to *all* the other > related nodes? In which case the dictionary entry is fine. > > Alan G. The Node object being linkified won't know which other Node objects need to be linked to until the to-be-linkified Node's article text is scanned. So, I think the full dict is needed. The best analogy I can come up with for what I am trying to do is this: Consider a wiki which only supports WikiNames rather than arbitrary page names and arbitrary page links. Quite often, in a wiki, people add text which could/should have been in the form of a wiki link, but they didn't format it that way. For example, there might be a page called ExtantWikiName and, on some other page, someone wrote `extant wiki name' rather than `ExtantWikiName'. So, one might want a function which scanned each page of the wiki, looking for strings which match the name of wiki pages, but don't have wiki link formatting and then so format them. It seems to me that this method, if a method of each wiki page, would need to be given knowledge of all page names in the wiki. That's pretty much my task, save that my target app doesn't support wiki linking, so I need to associate node titles (the analogue of wiki page names) with the unique id's of pages with the title to be able to generate the links. Off to code it up! Thanks and best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Feb 12 23:03:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 23:07:29 2005 Subject: [Tutor] default argument frustration In-Reply-To: <00ef01c510de$a203f680$31d78751@xp> References: <420A8938.5040604@po-box.mcgill.ca> <07fe01c50f46$60d84240$68b78851@xp> <420C670B.4070209@po-box.mcgill.ca> <001e01c51067$bd0478f0$31d78751@xp> <00ef01c510de$a203f680$31d78751@xp> Message-ID: <420E7D3E.2030201@po-box.mcgill.ca> I've combined a few email's worth of quoting as no previous post had all the elements I wanted to refer to. Alan Gauld said unto the world upon 2005-02-11 13:30: >> >>FOR THE LOVE OF MIKE can someone tell me even one reason why this >>isn't a misfeature?!?! >> > > Its the only sane way to implement default arguments. The whole > point of function definitions is that they provide a single concise > interface. The function should return the same result each time > you call it with the same input. The only way to achieve that > is to have the default calculated once. Alan Gauld said unto the world upon 2005-02-12 03:41: > Karl Pfl?sterer said unto the world upon 2005-02-11 16:44: >> >>IBTD. >>With full lexical scope you only need to calculate the default >>argument in the lexical scope it was defined in. Look at a >>languale like Common Lisp. > > > Sorry, you are quite right. I meant its the only sane way to do it > given the way Python works. > > Lisp and others implement closures and defered evaluation quite > nicely, but I don't think it would be easy to build that into Python. > Although it might be easier now with nested functions etc... > > Alan G. I get that Karl was saying that other languages (eg Lisp) can do it differently, though the details of the Lisp comparison are lost on me. Alan was saying that there is no other obvious way for Python to do it. What I am still not clear on it is why Alan's claim is true. (Not doubting it is, but would like to get why it is.) Is this the rough idea this?: The def statement is executed only once, and thus the default argument is calculated just the once, too (on building of the function object). So, any way around this feature of Python would either require that defs be executed each time a function is called (giant performance hit across the board even if doable) or require the addition of a new reserved word, say redef, for function defs that should be re-evaluated each time the function is run (again, if doable). If that is in the vicinity of being right, I start to be less inclined to vent. Python's conservatism abut adding new reserved words seems a good thing, and enough to kill such a redef idea, if the performance issue wasn't. That makes the workaround a la the Tutorial seem less irksome. Thanks and best to all, Brian vdB From bvande at po-box.mcgill.ca Sat Feb 12 23:21:54 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Feb 12 23:39:03 2005 Subject: ****SPAM(11.2)**** [Tutor] Larger program organization In-Reply-To: <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> References: <20050211173944.07AAC1E4008@bag.python.org> <6.1.2.0.0.20050211132921.036258d8@mail.mric.net> Message-ID: <420E8182.9010204@po-box.mcgill.ca> Bob Gailer said unto the world upon 2005-02-11 15:34: > At 10:39 AM 2/11/2005, Ryan Davis wrote: > >> I'm starting to make a code-generation suite in python, customized to >> the way we ASP.NET at my company, and I'm having some trouble finding >> a good way to organize all the code. > > > My take on doing that in Python: > > Organize things into modules. Especially with an eye to potential reuse. > Look at the module index in the docs to see how most of the "standard" > modules focus on doing one thing well. > > Within a module create classes for every conceivable object. Whenever > you find yourself writing an if statement ask whether this would be > better handled by subclasses. Whenever you find yourself about to write > a global statement, consider making the variables properties of a class. Hi all, as readers of another concurrent thread will know, I am, with lots of help, just beginning to start thinking about proper OOP design. I am curious about Bob's "Whenever you find yourself writing an if statement ask whether this would be better handled by subclasses." Could you explain a bit more? Thanks and best, Brian vdB From kent37 at tds.net Sun Feb 13 01:02:58 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun Feb 13 01:03:05 2005 Subject: [Tutor] Downloading from http In-Reply-To: References: <001a01c5110e$ae6583f0$c15428cf@JSLAPTOP> Message-ID: <420E9932.50107@tds.net> Mark Kels wrote: > On Sat, 12 Feb 2005 09:25:10 -0500, Jacob S. wrote: > >>urllib or urllib2 or maybe httplib maybe? >> >> urlopen( url[, data]) > I'm sorry, but I didn't understood a thing (maybe its because of my > bad english, and mybe its because I'm just dumb :). Anyway, can you > give me a code example or a link to a tutorial that talks about this ? >>> from urllib import urlopen >>> u=urlopen('http://www.google.com') >>> d=u.read() >>> print d[:200] Google