From mindboggler12 at gmail.com Wed Jul 1 02:38:05 2009 From: mindboggler12 at gmail.com (jonathan wallis) Date: Tue, 30 Jun 2009 20:38:05 -0400 Subject: [Tutor] Need help with python game program Message-ID: <57b8984c0906301738w1fb0e660m6bb2123399f27a0e@mail.gmail.com> My problem is simple, is their a way to make a variable equal multiple numbers? Such as X = 5 through 10, and then the program makes x equal something random 5 through 10, or something similar. 2009/6/30 > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. PYTHONPATH-corrected (Bob Rea) > 2. Re: Needing Help (Bob Rea) > 3. Re: PYTHONPATH-corrected (Steve Willoughby) > 4. Re: Needing Help (Wayne) > 5. Re: Needing Help (Bob Rea) > 6. Re: Needing Help (Marc Tompkins) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 30 Jun 2009 14:33:27 -0400 > From: Bob Rea > To: tutor at python.org > Subject: [Tutor] PYTHONPATH-corrected > Message-ID: <200906301433.27455.petard at petard.us> > Content-Type: text/plain; charset="iso-8859-1" > > In working my way through the book on python, I am working > in directories for chapers. Now I am on modules, and some > are reused in later chapters. I have set up a directory for > the modules. How do I add it to my PYTHONPATH? > I can use sys.path.append but that only lasts for the > session. > > This is on a suse linux 10 box > > -- > Bob Rea > mailto:petard at petard.us > http://www.petard.us > http://www.petard.us/blog > http://www.petard.us/gallery > > > ------------------------------ > > Message: 2 > Date: Tue, 30 Jun 2009 14:06:01 -0400 > From: Bob Rea > To: tutor at python.org > Subject: Re: [Tutor] Needing Help > Message-ID: <200906301406.02104.bob at telaugos.com> > Content-Type: text/plain; charset="utf-8" > > On Tue June 30 2009 1:17 pm, vishwajeet singh > wrote: > > You can put your script in pastebin > > http://python.pastebin.com/ > > I don't think any one will > > mind you pasting code in mail but pastebin makes it > > easier to read > > I am making my way through _Making Use of Python_ by Rashi > Gupta. I am using Python 2.4.1 > > I have run into problems in a script, listed at > http://python.pastebin.com/m51bc3388 > > If I input my own name and dob, it works: > bob at gandalf:~/python/MakingUse/Chapter05> python code1.py > Enter your first name: Bob > Enter your last name: Rea > Enter your date of birth, mm-dd-yyyy: 03-05-1943 > You can chose one of the following login names: > 1. BobR > 2. BobR53 > 3. RBob43 > 4. BRea66 > > If I use the data listed in the book, it fails: > bob at gandalf:~/python/MakingUse/Chapter05> python code1.py > Enter your first name: Laura > Enter your last name: Jones > Enter your date of birth, mm-dd-yyyy: 12-24-1980 > You can chose one of the following login names: > 1. LauraJ > 2. LauraJ2412 > 3. JLaura80 > Traceback (most recent call last): > File "code1.py", line 67, in ? > fourth=fname[0]+lname+ age_func() > TypeError: cannot concatenate 'str' and 'NoneType' objects > > What is going on here? > > Bob Rea > petard at petard.us > -- > Bob Rea > mailto:gapetard at stsams.org > http://www.petard.us > http://www.petard.us/blog > http://www.petard.us/gallery > > Where is Bill Stringfellow > now that we really need him? > > > ------------------------------ > > Message: 3 > Date: Tue, 30 Jun 2009 12:08:13 -0700 > From: Steve Willoughby > To: Bob Rea > Cc: tutor at python.org > Subject: Re: [Tutor] PYTHONPATH-corrected > Message-ID: <20090630190813.GA65674 at dragon.alchemy.com> > Content-Type: text/plain; charset=us-ascii > > On Tue, Jun 30, 2009 at 02:33:27PM -0400, Bob Rea wrote: > > In working my way through the book on python, I am working > > in directories for chapers. Now I am on modules, and some > > are reused in later chapters. I have set up a directory for > > the modules. How do I add it to my PYTHONPATH? > > I can use sys.path.append but that only lasts for the > > session. > > You set the variable in your system's environment, which is > platform-dependent. For Linux, you'd typically put a line > in your ~/.profile or ~/.cshrc or ~/.login or ~/.bashrc or > whatever your shell uses per your account set up. > > So, for example, in a bash/sh shell, you'd say: > > export PYTHONPATH="/path/to/my/modules" > > or for csh: > > setenv PYTHONPATH "/path/to/my/modules" > > Then starting the next time you log in, that will be set > in your environment for you. > > > This is on a suse linux 10 box > > > > -- > > Bob Rea > > mailto:petard at petard.us > > http://www.petard.us > > http://www.petard.us/blog > > http://www.petard.us/gallery > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. > > > ------------------------------ > > Message: 4 > Date: Tue, 30 Jun 2009 14:27:34 -0500 > From: Wayne > To: Bob Rea > Cc: tutor at python.org > Subject: Re: [Tutor] Needing Help > Message-ID: > <333efb450906301227u76274a83x53ef42fdae41fead at mail.gmail.com> > Content-Type: text/plain; charset="windows-1252" > > Oops, forgot my reply-to-all > > On Tue, Jun 30, 2009 at 2:20 PM, Wayne wrote: > > > On Tue, Jun 30, 2009 at 1:06 PM, Bob Rea wrote: > > > >> > >> If I input my own name and dob, it works: > >> bob at gandalf:~/python/MakingUse/Chapter05> python code1.py > >> Enter your first name: Bob > >> Enter your last name: Rea > >> Enter your date of birth, mm-dd-yyyy: 03-05-1943 > >> You can chose one of the following login names: > >> 1. BobR > >> 2. BobR53 > >> 3. RBob43 > >> 4. BRea66 > >> > >> If I use the data listed in the book, it fails: > >> bob at gandalf:~/python/MakingUse/Chapter05> python code1.py > >> Enter your first name: Laura > >> Enter your last name: Jones > >> Enter your date of birth, mm-dd-yyyy: 12-24-1980 > >> You can chose one of the following login names: > >> 1. LauraJ > >> 2. LauraJ2412 > >> 3. JLaura80 > >> Traceback (most recent call last): > >> File "code1.py", line 67, in ? > >> fourth=fname[0]+lname+ age_func() > >> TypeError: cannot concatenate 'str' and 'NoneType' objects > >> > >> What is going on here? > >> > > > > Well the first line after "Traceback" give you the line of code and the > > filename. Which happens to be code1.py line 67. > > > > TypeError is the type of error - specifically you tried to do something > > with incompatible types. In this case, adding together a string and > > NoneType. > > > > I'll do a little digging, but my guess is you have a problem with your > > age_func() not returning any value. > > > > HTH, > > Wayne > > > > I was correct:def age_func(): > age=cur_year-year-1 > if month age=age+1 > return str(age) > > What happens if month is > cur_month AND it's not my birthday? > > You don't return a value. But if you simply unindent the "return" value > then > it should fix it: > > def age_func(): > age=cur_year-year-1 > if month age=age+1 > return str(age) > > Now regardless of whether age is incremented, it will return a string. > HTH, > Wayne > -- > To be considered stupid and to be told so is more painful than being called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every > weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn?t. - Primo Levi > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20090630/fe4ba054/attachment-0001.htm > > > > ------------------------------ > > Message: 5 > Date: Tue, 30 Jun 2009 15:27:17 -0400 > From: Bob Rea > To: Wayne > Cc: tutor at python.org > Subject: Re: [Tutor] Needing Help > Message-ID: <200906301527.20516.bob at telaugos.com> > Content-Type: text/plain; charset="utf-8" > > On Tue June 30 2009 3:20 pm, you wrote: > > On Tue, Jun 30, 2009 at 1:06 PM, Bob Rea > wrote: > > > > > > If I input my own name and dob, it works: > > > bob at gandalf:~/python/MakingUse/Chapter05> python > > > code1.py Enter your first name: Bob > > > Enter your last name: Rea > > > Enter your date of birth, mm-dd-yyyy: 03-05-1943 > > > You can chose one of the following login names: > > > 1. BobR > > > 2. BobR53 > > > 3. RBob43 > > > 4. BRea66 > > > > > > If I use the data listed in the book, it fails: > > > bob at gandalf:~/python/MakingUse/Chapter05> python > > > code1.py Enter your first name: Laura > > > Enter your last name: Jones > > > Enter your date of birth, mm-dd-yyyy: 12-24-1980 > > > You can chose one of the following login names: > > > 1. LauraJ > > > 2. LauraJ2412 > > > 3. JLaura80 > > > Traceback (most recent call last): > > > File "code1.py", line 67, in ? > > > fourth=fname[0]+lname+ age_func() > > > TypeError: cannot concatenate 'str' and 'NoneType' > > > objects > > > > > > What is going on here? > > > > Well the first line after "Traceback" give you the line > > of code and the filename. Which happens to be code1.py > > line 67. > > > > TypeError is the type of error - specifically you tried > > to do something with incompatible types. In this case, > > adding together a string and NoneType. > > > > I'll do a little digging, but my guess is you have a > > problem with your age_func() not returning any value. > > > > HTH, > > Wayne > > Why doe sit work with a dob in 1943 and not with one in 1980 > then, that's what really bugs me > -- > Bob Rea > mailto:gapetard at stsams.org > http://www.petard.us > http://www.petard.us/blog > http://www.petard.us/gallery > > Where is Bill Stringfellow > now that we really need him? > > > ------------------------------ > > Message: 6 > Date: Tue, 30 Jun 2009 12:45:00 -0700 > From: Marc Tompkins > To: Bob Rea > Cc: tutor at python.org > Subject: Re: [Tutor] Needing Help > Message-ID: > <40af687b0906301245n3ffcc950k458e4bf629530965 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Tue, Jun 30, 2009 at 12:27 PM, Bob Rea wrote: > > > Why doe sit work with a dob in 1943 and not with one in 1980 > > then, that's what really bugs me > > > > Nothing to do with the year. Your birth month is BEFORE June; her birth > month is after. > -- > www.fsrtechnologies.com > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20090630/0afb4e3c/attachment.htm > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 64, Issue 135 > ************************************** > -- You will be a winner today. Pick a fight with a four-year-old. You should emulate your heros, but don't carry it too far. Especially if they are dead. -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Wed Jul 1 02:56:14 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 30 Jun 2009 17:56:14 -0700 Subject: [Tutor] Need help with python game program References: <57b8984c0906301738w1fb0e660m6bb2123399f27a0e@mail.gmail.com> Message-ID: "jonathan wallis" wrote in message news:57b8984c0906301738w1fb0e660m6bb2123399f27a0e at mail.gmail.com... > My problem is simple, is their a way to make a variable equal multiple > numbers? Such as X = 5 through 10, and then the program makes x equal > something random 5 through 10, or something similar. Use the random module. There are various types of random number generation there, such as: x = random.randint(5,10) -Mark From rabidpoobear at gmail.com Wed Jul 1 04:01:25 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 30 Jun 2009 21:01:25 -0500 Subject: [Tutor] Need help with python game program In-Reply-To: <57b8984c0906301738w1fb0e660m6bb2123399f27a0e@mail.gmail.com> References: <57b8984c0906301738w1fb0e660m6bb2123399f27a0e@mail.gmail.com> Message-ID: Please don't reply to messages like this. If you are starting a new thread, send a new e-mail to tutor at python.org. DO NOT start a thread by replying to another message. If you do, it will bork on people's machines who use threaded e-mail readers. also, please remove long, irrelevant quotations from your e-mails unless you reference it. for example, the quoted text in your e-mail is at least 10x longer than the actual content.I believe mark already answered your question. Thanks, -Luke On Tue, Jun 30, 2009 at 7:38 PM, jonathan wallis wrote: > My problem is simple, is their a way to make a variable equal multiple > numbers? Such as X = 5 through 10, and then the program makes x equal > something random 5 through 10, or something similar. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Jul 1 04:29:47 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 30 Jun 2009 22:29:47 -0400 Subject: [Tutor] Need help with python game program In-Reply-To: References: Message-ID: <4A4ACA1B.1060604@ieee.org> jonathan wallis wrote: > My problem is simple, is their a way to make a variable equal multiple > numbers? Such as X = 5 through 10, and then the program makes x equal > something random 5 through 10, or something similar. > > For a short question, why did you quote an entire mailing list digest? Answer to your question, certainly a variable can "equal" multiple numbers. Several ways: 1) one at a time. X=5, then later X=7.332 2) a list of values X = [5.3, 8.001, 17, 2] 3) a dictionary X = {"tom":3, "dick":42, "harry":12} 4) a class. Sky's the limit here As for random, look up the random.uniform() and random.randint() functions. Did you have a particular programming language in mind? I've been assuming Python, but you might be thinking something else. Have you any experience in any other language? DaveA From sato.photo at gmail.com Wed Jul 1 04:53:10 2009 From: sato.photo at gmail.com (Daniel Sato) Date: Tue, 30 Jun 2009 19:53:10 -0700 Subject: [Tutor] Python Programming exercise Message-ID: I have been going through some Python Programming exercises while following the MIT OpenCourseWare Intro to CS syllabus and am having some trouble with the first "If" exercise listed on this page: http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises I have been able to make the module quit after entering a password three times, but can't get it to quit right away after the correct one is entered. I know this is really basic, please forgive me. I have no programming experience and have just started going through these tutorials. My code is here: http://python.pastebin.com/m6036b52e -- Daniel Sato http://www.danielsato.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From vincent at vincentdavis.net Wed Jul 1 05:39:35 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Tue, 30 Jun 2009 21:39:35 -0600 Subject: [Tutor] calculating a sort key and operator.attrgetter() Message-ID: <77e831100906302039u9017151u45e3bd6fec3b0372@mail.gmail.com> I have a class with an attribute which is a list "rank_list" this is a list of instances f another class that has attributes "quality, is_observed" if I want to sort the list by the attribute "quality" I can just use, self.rank_list.sort(key=operator.attrgetter('quality')) But I want to sort like this. self.rank_list.sort(key=(operator.attrgetter('quality') * operator.attrgetter('is_observed') * self.does_observe)) Will this work or is there a better way? Thanks Vincent Davis -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jul 1 09:55:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 1 Jul 2009 08:55:17 +0100 Subject: [Tutor] PYTHONPATH-corrected References: <200906301433.27455.petard@petard.us> <20090630190813.GA65674@dragon.alchemy.com> Message-ID: "Steve Willoughby" wrote >> in directories for chapers. Now I am on modules, and some >> are reused in later chapters. I have set up a directory for >> the modules. How do I add it to my PYTHONPATH? > So, for example, in a bash/sh shell, you'd say: > > export PYTHONPATH="/path/to/my/modules" And you can add multiple directories by separating them with colons: export PYTHONPATH="/path/to/my/modules:/path/to/more/modules:/path/ytoyet/more" HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From foobar8 at gmail.com Wed Jul 1 11:06:24 2009 From: foobar8 at gmail.com (=?ISO-8859-1?Q?Siim_M=E4rtmaa?=) Date: Wed, 1 Jul 2009 12:06:24 +0300 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <76f6cc7c0907010206v547cc1b0ye230f006eb9af77c@mail.gmail.com> 2009/7/1 Daniel Sato : > I have been going through some Python Programming exercises while following > the MIT OpenCourseWare Intro to CS syllabus and am having some trouble with > the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is > entered.? I know this is really basic, please forgive me.? I have no > programming experience and have just started going through these tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e > > -- > Daniel Sato > http://www.danielsato.com > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hello daniel, some comments password = "qwerty" guess = "0" # <- no need to initialise that variable or # if you would need, using just "" would be enough #instead of "0" count = 0 while count != 3: # <- that works here, but i usually use "< 3" guess = raw_input("Enter your password: ") guess = str(guess) # no need to typecast here because raw_input alredy returns a str #when you don't know the type use type(yourvar) in python if guess != password # missing ":" print "Access Denied" count = count + 1 # <- has to be indented to the same level with the above line # also you can use count += 1 instead else: print "Password Confirmed" # to exit you can use the exit() function From emile at fenx.com Wed Jul 1 18:19:16 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 01 Jul 2009 09:19:16 -0700 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: On 6/30/2009 7:53 PM Daniel Sato said... > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is > entered. I know this is really basic, please forgive me. I have no > programming experience and have just started going through these tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e First, paste your code into a python command window. You'll get errors, but clean them up. Second, code blocks that are indented alike execute as part of the same block. Take a look where you increment count. HTH, Emile From angusr at bigfoot.com Wed Jul 1 17:44:36 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Wed, 01 Jul 2009 16:44:36 +0100 Subject: [Tutor] When are strings interned? Message-ID: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> Hello, world! This is my first post to the Tutor list (although I've already posted to comp.lang.python a couple of times). I'm currently reading Chapter 4 of Wesley Chun's book, "Core Python Programming" (2nd ed.). I find this, in Python 2.5.4, on my Win98SE system (using IDLE): >>> n = "colourless" >>> o = "colourless" >>> n == o True >>> n is o True >>> p = "green ideas" >>> q = "green ideas" >>> p == q True >>> p is q False Why the difference? -- Angus Rodgers From motoom at xs4all.nl Wed Jul 1 11:39:22 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 01 Jul 2009 11:39:22 +0200 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <4A4B2ECA.6060807@xs4all.nl> Daniel Sato wrote: > am having some trouble with the first "If" Don't forget the colon at the end of the line. if condition: pass Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From kent37 at tds.net Wed Jul 1 07:15:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 1 Jul 2009 01:15:10 -0400 Subject: [Tutor] calculating a sort key and operator.attrgetter() In-Reply-To: <77e831100906302039u9017151u45e3bd6fec3b0372@mail.gmail.com> References: <77e831100906302039u9017151u45e3bd6fec3b0372@mail.gmail.com> Message-ID: <1c2a2c590906302215p62bf29c6je7868868dbe5e18b@mail.gmail.com> On Tue, Jun 30, 2009 at 11:39 PM, Vincent Davis wrote: > I have a class with an attribute which is a list "rank_list" this is a list > of instances f another class that has attributes "quality, is_observed" > if I want to sort the list by the attribute "quality" I can just use, > self.rank_list.sort(key=operator.attrgetter('quality')) > But I want to sort like this. > self.rank_list.sort(key=(operator.attrgetter('quality') * > operator.attrgetter('is_observed') * self.does_observe)) > Will this work or is there a better way? That won't work because attrgetter() returns a function and you can't multiply functions. What you can do is define your own function that returns the value you want for the key and use that for the sort. I'm leaving out self.does_observe because that won't change for the list items, wil it? def make_key(item): return item.quality * item.is_observed self.rank_list.sort(key=make_key) Kent From roadierich at googlemail.com Wed Jul 1 12:31:27 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 1 Jul 2009 11:31:27 +0100 Subject: [Tutor] Fwd: calculating a sort key and operator.attrgetter() In-Reply-To: References: <77e831100906302039u9017151u45e3bd6fec3b0372@mail.gmail.com> Message-ID: Forgot to reply-all... ---------- Forwarded message ---------- From: Rich Lovely Date: 2009/7/1 Subject: Re: [Tutor] calculating a sort key and operator.attrgetter() To: Vincent Davis 2009/7/1 Vincent Davis : > I have a class with an attribute which is a list "rank_list" this is a list > of instances f another class that has attributes "quality, is_observed" > if I want to sort the list by the attribute "quality" I can just use, > self.rank_list.sort(key=operator.attrgetter('quality')) > But I want to sort like this. > self.rank_list.sort(key=(operator.attrgetter('quality') * > operator.attrgetter('is_observed') * self.does_observe)) > Will this work or is there a better way? > > Thanks > Vincent Davis > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > The attrgetter returns a callable, so you'll get e syntax error along the lines of "You can't multiply two function objects". As written, it sounds as if self.does_observe will be the same for all classes within the container, therefore it has no effect on the sort results. ?The only relevant bits are the two attrgetters. The key argument expects a callable that takes one arguement, and returns the value to be compared. ?Attrgetter returns a function that takes an object as an argument and gets the attribute named in the call to the generator. ?When you know the name of the attribute you want in advance, you can get the same effect using a lambda: operator.attrgetter("is_observed") --> lambda o: o.is_observed There are two ways to do what you're after: 1. Define a new function (This can be inside the function that does the sorting, or higher if it's needed elsewhere) def keyFunc(o): ? ?"""returns a sort key for object o""" ? ?return o.quality * o.is_observed self.rank_list.sort(key=keyFunc) 2. use a lambda: self.rank_list.sort(key=(lambda o: o.quality * o.is_observed)) If you want a reusable solution, method 1 is better. ?If you want a simple, easy to read, solution, 2 is probably better. ?If there is a chance of the wrong sort of class getting into the list, you'll need to use 1 if you want to use error handling, as you can't use try and except in a lambda. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From srilyk at gmail.com Wed Jul 1 15:23:21 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 1 Jul 2009 08:23:21 -0500 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <333efb450907010623j203173f0o997e540e3887febc@mail.gmail.com> On Tue, Jun 30, 2009 at 9:53 PM, Daniel Sato wrote: > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is > entered. I know this is really basic, please forgive me. I have no > programming experience and have just started going through these tutorials Let's take a quick look at your code: 1. password = "qwerty" 2. guess = "0" 3. count = 0 4. while count != 3: 5. guess = raw_input("Enter your password: ") 6. guess = str(guess) 7. if guess != password 8. print "Access Denied" 9. count = count + 1 10. else: 11. print "Password Confirmed" On line 4 you enter a while loop. What criteria stops the loop? As an aside - with while loops it's better to use a < or > (or >= <=) comparison. Because what happens if something goes wrong inside your loop and count becomes 4? Your loop takes a LONG time to finish! Actually in python it probably won't ever finish. Also you should move line 9 either right after line 4 or right after line 11. When you're incrementing a value it's best to do it at the beginning or end of a loop. (and certainly never in between an if and else!) So with this in mind, what could you do once it prints "Password confirmed" to make sure the loop ends? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From froslie at gmail.com Wed Jul 1 22:47:40 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 1 Jul 2009 16:47:40 -0400 Subject: [Tutor] egg Message-ID: <41fcacc90907011347w1e938c64j92428e3abf120dc3@mail.gmail.com> Hi, I have a basic question concerning pythons eggs. I have setup easy install and used it to install mechanize-- this was easy as I only needed to type in 'Easy_Install Mechanize' in terminal. Now I need to install 'simplejson 2.0.9' from this here: http://pypi.python.org/pypi/simplejson Can anyone suggest the correct way to do this as it seems it is not as direct? I've read the EasyInstall documentation and believe I understand how, but am a little confused regarding my python paths. Using Mac OSX 10.5.7 Thanks so much, -- Pete Froslie http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From froslie at gmail.com Wed Jul 1 23:40:41 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 1 Jul 2009 17:40:41 -0400 Subject: [Tutor] egg In-Reply-To: <41fcacc90907011347w1e938c64j92428e3abf120dc3@mail.gmail.com> References: <41fcacc90907011347w1e938c64j92428e3abf120dc3@mail.gmail.com> Message-ID: <41fcacc90907011440y711308ft3826e2df58e7ff2e@mail.gmail.com> responding to myself: apparently it seems to be as simple again as: 'easy_install simplejson' from terminal. Anyone, have a suggestion for a resource where I can read more about the paths I have setup? I would like to make sure there are not any redundancies.. thanks On Wed, Jul 1, 2009 at 4:47 PM, Pete Froslie wrote: > Hi, I have a basic question concerning pythons eggs. I have setup easy > install and used it to install mechanize-- this was easy as I only needed to > type in 'Easy_Install Mechanize' in terminal. Now I need to install > 'simplejson 2.0.9' from this here: http://pypi.python.org/pypi/simplejson > > Can anyone suggest the correct way to do this as it seems it is not as > direct? I've read the EasyInstall documentation and believe I understand > how, but am a little confused regarding my python paths. Using Mac OSX > 10.5.7 > > Thanks so much, > > -- > Pete Froslie > http://www.froslie.net > > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Wed Jul 1 14:33:38 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 01 Jul 2009 08:33:38 -0400 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <1246451618.31620.17.camel@bermanrl-desktop> 1. Pay more attention to what ends an if statement (:) also watch your indentation. 2. Code is better than my commentary. This works the way you want it to work. password = "qwerty" guess = "0" count = 0 while count != 3: guess = raw_input("Enter your password: ") guess = str(guess) if guess != password: print "Access Denied" count = count + 1 else: print "Password Confirmed" break Robert Berman On Tue, 2009-06-30 at 19:53 -0700, Daniel Sato wrote: > I have been going through some Python Programming exercises while > following the MIT OpenCourseWare Intro to CS syllabus and am having > some trouble with the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password > three times, but can't get it to quit right away after the correct one > is entered. I know this is really basic, please forgive me. I have > no programming experience and have just started going through these > tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e > > -- > Daniel Sato > http://www.danielsato.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at gmail.com Wed Jul 1 17:00:45 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 01 Jul 2009 11:00:45 -0400 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <4A4B7A1D.5050003@gmail.com> Daniel Sato wrote: > I have been going through some Python Programming exercises while > following the MIT OpenCourseWare Intro to CS syllabus and am having > some trouble with the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password > three times, but can't get it to quit right away after the correct one > is entered. I know this is really basic, please forgive me. I have > no programming experience and have just started going through these > tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e When the code is that small please just put it in the body of your post. Save pastebin for (IMHO) anything over say 60 lines. 1. password = "qwerty" 2. guess = "0" 3. count = 0 4. while count != 3: 5. guess = raw_input("Enter your password: ") 6. guess = str(guess) 7. if guess != password 8. print "Access Denied" 9. count = count + 1 10. else: 11. print "Password Confirmed" 2 ways - either 1. while count != 3 and guess != password: or 11. print "Password Confirmed" 12. break -- Bob Gailer Chapel Hill NC 919-636-4239 From bermanrl at cfl.rr.com Thu Jul 2 02:29:35 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 01 Jul 2009 20:29:35 -0400 Subject: [Tutor] When are strings interned? In-Reply-To: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> References: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> Message-ID: <1246494575.31620.29.camel@bermanrl-desktop> On Wed, 2009-07-01 at 16:44 +0100, Angus Rodgers wrote: > Hello, world! > > This is my first post to the Tutor list (although I've already > posted to comp.lang.python a couple of times). > > I'm currently reading Chapter 4 of Wesley Chun's book, "Core > Python Programming" (2nd ed.). > > I find this, in Python 2.5.4, on my Win98SE system (using IDLE): > > >>> n = "colourless" > >>> o = "colourless" > >>> n == o > True > >>> n is o > True > >>> p = "green ideas" > >>> q = "green ideas" > >>> p == q > True > >>> p is q > False > > Why the difference? The string p is equal to the string q. The object p is not the object q. Robert From cwitts at compuscan.co.za Wed Jul 1 08:48:16 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 01 Jul 2009 08:48:16 +0200 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <4A4B06B0.3070804@compuscan.co.za> Daniel Sato wrote: > I have been going through some Python Programming exercises while > following the MIT OpenCourseWare Intro to CS syllabus and am having > some trouble with the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password > three times, but can't get it to quit right away after the correct one > is entered. I know this is really basic, please forgive me. I have > no programming experience and have just started going through these > tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e > > -- > Daniel Sato > http://www.danielsato.com > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Indent line 9, because Python is indentation sensitive and does not use braces for code blocks you have to make sure it is all in-line. Also line 8 should have a colon at the end of it. My memory is a bit fuzzy on whether or not raw_input() captures the new-line character as well, so if it doesn't match still you will need to do a .strip() on your guess. Hope that helps. -- Kind Regards, Christian Witts From davea at ieee.org Wed Jul 1 20:42:03 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 01 Jul 2009 14:42:03 -0400 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <4A4BADFB.1050309@ieee.org> Daniel Sato wrote: > > > I have been going through some Python Programming exercises while following > the MIT OpenCourseWare Intro to CS syllabus and am having some trouble with > the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is > entered. I know this is really basic, please forgive me. I have no > programming experience and have just started going through these tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e > > (for short functions, it's probably better to just include it in your message. That way, they'll be archived together, in case somebody is reading this message a year from now.) You have no context. Are you going to actually do something with the password, or are you done when the confirmation has been printed out? If the latter, just add a line after the print statement, setting count = 99. You could use a break as well, but then you wouldn't have anything to indicate whether the password was ever correctly entered. Normally, this would be inside a function (def), which might return a boolean indicating whether the password succeeded or not. In that case, you might put a return instead. From craig.a.mcd at googlemail.com Wed Jul 1 08:46:41 2009 From: craig.a.mcd at googlemail.com (Craig McDonald) Date: Wed, 1 Jul 2009 07:46:41 +0100 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: <29bd9a600906302346l20d134e9yc09cbc4a4eaf0c6d@mail.gmail.com> On Wed, Jul 1, 2009 at 3:53 AM, Daniel Sato wrote: > I have been going through some Python Programming exercises while following > the MIT OpenCourseWare Intro to CS syllabus and am having some trouble with > the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is > entered.? I know this is really basic, please forgive me.? I have no > programming experience and have just started going through these tutorials. You need a 'break' statement to terminate the loop once the condition has been met. http://www.swaroopch.com/notes/Python_en:Control_Flow#The_break_Statement Craig From marc.tompkins at gmail.com Thu Jul 2 03:43:04 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 1 Jul 2009 18:43:04 -0700 Subject: [Tutor] When are strings interned? In-Reply-To: <1246494575.31620.29.camel@bermanrl-desktop> References: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> <1246494575.31620.29.camel@bermanrl-desktop> Message-ID: <40af687b0907011843u48e0a08anf23af7230938b073@mail.gmail.com> On Wed, Jul 1, 2009 at 5:29 PM, Robert Berman wrote: > > >>> n = "colourless" > > >>> o = "colourless" > > >>> n == o > > True > > >>> n is o > > True > > >>> p = "green ideas" > > >>> q = "green ideas" > > >>> p == q > > True > > >>> p is q > > False > > > > Why the difference? > > The string p is equal to the string q. The object p is not the object q. > > Robert > Yes, but did you read his first example? That one has me scratching my head. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Wed Jul 1 16:07:15 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 1 Jul 2009 16:07:15 +0200 Subject: [Tutor] Python Programming exercise In-Reply-To: References: Message-ID: 2009/7/1 Daniel Sato : > I have been going through some Python Programming exercises while following > the MIT OpenCourseWare Intro to CS syllabus and am having some trouble with > the first "If" exercise listed on this page: > > http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements#If_Exercises > > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is > entered.? I know this is really basic, please forgive me.? I have no > programming experience and have just started going through these tutorials. > > My code is here: > > http://python.pastebin.com/m6036b52e Some genral comments. # You do not need to create the guess variable wirh value "0" as it gets created in the while loop. # raw_input() already gives a string so no need to use str() on guess You will need to break out of the while loop if the password matches. So add a break under print "Password Confirmed" and it will stop when you want it to . Below is a modified (untested) version. Greets Sander ---- password = "qwerty" count = 0 while count != 3: guess = raw_input("Enter your password: ") if guess != password print "Access Denied" count = count + 1 else: print "Password Confirmed" break ---- From vincent at vincentdavis.net Wed Jul 1 16:36:09 2009 From: vincent at vincentdavis.net (Vincent Davis) Date: Wed, 1 Jul 2009 08:36:09 -0600 Subject: [Tutor] calculating a sort key and operator.attrgetter() In-Reply-To: <1c2a2c590906302215p62bf29c6je7868868dbe5e18b@mail.gmail.com> References: <77e831100906302039u9017151u45e3bd6fec3b0372@mail.gmail.com> <1c2a2c590906302215p62bf29c6je7868868dbe5e18b@mail.gmail.com> Message-ID: <77e831100907010736nd7a9c31k320d1d5d1f58cf4c@mail.gmail.com> Thanks for the help, Looks like I will define a function. And yes you are right self.does_observe is constant so it will not affect the outcome. Thanks again Vincent Davis On Tue, Jun 30, 2009 at 11:15 PM, Kent Johnson wrote: > On Tue, Jun 30, 2009 at 11:39 PM, Vincent Davis > wrote: > > I have a class with an attribute which is a list "rank_list" this is a > list > > of instances f another class that has attributes "quality, is_observed" > > if I want to sort the list by the attribute "quality" I can just use, > > self.rank_list.sort(key=operator.attrgetter('quality')) > > But I want to sort like this. > > self.rank_list.sort(key=(operator.attrgetter('quality') * > > operator.attrgetter('is_observed') * self.does_observe)) > > Will this work or is there a better way? > > That won't work because attrgetter() returns a function and you can't > multiply functions. What you can do is define your own function that > returns the value you want for the key and use that for the sort. I'm > leaving out self.does_observe because that won't change for the list > items, wil it? > > def make_key(item): > return item.quality * item.is_observed > > self.rank_list.sort(key=make_key) > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jul 1 10:02:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 1 Jul 2009 09:02:29 +0100 Subject: [Tutor] Python Programming exercise References: Message-ID: "Daniel Sato" wrote > I have been able to make the module quit after entering a password three > times, but can't get it to quit right away after the correct one is ------------ password = "qwerty" guess = "0" count = 0 while count != 3: guess = raw_input("Enter your password: ") guess = str(guess) if guess != password print "Access Denied" count = count + 1 else: print "Password Confirmed" --------- There are a couple of ways to do it. The simplest is probably just to insert the break command into the code after printing "Password Confirmed" But you could alternatively change the test in the loop to be: while count <= 3 and guess != password: as before... Either way works. Notice that I changed the loop test from !=3 to <=3 This is a little bit safer because if for some reason (a bug say) the loop code changes the count beyond 3 your code will loop forever... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wescpy at gmail.com Thu Jul 2 06:02:15 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 1 Jul 2009 21:02:15 -0700 Subject: [Tutor] When are strings interned? In-Reply-To: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> References: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> Message-ID: <78b3a9580907012102s282f55f2r2784507875c1bdb2@mail.gmail.com> >>>> n = "colourless" >>>> o = "colourless" >>>> n == o > True >>>> n is o > True >>>> p = "green ideas" >>>> q = "green ideas" >>>> p == q > True >>>> p is q > False > > Why the difference? angus, welcome to Python! you're definitely doing your homework when it comes to trying to understand how Python manages its memory. with regards to your query, you came up with a very good example. fortunately, it's not that important for beginners to fully understand this behavior because for the most part when dealing with strings, you will rarely *care* about whether two variables reference the same string object (or not). you will just use "==" as you did above, and both cases result in the same consistent answer. checking object identity (using 'is') occurs most commonly when comparing a variable against a well-known constant such as True, False, and None. the remaining use cases are where you really do care that a pair of variables refers to the exact same object. regardless, with respect to you original question (which is asked every now and then), there is no hardcoded rule or algorithm that is published because it may change in subsequent versions of Python. the main idea is that short and often-used strings (such as those which can be attribute names or dictionary keys) are interned while the rest are not. here is another reply that someone posted several years ago that may also help: http://groups.google.com/group/comp.lang.python/msg/e4c9c360e19d9c78 hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From jeremiah.dodds at gmail.com Thu Jul 2 10:49:09 2009 From: jeremiah.dodds at gmail.com (Jeremiah Dodds) Date: Thu, 2 Jul 2009 09:49:09 +0100 Subject: [Tutor] When are strings interned? In-Reply-To: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> References: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> Message-ID: <12cbbbfc0907020149s4a9e1354ibdb132f16873c6d8@mail.gmail.com> On Wed, Jul 1, 2009 at 4:44 PM, Angus Rodgers wrote: > Hello, world! > > This is my first post to the Tutor list (although I've already > posted to comp.lang.python a couple of times). > > I'm currently reading Chapter 4 of Wesley Chun's book, "Core > Python Programming" (2nd ed.). > > I find this, in Python 2.5.4, on my Win98SE system (using IDLE): > > >>> n = "colourless" > >>> o = "colourless" > >>> n == o > True > >>> n is o > True > >>> p = "green ideas" > >>> q = "green ideas" > >>> p == q > True > >>> p is q > False > > Why the difference? > -- > > IIRC, in cPython (the "defaul" python available from python.org), there is an optimization done for strings (and I think integers) below a certain size. This is an implementation detail, and could be different in (for instance) Jython. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jul 2 12:39:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 02 Jul 2009 20:39:28 +1000 Subject: [Tutor] When are strings interned? In-Reply-To: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> References: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> Message-ID: Angus Rodgers wrote: > Hello, world! > > This is my first post to the Tutor list (although I've already > posted to comp.lang.python a couple of times). > > I'm currently reading Chapter 4 of Wesley Chun's book, "Core > Python Programming" (2nd ed.). > > I find this, in Python 2.5.4, on my Win98SE system (using IDLE): > >>>> n = "colourless" >>>> o = "colourless" >>>> n == o > True >>>> n is o > True >>>> p = "green ideas" >>>> q = "green ideas" >>>> p == q > True >>>> p is q > False > > Why the difference? In this particular case, the reason is because "colourless" can be used as an identifier. Now, before I continue, I need to warn, never to rely on any sort of interning behavior; as they are strictly implementation detail, implementation specific, and is NOT the behavior of Python (but only the behavior of CPython). Identifier are strings that can be used for names (variables). In python most name lookups are actually a dict lookup (except for locals). Strings that can be used as identifier are interned to speed up these lookups. Identifiers cannot contain spaces, that's why green ideas are not interned. And... have I told you not to rely on this behavior? NEVER rely on this implementation details. Once you get bitten by it, you'll regret it. From dhburns at cherokeetel.net Wed Jul 1 21:49:42 2009 From: dhburns at cherokeetel.net (David H. Burns) Date: Wed, 01 Jul 2009 14:49:42 -0500 Subject: [Tutor] window graphics Message-ID: <4A4BBDD6.8090702@cherokeetel.net> I am new to Python and I'm looking for help on graphics in Python3.0. All the graphics libraries I've seen are far to complex (and don't seem compatible with 3. What I really need to know is two things (1) how to set up a graphic window and (2)how to plot a pixel. Basically that's all a "graphics package" needs. Is this the right group? Any help appreciated, David From afith13 at gmail.com Thu Jul 2 03:56:38 2009 From: afith13 at gmail.com (Andrew Fithian) Date: Wed, 1 Jul 2009 18:56:38 -0700 Subject: [Tutor] When are strings interned? In-Reply-To: <40af687b0907011843u48e0a08anf23af7230938b073@mail.gmail.com> References: <2n0n45lad89hadb0psvgdggika3tr3ahlq@4ax.com> <1246494575.31620.29.camel@bermanrl-desktop> <40af687b0907011843u48e0a08anf23af7230938b073@mail.gmail.com> Message-ID: <64fb0beb0907011856q11cf7d23w32c9661bd0d14952@mail.gmail.com> My guess is that Python sees the space and decides it isn't a short string so it doesn't get interned. I got the expected results when I used 'green_ideas' instead of 'green ideas'. -Drew On Wed, Jul 1, 2009 at 6:43 PM, Marc Tompkins wrote: > On Wed, Jul 1, 2009 at 5:29 PM, Robert Berman wrote: >> >> > >>> n = "colourless" >> > >>> o = "colourless" >> > >>> n == o >> > True >> > >>> n is o >> > True >> > >>> p = "green ideas" >> > >>> q = "green ideas" >> > >>> p == q >> > True >> > >>> p is q >> > False >> > >> > Why the difference? >> >> The string p is equal to the string q. The object p is not the object q. >> >> Robert > > Yes, but did you read his first example?? That one has me scratching my > head. > -- > www.fsrtechnologies.com > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From lie.1296 at gmail.com Thu Jul 2 13:21:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 02 Jul 2009 21:21:28 +1000 Subject: [Tutor] Need help with python game program In-Reply-To: References: <57b8984c0906301738w1fb0e660m6bb2123399f27a0e@mail.gmail.com> Message-ID: Luke Paireepinart wrote: > Please don't reply to messages like this. If you are starting a new > thread, send a new e-mail to tutor at python.org . > DO NOT start a thread by replying to another message. If you do, it > will bork on people's machines who use threaded e-mail readers. also, > please remove long, irrelevant quotations from your e-mails unless you > reference it. for example, the quoted text in your e-mail is at least > 10x longer than the actual content. > I believe mark already answered your question. > Thanks, > -Luke > > On Tue, Jun 30, 2009 at 7:38 PM, jonathan wallis > > wrote: > > My problem is simple, is their a way to make a variable equal > multiple numbers? Such as X = 5 through 10, and then the program > makes x equal something random 5 through 10, or something similar. And most importantly, don't top-post. Because it messes up reading order. Why is top-posting harmful? From gregor.lingl at aon.at Thu Jul 2 13:25:16 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Thu, 02 Jul 2009 13:25:16 +0200 Subject: [Tutor] window graphics In-Reply-To: <4A4BBDD6.8090702@cherokeetel.net> References: <4A4BBDD6.8090702@cherokeetel.net> Message-ID: <4A4C991C.5070905@aon.at> Hi David, Python 3 (preferably 3.1) has a very easy to use graphics module in the standard library: the turtle module. It has a lot of capabilities, but alas, its working with geometrical objects and doesn't allow to adress single pixels . Get started by writing: >>> from turtle import * >>> forward(100) You can find the docs in Python Docs' global module index You can find example scripts in the Demo directory of the source code distribution or here: http://svn.python.org/view/python/branches/py3k/Demo/turtle/ If you want to give it a try and need more information, please feel free to ask Regards, Gregor David H. Burns schrieb: > I am new to Python and I'm looking for help on graphics in Python3.0. > All the graphics libraries I've seen are far to complex (and don't > seem compatible with 3. What I really need to know is two things (1) > how to set up a graphic window and (2)how to plot a pixel. Basically > that's all a "graphics package" needs. Is this the right group? > > Any help appreciated, > > David > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From a.t.hofkamp at tue.nl Thu Jul 2 13:38:09 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 02 Jul 2009 13:38:09 +0200 Subject: [Tutor] window graphics In-Reply-To: <4A4BBDD6.8090702@cherokeetel.net> References: <4A4BBDD6.8090702@cherokeetel.net> Message-ID: <4A4C9C21.8000909@tue.nl> David H. Burns wrote: > I am new to Python and I'm looking for help on graphics in Python3.0. > All the graphics libraries I've seen are far to complex (and don't seem > compatible with 3. What I really need to know is two things (1) how to > set up a graphic window and (2)how to plot a pixel. Basically that's all > a "graphics package" needs. Is this the right group? For Python help it is, for specific GUI-toolkit related questions, the group for the toolkit that you use may be better. With respect to your question, it is too early to use Python 3.0. As you have found out already, most libraries don't support 3.0 yet. Also, most of the Python tutorials and documentation is written for Python 2. I'd recommend that you start with Python 2.6 instead. Once you understand the language, making the transition to Python 3 will be relatively easy. (and, starting with 2.6, the language is slowly changing towards 3, so by the time 2.8 or 2.9 is released, you'll be writing almost Python 3) Indeed, many graphics packages are complex, since they aim to give full GUI toolkit coverage so you can make full-blown graphic applications. However, when you restrict yourself to just drawing on a canvas, the toolkits are fairly simple and similar (at least the ones I have seen, PyGTK and a little PyQT). Most tutorials for the GUI toolkits start rendering lines at a canvas at some point, so take that as a starting point, and strip all the stuff you don't need. Another approach may be to use pygame instead of a GUI toolkit. Albert From alan.gauld at btinternet.com Thu Jul 2 16:07:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Jul 2009 15:07:44 +0100 Subject: [Tutor] window graphics References: <4A4BBDD6.8090702@cherokeetel.net> Message-ID: "David H. Burns" wrote > All the graphics libraries I've seen are far to complex (and don't seem > compatible with 3. See the other posts re the wisdom of using Python 3 at this stage, however.... > What I really need to know is two things (1) how to > set up a graphic window >>> from tkinter import * >>> tk = Tk() >>> c = Canvas(tk, height=100,width=100) >>> c.pack() >>> c.create_line(0,15,30,75) 1 >>> c.create_oval(50,70,80,90) 2 >>> tk.mainloop() 2)how to plot a pixel. Basically that's all a "graphics package" needs. There is no pixel method per say but you can plot a single pixel sized oval. c.create_oval(4,4,4,4) Which is hard to see but here is a fuller example: >>> tk = Tk() >>> c = Canvas(tk, height=100,width=100) >>> c.pack() >>> for x in range(25,50): c.create_oval(x,x,x,x) >>> tk.mainloop() 3) Is this the right group? Yes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From alan.gauld at btinternet.com Thu Jul 2 16:10:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Jul 2009 15:10:13 +0100 Subject: [Tutor] IDLE 3.0 menu weirdness Message-ID: I tried posting this on the IDLE list but got no replies so.... I've been updating my online tutorial to Python v3. I've come across a weird "feature" of IDLE 3: The menus show as a pair of up/down arrows! Clicking the arrows does nothing obvious. If you select a menu and then hit the letter of the menu item it works OK but you can't see it on screen so can't use the mouse. This is a real pain! Has anyone else found this? Or is it just me? And does anyone know what to do to fix it ? I'm using Windows XP Pro SP2 and Python 3.0 >>> import sys >>> sys.version '3.0 (r30:67503, Dec 11 2008, 09:05:16) [MSC v.1500 32 bit (Intel)]' >>> IDLE for 2.5.1 works fine on the same machine -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From kent37 at tds.net Thu Jul 2 21:44:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 2 Jul 2009 15:44:32 -0400 Subject: [Tutor] window graphics In-Reply-To: <4A4BBDD6.8090702@cherokeetel.net> References: <4A4BBDD6.8090702@cherokeetel.net> Message-ID: <1c2a2c590907021244l1ac11598o316fac2c58e724e2@mail.gmail.com> On Wed, Jul 1, 2009 at 3:49 PM, David H. Burns wrote: > I am new to Python and I'm looking for help on graphics in Python3.0. All > the graphics libraries I've seen are far to complex (and don't seem > compatible with 3. What I really need to know is two things (1) how to set > up a graphic window and (2)how to plot a pixel. Basically that's all a > "graphics package" needs. Why do you want to plot single pixels? Drawing single pixels directly to a window is likely to be too slow for any substantive project. Kent From kent37 at tds.net Fri Jul 3 04:45:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 2 Jul 2009 22:45:26 -0400 Subject: [Tutor] window graphics In-Reply-To: <4A4D4DEC.8080903@cherokeetel.net> References: <4A4BBDD6.8090702@cherokeetel.net> <1c2a2c590907021244l1ac11598o316fac2c58e724e2@mail.gmail.com> <4A4D4DEC.8080903@cherokeetel.net> Message-ID: <1c2a2c590907021945i4c9fb80es83373fd46c272b17@mail.gmail.com> Forwarding to the list with my reply... On Thu, Jul 2, 2009 at 8:16 PM, David H. Burns wrote: > I don't necessarily want to plot single pixels. I'm not at all sure what > "directly" means in this context. "Plotting" to the screen involves sending > data to a software algorithm which invokes the appropriate hardware to "turn > on" the pixel. What I want is a simple and versatile way of displaying > graphics. The ability to display a single pixel when desired seems necessary > for that. I don't see that plotting single pixel would be slower than any > other method, be cause at some point in any graphics package some algorithm > has to do exactly that. It is true that modern graphics cards are > complicated and have their own processors which allow many "built in" > features using both hardware and software algorithms. So ?it may be that > what I think I want to do not the most efficient way to use them. But these > cards musts be addressed by some software routine. I guess that is what I am > looking for. My point is, you should look for a higher-level of interface than single pixels. What do you want to plot? Bitmap images? Graphs and charts? Sprites? Pygame and Pyglets and PIL will help to create and draw bitmaps and sprites. PyOpenGL is perhaps the closest to the hardware. matplotlib and a host of others are good for graphs and charts. There are several good 3-D rendering programs for python Tkinter Canvas lets you draw basic shapes etc Kent From dorjetarap at googlemail.com Fri Jul 3 10:58:52 2009 From: dorjetarap at googlemail.com (karma) Date: Fri, 3 Jul 2009 10:58:52 +0200 Subject: [Tutor] printing tree structure Message-ID: Hi all , I have a nested list in the structure [root,[leftSubtree],[RightSubtree]] that I want to print out. I was thinking that a recursive solution would work here, but so far I can't quite get it working. This is what I have so far: Can someone suggest whether this is suited to a recursive solution and if so, what am I doing wrong. Thanks >>> L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]] >>> def printTree(L): for i in L: if isinstance(i,str): print 'Root: ', i else: print '--Subtree: ', i printTree(i) >>> printTree(L) Root: a --Subtree: ['b', ['d', [], []], ['e', [], []]] Root: b --Subtree: ['d', [], []] Root: d --Subtree: [] --Subtree: [] --Subtree: ['e', [], []] # this shouldn't be here Root: e --Subtree: [] --Subtree: [] --Subtree: ['c', ['f', [], []], []] Root: c --Subtree: ['f', [], []] Root: f --Subtree: [] --Subtree: [] --Subtree: [] From washakie at gmail.com Fri Jul 3 13:33:23 2009 From: washakie at gmail.com (John [H2O]) Date: Fri, 3 Jul 2009 04:33:23 -0700 (PDT) Subject: [Tutor] creating a dict-like class - asigning variables... this one may take some thought ; ) In-Reply-To: <20090528134347.2fae12c7@o> References: <23759398.post@talk.nabble.com> <20090528134347.2fae12c7@o> Message-ID: <24321728.post@talk.nabble.com> spir wrote: > > > What you're looking for is a dictionary... > s = {"cheese":"Brie", "country":"France", ...} > > Or maybe a kind of object type that works ~ like a dict, but with object > syntax (get rid of {} and "" for keys). Example: > > class Stuff(object): > def __iter__(self): > return iter(self.__dict__.items()) > def items(self): > return self.__dict__ > > stuff = Stuff() > stuff.cheese="Brie" > stuff.country="France" > print stuff.cheese, stuff.country > print stuff.items() > for st in stuff: > print " ", st > ==> > Brie France > {'cheese': 'Brie', 'country': 'France'} > ('cheese', 'Brie') > ('country', 'France') > > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Denis, This is working, but what would be ideal is to have 'best of both' worlds. Is there a way to combine this class with a dict, so that I can do both: %S = Stuff() %S['this'] = 'is great' and then: %S.this 'is great' But also, be able to change it so that: %S.this = 'is even better' and yet still: %S['this'] 'is even better' Thanks! -- View this message in context: http://www.nabble.com/creating-a-dict-like-class---asigning-variables...-this-one-may-take-some-thought--%29-tp23759398p24321728.html Sent from the Python - tutor mailing list archive at Nabble.com. From lie.1296 at gmail.com Fri Jul 3 13:45:10 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 03 Jul 2009 21:45:10 +1000 Subject: [Tutor] printing tree structure In-Reply-To: References: Message-ID: karma wrote: > Hi all , > > I have a nested list in the structure > [root,[leftSubtree],[RightSubtree]] that I want to print out. I was > thinking that a recursive solution would work here, but so far I can't > quite get it working. This is what I have so far: > > Can someone suggest whether this is suited to a recursive solution and > if so, what am I doing wrong. > > Thanks > >>>> L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]] >>>> def printTree(L): > for i in L: > if isinstance(i,str): > print 'Root: ', i > else: > print '--Subtree: ', i > printTree(i) > > >>>> printTree(L) > Root: a > --Subtree: ['b', ['d', [], []], ['e', [], []]] > Root: b > --Subtree: ['d', [], []] > Root: d > --Subtree: [] > --Subtree: [] > --Subtree: ['e', [], []] # this shouldn't be here Why shouldn't it be there? Look more closely: Root: b --Subtree: ['d', [], []] ... --Subtree: ['e', [], []] ... The program recurse correctly, however the way you're printing it is misleading. When printing trees with arbitrary depth, you usually want to keep track of the recursion depth. Something like this: def print_tree(tree, depth=0): ... print_tree(node, depth + 1) ... From lie.1296 at gmail.com Fri Jul 3 14:21:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 03 Jul 2009 22:21:28 +1000 Subject: [Tutor] creating a dict-like class - asigning variables... this one may take some thought ; ) In-Reply-To: <24321728.post@talk.nabble.com> References: <23759398.post@talk.nabble.com> <20090528134347.2fae12c7@o> <24321728.post@talk.nabble.com> Message-ID: John [H2O] wrote: > > > spir wrote: >> >> What you're looking for is a dictionary... >> s = {"cheese":"Brie", "country":"France", ...} >> >> Or maybe a kind of object type that works ~ like a dict, but with object >> syntax (get rid of {} and "" for keys). Example: >> >> class Stuff(object): >> def __iter__(self): >> return iter(self.__dict__.items()) >> def items(self): >> return self.__dict__ >> >> stuff = Stuff() >> stuff.cheese="Brie" >> stuff.country="France" >> print stuff.cheese, stuff.country >> print stuff.items() >> for st in stuff: >> print " ", st >> ==> >> Brie France >> {'cheese': 'Brie', 'country': 'France'} >> ('cheese', 'Brie') >> ('country', 'France') >> >> >> Denis >> ------ >> la vita e estrany >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > Denis, > > This is working, but what would be ideal is to have 'best of both' worlds. > Is there a way to combine this class with a dict, so that I can do both: If you want to control attribute access, override its __getattr__ and __setattr__. If you want to make a dict lookalike, override its __getitem__ and __setitem__ or inherit from dict. Knowing this, you can do this: class SuperDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value >>> S = SuperDict() >>> S.foo = 42 >>> S['bar'] = 100 >>> S.bar 100 >>> S['foo'] 42 >>> S.items() [('foo', 42), ('bar', 100)] >>> S['this'] = 'is great' >>> S.this 'is great' >>> S.this = 'is even better' >>> S['this'] 'is even better' From alan.gauld at btinternet.com Fri Jul 3 15:09:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Jul 2009 14:09:58 +0100 Subject: [Tutor] printing tree structure References: Message-ID: "karma" wrote > thinking that a recursive solution would work here, but so far I can't > quite get it working. This is what I have so far: > > Can someone suggest whether this is suited to a recursive solution and Yes certainly > if so, what am I doing wrong. >>>> L = ['a', ['b', ['d', [], [] ], ['e', [], [] ] ], ['c', ['f', [], [] ], [] ] ] >>>> def printTree(L): > for i in L: > if isinstance(i,str): > print 'Root: ', i > else: > print '--Subtree: ', i > printTree(i) > >>>> printTree(L) > Root: a > --Subtree: ['b', ['d', [], []], ['e', [], []]] > Root: b > --Subtree: ['d', [], []] > Root: d > --Subtree: [] > --Subtree: [] This is the end of the recursive call to printTree( ['d', [ [], [] ] ] > --Subtree: ['e', [], []] # this shouldn't be here This is the next element in printTree( ['d', [], []], ['e', [], []] ) > Root: e This is the start of printTree( ['e', [], [] ] ) > --Subtree: [] > --Subtree: [] Now why do you think the line you highlighted is an error? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dorjetarap at googlemail.com Fri Jul 3 15:21:37 2009 From: dorjetarap at googlemail.com (karma) Date: Fri, 3 Jul 2009 15:21:37 +0200 Subject: [Tutor] printing tree structure In-Reply-To: References: Message-ID: Thanks all for the feedback. As you all rightly pointed out, I was confusing myself by not keeping a track of the recursion depth. Thanks again 2009/7/3 Alan Gauld : > > "karma" wrote > >> thinking that a recursive solution would work here, but so far I can't >> quite get it working. This is what I have so far: >> >> Can someone suggest whether this is suited to a recursive solution and > > Yes certainly > >> if so, what am I doing wrong. > >>>>> L = ['a', > > ? ? ? ? ? ? ? ? ? ?['b', ? ? ? ? ? ? ? ? ? ? ? ? ?['d', [], [] ], > ? ? ? ? ? ? ? ?['e', [], [] ] > ? ? ? ? ? ? ? ? ? ? ], ? ? ? ? ? ? ? ? ? ?['c', > ?['f', [], [] ], ? ? ? ? ? ? ? ? ? ? ? ? ?[] > ? ? ? ? ? ? ? ? ? ? ] > ? ? ? ? ? ? ? ? ?] > >>>>> def printTree(L): >> >> for i in L: >> ? ? ? ? ?if isinstance(i,str): >> ? ? ? ? ? ? ? print 'Root: ', i >> ? ? ? ? ?else: >> ? ? ? ? ? ? ? ?print '--Subtree: ', i >> ? ? ? ? ? ? ? ?printTree(i) >> > >>>>> printTree(L) >> >> Root: ?a >> --Subtree: ?['b', ['d', [], []], ['e', [], []]] >> Root: ?b >> --Subtree: ?['d', [], []] >> Root: ?d >> --Subtree: ?[] >> --Subtree: ?[] > > This is the end of the recursive call to printTree( ['d', [ [], [] ] ] > >> --Subtree: ?['e', [], []] # this shouldn't be here > > This is the next element in printTree( ['d', [], []], ['e', [], []] ) > >> Root: ?e > > This is the start of printTree( ['e', [], [] ] ?) > >> --Subtree: ?[] >> --Subtree: ?[] > > Now why do you think the line you highlighted is an error? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From angusr at bigfoot.com Fri Jul 3 15:23:12 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Fri, 03 Jul 2009 14:23:12 +0100 Subject: [Tutor] Floor and modulus for complex arguments Message-ID: I'm a little confused by: (i) the definition of the modulus and floor division functions for complex arguments; (ii) the fact that these functions for complex arguments are now "deprecated"; and (iii) the fact that the math.floor() function is not defined at all for a complex argument. If I were thinking about this from scratch (in the context of mathematics, rather than any particular programming language), I /think/ I would be naturally inclined to define: floor(x + yj) = floor(x) + floor(y)j for all real x, y z % w = z - floor(z / w) * w for all complex z, w (!= 0) These seem like they would be mathematically useful definitions (e.g. in algebraic number theory, where one has to find the "nearest" Gaussian integer multiple of one Gaussian integer to another - I forget the details, but it has something to do with norms and Euclidean domains), and I don't understand why Python doesn't do it this way, rather than first defining it a different way (whose mathematical usefulness is not immediately apparent to me) and then "deprecating" the whole thing! It seems like a wasted opportunity - but am I missing something? Has there been heated debate about this (e.g. in the context of Python 3, where the change to the division operator has apparently already provoked heated debate)? Also, by the way, is there some obvious reason for Python's use of the notation x + yj, rather than the more standard (except perhaps among electrical engineers) x + yi? -- Angus Rodgers From dhburns at cherokeetel.net Fri Jul 3 03:59:01 2009 From: dhburns at cherokeetel.net (David H. Burns) Date: Thu, 02 Jul 2009 20:59:01 -0500 Subject: [Tutor] window graphics In-Reply-To: References: Message-ID: <4A4D65E5.3040004@cherokeetel.net> Thanks, Alan, With the Python3.0, I have installed, he entry "from tkinter import *" doesn't produce any error message, but "tk = TK()" results in "NameError: 'TK' is not defined". Also for the word "canvas" As you suggest, I probably need to start with a 2.x version. From yashkochar at gmail.com Fri Jul 3 13:18:39 2009 From: yashkochar at gmail.com (Yash) Date: Fri, 3 Jul 2009 07:18:39 -0400 Subject: [Tutor] IDLE 3.0 menu weirdness Message-ID: Alan, I do not observe the problem on my installation of Python 3.0.1 (r301:69561, Feb 13 2009, 20:04:18) [MSC v.1500 32 bit (Intel)] on Win Vista or on Win XP SP 3 I don't see any arrows. Also the shortcut keywords work fine and I am able to use the mouse freely. The only problem I get is that after I exit the IDLE, the pythonw.exe process still keeps running. I have to manually kill the process before I can launch the IDLE again. Yash > > ---------- Forwarded message ---------- > From:?"Alan Gauld" > To:?tutor at python.org > Date:?Thu, 2 Jul 2009 15:10:13 +0100 > Subject:?[Tutor] IDLE 3.0 menu weirdness > I tried posting this on the IDLE list but got no replies so.... > > I've been updating my online tutorial to Python v3. > I've come across a weird "feature" of IDLE 3: > The menus show as a pair of up/down arrows! Clicking the arrows does nothing obvious. > > If you select a menu and then hit the letter of the menu item it works OK but you can't see it on screen so can't use the mouse. This is a real pain! Has anyone else found this? Or is it just me? > And does anyone know what to do to fix it ? > > I'm using Windows XP Pro SP2 and Python 3.0 > >>>> import sys >>>> sys.version > > '3.0 (r30:67503, Dec 11 2008, 09:05:16) [MSC v.1500 32 bit (Intel)]' >>>> > > IDLE for 2.5.1 works fine on the same machine > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/l2p/ > From davea at dejaviewphoto.com Fri Jul 3 13:25:51 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Fri, 03 Jul 2009 07:25:51 -0400 Subject: [Tutor] printing tree structure In-Reply-To: References: Message-ID: <4A4DEABF.3060604@dejaviewphoto.com> karma wrote: > Hi all , > > I have a nested list in the structure > [root,[leftSubtree],[RightSubtree]] that I want to print out. I was > thinking that a recursive solution would work here, but so far I can't > quite get it working. This is what I have so far: > > Can someone suggest whether this is suited to a recursive solution and > if so, what am I doing wrong. > > Thanks > > >>>> L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]] >>>> def printTree(L): >>>> > for i in L: > if isinstance(i,str): > print 'Root: ', i > else: > print '--Subtree: ', i > printTree(i) > > > >>>> printTree(L) >>>> > Root: a > --Subtree: ['b', ['d', [], []], ['e', [], []]] > Root: b > --Subtree: ['d', [], []] > Root: d > --Subtree: [] > --Subtree: [] > --Subtree: ['e', [], []] # this shouldn't be here > Root: e > --Subtree: [] > --Subtree: [] > --Subtree: ['c', ['f', [], []], []] > Root: c > --Subtree: ['f', [], []] > Root: f > --Subtree: [] > --Subtree: [] > --Subtree: [] > > Using tabs in Python source code is never a good idea, and mixing tabs and spaces is likely to cause real problems, sometimes hard to debug. That's not the problem here, but I wanted to mention it anyway. The problem you have is the hierarchy doesn't show in the printout. There are a few ways to indicate it, but the simplest is indentation, the same as for Python source code. Once things are indented, you'll see that the line you commented as "this shouldn't be here" is correct after all. Add an additional parameter to the function to indicate level of indenting. Simplest way is to simply pass a string that's either 0 spaces, 4 spaces, etc. L = ['a', ['b', ['d', [], []], ['e', [], []]], ['c', ['f', [], []], []]] def printTree(L, indent=""): for i in L: if isinstance(i,str): print indent, 'Root: ', i else: print indent, '--Subtree: ', i printTree(i, indent+" ") printTree(L) Root: a --Subtree: ['b', ['d', [], []], ['e', [], []]] Root: b --Subtree: ['d', [], []] Root: d --Subtree: [] --Subtree: [] --Subtree: ['e', [], []] Root: e --Subtree: [] --Subtree: [] --Subtree: ['c', ['f', [], []], []] Root: c --Subtree: ['f', [], []] Root: f --Subtree: [] --Subtree: [] --Subtree: [] Now I don't know if that's what your list of lists was supposed to mean, but at least it shows the structure of your printTree() loop. DaveA From angus at bigfoot.com Fri Jul 3 13:46:06 2009 From: angus at bigfoot.com (Angus Rodgers) Date: Fri, 03 Jul 2009 12:46:06 +0100 Subject: [Tutor] When are strings interned? In-Reply-To: References: Message-ID: This is partly a test to see if I can reply in the correct format to a message in the tutor list (which I receive in digest format). >Date: Thu, 02 Jul 2009 20:39:28 +1000 >From: Lie Ryan > >Angus Rodgers wrote: >[...] >>>>> p = "green ideas" >>>>> q = "green ideas" >>>>> p == q >> True >>>>> p is q >> False >[...] >In this particular case, the reason is because "colourless" can be used >as an identifier. >[...] Identifiers cannot contain spaces, that's why green ideas are >not interned. That is very clear, thanks. Presumably a different optimisation is going on here: >>> "green ideas" is "green ideas" True [Does it create confusion to quote a dialogue with the interpreter in this way? The >>> looks like an instance of e-mail quotation.] >And... have I told you not to rely on this behavior? NEVER rely on this >implementation details. Once you get bitten by it, you'll regret it. Noted! -- Angus Rodgers From angusr at bigfoot.com Fri Jul 3 15:43:21 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Fri, 03 Jul 2009 14:43:21 +0100 Subject: [Tutor] When are strings interned? In-Reply-To: References: Message-ID: This is partly a test to see if I can reply in the correct format to a message in the tutor list (which I receive in digest format). >Date: Thu, 02 Jul 2009 20:39:28 +1000 >From: Lie Ryan > >Angus Rodgers wrote: >[...] >>>>> p = "green ideas" >>>>> q = "green ideas" >>>>> p == q >> True >>>>> p is q >> False >[...] >In this particular case, the reason is because "colourless" can be used >as an identifier. >[...] Identifiers cannot contain spaces, that's why green ideas are >not interned. That is very clear, thanks. Presumably a different optimisation is going on here: >>> "green ideas" is "green ideas" True [Does it create confusion to quote a dialogue with the interpreter in this way? The >>> looks like an instance of e-mail quotation.] >And... have I told you not to rely on this behavior? NEVER rely on this >implementation details. Once you get bitten by it, you'll regret it. Noted! -- Angus Rodgers From tim.peters at gmail.com Fri Jul 3 16:18:23 2009 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 3 Jul 2009 10:18:23 -0400 Subject: [Tutor] Floor and modulus for complex arguments In-Reply-To: References: Message-ID: <1f7befae0907030718x150c7ff1rd372cbb865dee0d5@mail.gmail.com> [Angus Rodgers] > I'm a little confused by: (i) the definition of the modulus and > floor division functions for complex arguments; Perhaps you're confused by the current definitions simply because they don't make good sense. > (ii) the fact that these functions for complex arguments are > now "deprecated"; And they're deprecated /because/ they never made good sense. > and (iii) the fact that the math.floor() function is not defined > at all for a complex argument. The math module consists mostly of Python wrappers around the C functions defined by the C standard in C's math.h. C doesn't define floor() for complex numbers, so neither does Python's math.floor(). > If I were thinking about this from scratch (in the context of > mathematics, rather than any particular programming language), > I /think/ I would be naturally inclined to define: > > ?floor(x + yj) = floor(x) + floor(y)j ? ? for all real x, y > > ?z % w = z - floor(z / w) * w ? ?for all complex z, w (!= 0) > > These seem like they would be mathematically useful definitions > (e.g. in algebraic number theory, where one has to find the > "nearest" Gaussian integer multiple of one Gaussian integer to > another - I forget the details, but it has something to do with > norms and Euclidean domains), and I don't understand why Python > doesn't do it this way, rather than first defining it a different > way (whose mathematical usefulness is not immediately apparent > to me) and then "deprecating" the whole thing! ?It seems like > a wasted opportunity - but am I missing something? My guess: that in the absence of a /compelling/ reason to add something, it's best to leave it out. That you vaguely believe there might be "a reason" for defining complex floor in a particular more-or-less arbitrary way, but "forget the details" as to why /maybe/ that /might/ be useful ... well, that's not exactly compelling ;-) > Has there been heated debate about this (e.g. in the context > of Python 3, where the change to the division operator has > apparently already provoked heated debate)? Few people care about complex numbers in Python, and so no, there was no heated debate about this. > Also, by the way, is there some obvious reason for Python's use > of the notation x + yj, rather than the more standard (except > perhaps among electrical engineers) x + yi? When complex numbers were first added to Python, there /was/ heated debate about how to spell complex literals. Guido got weary of the debate, but didn't see a compelling reason to prefer "i" or "j", so left it to a vote on comp.lang.python. "j" got more votes. See? There's nothing "complex" about any of this after all ;-) From lie.1296 at gmail.com Fri Jul 3 16:25:13 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 04 Jul 2009 00:25:13 +1000 Subject: [Tutor] Floor and modulus for complex arguments In-Reply-To: References: Message-ID: Angus Rodgers wrote: > I'm a little confused by: (i) the definition of the modulus and > floor division functions for complex arguments; (ii) the fact > that these functions for complex arguments are now "deprecated"; > and (iii) the fact that the math.floor() function is not defined > at all for a complex argument. maybe because math module is specifically designed NOT to support complex number. For which cmath (complex math) is the appropriate module. But even cmath doesn't have floor(). > > If I were thinking about this from scratch (in the context of > mathematics, rather than any particular programming language), > I /think/ I would be naturally inclined to define: > > floor(x + yj) = floor(x) + floor(y)j for all real x, y > > z % w = z - floor(z / w) * w for all complex z, w (!= 0) I'm not a mathematician, and I understand zilch about complex numbers. But looking literally at your definition, python 2.5 seems to define complex mod complex as you have defined: >>> import math >>> def floor(comp): ... return math.floor(comp.real) + math.floor(comp.imag) * 1j ... >>> def mod(z, w): ... return z - floor(z / w) * w ... >>> mod(10.4j+5.1, 5.2j+3.2) (1.8999999999999995+5.2000000000000002j) >>> (10.4j+5.1) % (5.2j+3.2) __main__:1: DeprecationWarning: complex divmod(), // and % are deprecated (1.8999999999999995+5.2000000000000002j) > These seem like they would be mathematically useful definitions > (e.g. in algebraic number theory, where one has to find the > "nearest" Gaussian integer multiple of one Gaussian integer to > another - I forget the details, but it has something to do with > norms and Euclidean domains), and I don't understand why Python > doesn't do it this way, rather than first defining it a different > way (whose mathematical usefulness is not immediately apparent > to me) and then "deprecating" the whole thing! It seems like > a wasted opportunity - but am I missing something? > > Has there been heated debate about this (e.g. in the context > of Python 3, where the change to the division operator has > apparently already provoked heated debate)? There is this: http://mail.python.org/pipermail/python-dev/2002-April/023251.html http://mail.python.org/pipermail/python-dev/2002-April/023259.html and the justification seems to be related to the grand unified numeric type. Apparently this is the reason given: """ Update of /cvsroot/python/python/dist/src/Objects In directory usw-pr-cvs1:/tmp/cvs-serv7877 Modified Files: complexobject.c Log Message: SF bug #543387. Complex numbers implement divmod() and //, neither of which makes one lick of sense. Unfortunately this is documented, so I'm adding a deprecation warning now, so we can delete this silliness, oh, around 2005 or so. Bugfix candidate (At least for 2.2.2, I think.) """ > Also, by the way, is there some obvious reason for Python's use > of the notation x + yj, rather than the more standard (except > perhaps among electrical engineers) x + yi? I'm not a mathematician, and I understand little about complex numbers. But it seems the reason is because when the decision was made, nobody in the devteam understand the reasoning behind complex numbers implementing the divmod, //, and % as such, and caused it to be removed due to being "makes no sense". Perhaps if you can convince the devteam about the math behind complex mod complex, this feature can be reintroduced. FWIW it has been 5+ years and nobody seems to complain before, it seems complex mod complex must have been very rarely used. From lie.1296 at gmail.com Fri Jul 3 16:57:48 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 04 Jul 2009 00:57:48 +1000 Subject: [Tutor] When are strings interned? In-Reply-To: References: Message-ID: Angus Rodgers wrote: > Presumably a different optimisation is going on here: > >>>> "green ideas" is "green ideas" > True You're correct, there is another layer of optimization, now related to constant string caching. The caching sometimes happens, sometimes not, depending on a very intricate implementation detail. It's difficult to explain, better see it yourself. Regard the following interpreter session as a lesson to not bother on implementation details: Python 2.6.2 (r262:71600, Jun 12 2009, 06:02:06) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 'foo bar' >>> b = 'foo bar' >>> a is b False >>> def foo(): ... c = 'foo bar' ... print a is c ... print b is c ... >>> foo() False False >>> # OK, so is it always False? ... # Think again... ... >>> def foo(): ... d = 'foo bar' ... e = 'foo bar' ... print d is e ... >>> foo() True >>> exit() $ cat test.py a = 'foo bar' b = 'foo bar' print a is b $ python test.py True $ # wasn't the same test False in the interactive $ # interpreter earlier? $ python Python 2.6.2 (r262:71600, Jun 12 2009, 06:02:06) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 'foo bar' >>> b = 'foo bar' >>> a is b False >>> # since a is b is equivalent to 'foo bar' is 'foo bar'. ... # And it is False, then this should also be False: ... >>> 'foo bar' is 'foo bar' True >>> # it seems not... I've only started with 'foo bar'. It is easy to continue further on with many other oddities involving long strings without spaces, other immutables, etc, etc, etc. > [Does it create confusion to quote a dialogue with the interpreter > in this way? The >>> looks like an instance of e-mail quotation.] > >> And... have I told you not to rely on this behavior? NEVER rely on this >> implementation details. Once you get bitten by it, you'll regret it. > > Noted! Oh, need I to remind that never to rely on any of this behaviors. From metolone+gmane at gmail.com Fri Jul 3 17:10:45 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 3 Jul 2009 08:10:45 -0700 Subject: [Tutor] window graphics References: <4A4D65E5.3040004@cherokeetel.net> Message-ID: "David H. Burns" wrote in message news:4A4D65E5.3040004 at cherokeetel.net... > Thanks, Alan, > > With the Python3.0, I have installed, he entry "from tkinter import *" > doesn't produce any error message, but "tk = TK()" results in "NameError: > 'TK' is not defined". Also for the word "canvas" > > As you suggest, I probably need to start with a 2.x version. Python is case-sensitive. Try "tk = Tk()" and "Canvas". -Mark From lie.1296 at gmail.com Fri Jul 3 17:23:43 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 04 Jul 2009 01:23:43 +1000 Subject: [Tutor] window graphics In-Reply-To: <4A4D65E5.3040004@cherokeetel.net> References: <4A4D65E5.3040004@cherokeetel.net> Message-ID: David H. Burns wrote: > Thanks, Alan, > > With the Python3.0, I have installed, he entry "from tkinter import *" > doesn't produce any error message, but "tk = TK()" results in > "NameError: 'TK' is not defined". Also for the word "canvas" Python is CaSe-SEnsITiVe. TK() is different from Tk() and canvas is different from Canvas. Also, Python 2.x's Tkinter has been renamed to python 3.x's tkinter From angusr at bigfoot.com Fri Jul 3 18:02:21 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Fri, 03 Jul 2009 17:02:21 +0100 Subject: [Tutor] Apology (was:When are strings interned?) In-Reply-To: References: Message-ID: >Date: Fri, 03 Jul 2009 12:46:06 +0100 >From: Angus Rodgers >To: tutor at python.org >Subject: Re: [Tutor] When are strings interned? >Message-ID: >Content-Type: text/plain; charset=us-ascii >[...] >Date: Fri, 03 Jul 2009 14:43:21 +0100 >From: Angus Rodgers >To: tutor at python.org >Subject: Re: [Tutor] When are strings interned? >Message-ID: >Content-Type: text/plain; charset=us-ascii >[...] I'm sorry about that. It's these new varifocal spectacles: even after more than two weeks, I still can't see properly with them! When I realised I'd posted using the non-existent e-mail address , I first posted an apology, to whoever might be using that address, thinking my post would be bounced to him. But my apology itself bounced. I then waited, until I saw that a message I posted later (about complex numbers) was included in the digest. This led me to conclude that my earlier message had (as I expected) not been accepted by the mailing list (because I didn't register using that address). So I reposted it, thinking that I had been care- ful, considerate, and patient. D'oh! -- Angus Rodgers From hyou00 at hotmail.com Fri Jul 3 16:46:33 2009 From: hyou00 at hotmail.com (hyou) Date: Fri, 3 Jul 2009 10:46:33 -0400 Subject: [Tutor] Popen problem with a pipe sign "|" Message-ID: Hello, I encountered this problem that when I'm using Popen to execute a DOS command "C:\...\devenv" solution.sln /build "Debug|Win32", it doesn't run anything. However, if I replace "Debug|Win32" with Debug, it works fine. If I use subprocess.call instead, it runs perfectly - however, I cannot find a way to control the output from subprocess.call.. Do you know how can I run the command with | sign correctly with popen? Or if that's not possible, can you give me a way to control the output from subprocess.call? Thanks a lot! Sincerely, Shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: From dhburns at cherokeetel.net Fri Jul 3 17:57:38 2009 From: dhburns at cherokeetel.net (David H. Burns) Date: Fri, 03 Jul 2009 10:57:38 -0500 Subject: [Tutor] window graphics In-Reply-To: References: Message-ID: <4A4E2A72.404@cherokeetel.net> Thanks. I had forgotten the case sensitivity. David From dhburns at cherokeetel.net Fri Jul 3 17:59:31 2009 From: dhburns at cherokeetel.net (David H. Burns) Date: Fri, 03 Jul 2009 10:59:31 -0500 Subject: [Tutor] window graphics In-Reply-To: References: Message-ID: <4A4E2AE3.7090608@cherokeetel.net> Thanks, I had forgotten the case sensitivity. David From alan.gauld at btinternet.com Fri Jul 3 19:28:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 3 Jul 2009 18:28:55 +0100 Subject: [Tutor] IDLE 3.0 menu weirdness References: Message-ID: "Yash" wrote > I do not observe the problem on my installation of > Python 3.0.1 > I don't see any arrows. > Also the shortcut keywords work fine Yes the shortcuts worked ok for me too, it was just the menus that were broken. I upgraded to v3.1 and everything is fine now. Definitely odd! > The only problem I get is that after I exit the IDLE, the pythonw.exe > process still keeps running. I have to manually kill the process > before I can launch the IDLE again. I didn't have that problem. Alan G. From sander.sweers at gmail.com Fri Jul 3 20:48:14 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 3 Jul 2009 20:48:14 +0200 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: References: Message-ID: 2009/7/3 hyou : > Do you know how can I run the command with | sign correctly with popen? Or > if that?s not possible, can you give me a way to control the output from > subprocess.call? subprocess.call does not support this but subprocess.Popen does. See Doug Hellmann's PMOTW which explains how to witk with stdin and stdout. http://blog.doughellmann.com/2007/07/pymotw-subprocess.html Greets Sander From dineshbvadhia at hotmail.com Fri Jul 3 21:09:08 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 3 Jul 2009 12:09:08 -0700 Subject: [Tutor] list comprehension problem Message-ID: I'm suffering from brain failure (or most likely just being brain less!) and need help to create a list comprehension for this problem: d is a list of integers: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1] Want to create a new list that adds the current number and the prior number, where the prior number is the accumulation of the previous numbers ie. dd = [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, 96] A brute force solution which works is: >>> dd = [] >>> y = d[0] >>> for i, x in enumerate(d): >>> y += x >>> dd.append(y) Is there a list comprehension solution? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Jul 3 21:22:30 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 03 Jul 2009 12:22:30 -0700 Subject: [Tutor] list comprehension problem In-Reply-To: References: Message-ID: On 7/3/2009 12:09 PM Dinesh B Vadhia said... > I'm suffering from brain failure (or most likely just being brain less!) > and need help to create a list comprehension for this problem: > > d is a list of integers: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, > 1, 6, 3, 5, 6, 11, 1] > > Want to create a new list that adds the current number and the prior > number, where the prior number is the accumulation of the previous > numbers ie. [ sum(d[:j]) for j in range(len(d)) ][1:] Emile > > dd = [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, > 84, 95, 96] > > A brute force solution which works is: > > >>> dd = [] > >>> y = d[0] > >>> for i, x in enumerate(d): > >>> y += x > >>> dd.append(y) > > Is there a list comprehension solution? > > Dinesh > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From angusr at bigfoot.com Fri Jul 3 21:37:09 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Fri, 03 Jul 2009 20:37:09 +0100 Subject: [Tutor] Floor and modulus for complex arguments In-Reply-To: References: Message-ID: >Date: Sat, 04 Jul 2009 00:25:13 +1000 >From: Lie Ryan >Message-ID: > >Angus Rodgers wrote: > >> I /think/ I would be naturally inclined to define: >> >> floor(x + yj) = floor(x) + floor(y)j for all real x, y >> >> z % w = z - floor(z / w) * w for all complex z, w (!= 0) > >I'm not a mathematician, and I understand zilch about complex numbers. >But looking literally at your definition, python 2.5 seems to define >complex mod complex as you have defined: > >>>> import math >>>> def floor(comp): >... return math.floor(comp.real) + math.floor(comp.imag) * 1j >... >>>> def mod(z, w): >... return z - floor(z / w) * w >... >>>> mod(10.4j+5.1, 5.2j+3.2) >(1.8999999999999995+5.2000000000000002j) >>>> (10.4j+5.1) % (5.2j+3.2) >__main__:1: DeprecationWarning: complex divmod(), // and % are deprecated >(1.8999999999999995+5.2000000000000002j) mod(z, w) and (z % w) will give the same result whenever (z / w).imag is >= 0 and < 1. In particular, if also (z / w).real is >= 1 and < 2, both expressions will be equal to z - w (as in this example). But in most cases they will give different results, e.g.: >>> z = 1.5 + 1.5j >>> mod(z, 1) (0.5+0.5j) >>> z % 1 (0.5+1.5j) >> These seem like they would be mathematically useful definitions >> (e.g. in algebraic number theory, where one has to find the >> "nearest" Gaussian integer multiple of one Gaussian integer to >> another - I forget the details, but it has something to do with >> norms and Euclidean domains) [...] >> >> Has there been heated debate about this (e.g. in the context >> of Python 3, where the change to the division operator has >> apparently already provoked heated debate)? > >There is this: >http://mail.python.org/pipermail/python-dev/2002-April/023251.html >http://mail.python.org/pipermail/python-dev/2002-April/023259.html I agree with Tim Peters that the original definition of complex // and % makes no sense. At least it makes no more sense to me than it does to him; and that was indeed the reason for my post. But I won't wax evangelical over my off-the-cuff definitions of floor (and implicitly //) and % for complex numbers, especially as the one application I only vaguely hinted at would actually need this instead: round(x + yj) = round(x) + round(y)j for all real x, y Or, in Python, something more like this (because unfortunately 'round' is built in): def cround(z): return complex(round(z.real), round(z.imag)) The details I omitted are here, in case anyone wants to know! "It is easy to see graphically that every complex number is within \frac{\sqrt 2}{2} units of a Gaussian integer. Put another way, every complex number (and hence every Gaussian integer) has a maximal distance of \frac{\sqrt 2}{2}\sqrt{N(z)} units to some multiple of z, where z is any Gaussian integer; this turns Z[i] into a Euclidean domain, where v(z) = N(z)." >But it seems the reason is because when the decision was made, nobody in >the devteam understand the reasoning behind complex numbers implementing >the divmod, //, and % as such, and caused it to be removed due to being >"makes no sense". Perhaps if you can convince the devteam about the math >behind complex mod complex, this feature can be reintroduced. FWIW it >has been 5+ years and nobody seems to complain before, it seems complex >mod complex must have been very rarely used. If I started to agitate for changes to a marginal and little-used feature of the language within days of starting to learn it, might I not quickly earn a reputation as a crank? 8-P I don't know how useful it would be to [re]define floor(), //, % and cround() for complex numbers. Not very, if nobody uses them! All I can say is that my suggested definitions seem to make more sense than the original definitions seem to. They do at least have an easily pictured geometrical interpretation. Imagine all multiples of the given non-zero complex number w by complex numbers of the form m + nj, where m and n are integers: they form an infinite grid of squares in the complex plane, and we are interested in which of these squares the other given complex number z falls into, or else we are interested in which vertex of the grid z lies closest to. -- Angus Rodgers From dineshbvadhia at hotmail.com Fri Jul 3 21:49:30 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 3 Jul 2009 12:49:30 -0700 Subject: [Tutor] list comprehension problem Message-ID: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1] and we want: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, 96] dd = [ sum(d[:j]) for j in range(len(d)) ][1:] gives: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95] Dinesh -------------------------------------------------------------------------------- Message: 6 Date: Fri, 03 Jul 2009 12:22:30 -0700 From: Emile van Sebille To: tutor at python.org Subject: Re: [Tutor] list comprehension problem Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 7/3/2009 12:09 PM Dinesh B Vadhia said... > I'm suffering from brain failure (or most likely just being brain less!) > and need help to create a list comprehension for this problem: > > d is a list of integers: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, > 1, 6, 3, 5, 6, 11, 1] > > Want to create a new list that adds the current number and the prior > number, where the prior number is the accumulation of the previous > numbers ie. [ sum(d[:j]) for j in range(len(d)) ][1:] Emile > > dd = [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, > 84, 95, 96] > > A brute force solution which works is: > > >>> dd = [] > >>> y = d[0] > >>> for i, x in enumerate(d): > >>> y += x > >>> dd.append(y) > > Is there a list comprehension solution? > > Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jul 3 22:21:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 3 Jul 2009 16:21:24 -0400 Subject: [Tutor] list comprehension problem In-Reply-To: References: Message-ID: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> On Fri, Jul 3, 2009 at 3:49 PM, Dinesh B Vadhia wrote: > d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1] > > and we want: > > [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, > 96] > dd = [ sum(d[:j]) for j in range(len(d)) ][1:] > > gives: > > [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95] In [9]: [ sum(d[:j+1]) for j in range(len(d)) ] Out[9]: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, 96] Kent From emile at fenx.com Fri Jul 3 22:37:54 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 03 Jul 2009 13:37:54 -0700 Subject: [Tutor] list comprehension problem In-Reply-To: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> Message-ID: On 7/3/2009 1:21 PM Kent Johnson said... > On Fri, Jul 3, 2009 at 3:49 PM, Dinesh B > Vadhia wrote: >> d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1] >> >> and we want: >> >> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, >> 96] >> dd = [ sum(d[:j]) for j in range(len(d)) ][1:] >> >> gives: >> >> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95] > > In [9]: [ sum(d[:j+1]) for j in range(len(d)) ] > Out[9]: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, > 78, 84, 95, 96] So, did we get an 'A'... Emile From cfuller084 at thinkingplanet.net Fri Jul 3 22:59:46 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 3 Jul 2009 15:59:46 -0500 Subject: [Tutor] list comprehension problem In-Reply-To: References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> Message-ID: <200907031559.47139.cfuller084@thinkingplanet.net> On Friday 03 July 2009 15:37, Emile van Sebille wrote: > On 7/3/2009 1:21 PM Kent Johnson said... > > > On Fri, Jul 3, 2009 at 3:49 PM, Dinesh B > > > > Vadhia wrote: > >> d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1] > >> > >> and we want: > >> > >> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, > >> 95, 96] > >> dd = [ sum(d[:j]) for j in range(len(d)) ][1:] > >> > >> gives: > >> > >> [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, > >> 95] > > > > In [9]: [ sum(d[:j+1]) for j in range(len(d)) ] > > Out[9]: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, > > 78, 84, 95, 96] > > So, did we get an 'A'... > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor The problem with these list comprehensions is that they have O(n**2) complexity. Whether they are faster or not depends on the speedup from the list comprehension and the length of the input. I'd be inclined to favor the linear for loop. Cheers From tim.peters at gmail.com Fri Jul 3 23:29:24 2009 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 3 Jul 2009 17:29:24 -0400 Subject: [Tutor] Floor and modulus for complex arguments In-Reply-To: References: Message-ID: <1f7befae0907031429y5a56f0do615b49ec88c7560c@mail.gmail.com> [Angus Rodgers] > ... > If I started to agitate for changes to a marginal and little-used > feature of the language within days of starting to learn it, might > I not quickly earn a reputation as a crank? ?8-P If that's your /goal/, it would be easier to rant about some imagined flaw in the ring of algebraic integers, and insist Guido was the head of a worldwide conspiracy to cover it up. James Harris doesn't have a copyright on inane babbling, after all ;-) From emile at fenx.com Sat Jul 4 00:02:18 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 03 Jul 2009 15:02:18 -0700 Subject: [Tutor] list comprehension problem In-Reply-To: <200907031559.47139.cfuller084@thinkingplanet.net> References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> <200907031559.47139.cfuller084@thinkingplanet.net> Message-ID: On 7/3/2009 1:59 PM Chris Fuller said... > > The problem with these list comprehensions is that they have O(n**2) > complexity. But, the more you work with them the more ease you'll develop at understanding and deploying them. I often find that a (quick) (perhaps complex) list comprehension is just what's needed vs a (less quick) (perhaps clarifying) refactoring. > Whether they are faster or not depends on the speedup from the > list comprehension and the length of the input. I suspect that list comprehensions are invariably faster when analogous algorithms are used. This doesn't mean it's the fastest way, only that they're faster than the same for loop. > I'd be inclined to favor the linear for loop. Yes, this one in particular gets slow quickly. I generally find non-comprehension solutions easier to (re)understand the more complex they get. OTOH, I've always had a passion for more compact code. Blame it on the combined 8kb program and data memory footprint we had to operate in when I got started. Emile From sander.sweers at gmail.com Sat Jul 4 00:40:42 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 4 Jul 2009 00:40:42 +0200 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: References: Message-ID: 2009/7/3 hyou : > Hi Sander, > > Thanks for the reply. However, the reason that I have to use subprocess.call is that if I use > subprocess.Popen, the pipe sign "|" will break the execution of the command (though I don't know > why). Do you know how can I put "|" correctly in Popen then? (The same command works fine both in > Command prompt and subprocess.call, but not .Popen) You create a Popen object for each program and redirect the stdout from program 1 to subprocess.PIPE. Now in program 2 you read the stdout from command 1 to the stdin. See below a simple example. p1 = subprocess.Popen('command1', stdout = subprocess.PIPE) p2 = subprovess.Popen('command2', stdin = p1.stdout) Greets Sander PS: Please make sure you also reply to the list. From dineshbvadhia at hotmail.com Sat Jul 4 00:54:42 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 3 Jul 2009 15:54:42 -0700 Subject: [Tutor] list comprehension problem In-Reply-To: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> Message-ID: Thanks Emile / Kent. The problem I see with this solution is that at each stage it is re-summing the j's instead of retaining a running total which the 'for-loop' method does ie. >>> dd = [] >>> y = d[0] >>> for i, x in enumerate(d): >>> y += x >>> dd.append(y) As the lists of integers get larger (mine are in the thousands of integers per list) the list comprehension solution will get slower. Do you agree? Dinesh From: Kent Johnson Sent: Friday, July 03, 2009 1:21 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] list comprehension problem On Fri, Jul 3, 2009 at 3:49 PM, Dinesh B Vadhia wrote: > d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, 1, 6, 3, 5, 6, 11, 1] > > and we want: > > [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, > 96] > dd = [ sum(d[:j]) for j in range(len(d)) ][1:] > > gives: > > [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95] In [9]: [ sum(d[:j+1]) for j in range(len(d)) ] Out[9]: [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, 78, 84, 95, 96] Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jul 4 01:17:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Jul 2009 00:17:43 +0100 Subject: [Tutor] list comprehension problem References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> Message-ID: "Dinesh B Vadhia" wrote > As the lists of integers get larger ... the list comprehension > solution will get slower. Do you agree? Yes thats why Chris said the linear loop solution is almost certainly faster in this case. However you could speed up the for loop significantly by missing out the call to enumerate(): >>> for x in d: >>> y += x >>> dd.append(y) Should give the same result... List Comprehensions are not always the best answer. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Sat Jul 4 01:19:04 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 03 Jul 2009 16:19:04 -0700 Subject: [Tutor] list comprehension problem In-Reply-To: References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> Message-ID: On 7/3/2009 3:54 PM Dinesh B Vadhia said... > Thanks Emile / Kent. > > The problem I see with this solution is that at each stage it is > re-summing the j's instead of retaining a running total which the > 'for-loop' method does ie. > > >>> dd = [] > >>> y = d[0] > >>> for i, x in enumerate(d): > >>> y += x > >>> dd.append(y) > > As the lists of integers get larger (mine are in the thousands of > integers per list) the list comprehension solution will get slower. Do > you agree? Yes, no doubt. Your original post asked only if there was a listcomp solution. There are probably listcomp solutions that are faster too. I've not tried looking. As a rule though, timing related optimizations are best done once a bottleneck is identified. It certainly doesn't hurt to develop the habit of writing clean efficient code, but I wouldn't normally look for better ways of getting something done once I'd written a working solution. In this case, IIRC, sum is highly efficient and for smaller lists (on today's CPUs small might be 1000's of entries) might work just fine. I wouldn't necessarily assume that the list comp is slower at a certain size without testing. I'd bet the listcomp is faster on short lists, and slower on long lists, but where the dividing line is could only be known by testing. If you're interested, look into the timeit module. Emile From emile at fenx.com Sat Jul 4 02:21:30 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 03 Jul 2009 17:21:30 -0700 Subject: [Tutor] list comprehension problem In-Reply-To: References: <1c2a2c590907031321l264693eapfd17036a05dfa0dc@mail.gmail.com> Message-ID: On 7/3/2009 4:19 PM Emile van Sebille said... > On 7/3/2009 3:54 PM Dinesh B Vadhia said... >> As the lists of integers get larger (mine are in the thousands of >> integers per list) the list comprehension solution will get slower. >> Do you agree? > > Yes, no doubt. Your original post asked only if there was a listcomp > solution. There are probably listcomp solutions that are faster too. > I've not tried looking. > > As a rule though, timing related optimizations are best done once a > bottleneck is identified. It certainly doesn't hurt to develop the > habit of writing clean efficient code, but I wouldn't normally look for > better ways of getting something done once I'd written a working > solution. In this case, IIRC, sum is highly efficient and for smaller > lists (on today's CPUs small might be 1000's of entries) might work just > fine. I wouldn't necessarily assume that the list comp is slower at a > certain size without testing. I'd bet the listcomp is faster on short > lists, and slower on long lists, but where the dividing line is could > only be known by testing. If you're interested, look into the timeit > module. OK -- I was interested. I found that for the comparable algorithms I tested, for loops are very slightly faster. As expected, the sum method would have very quickly been identified as a bottleneck. Here's the code: >>> from timeit import Timer >>> >>> for listlen in (1000,2000,3000,4000,5000): ... print 'Testing with listlen of %s' % listlen ... loop = """ ... import random ... d = range(%s) ... random.shuffle(d) ... ... def loop(intlist): ... dd = [] ... y=0 ... for x in intlist: ... y += x ... dd.append(y) ... return dd ... ... loop(d) ... """ % listlen ... listcomp=""" ... import random ... d = range(%s) ... random.shuffle(d) ... ... def listcomp(intlist): ... dd=[intlist[0]] ... [dd.append(dd[-1]+ii) for ii in intlist] ... return dd ... ... listcomp(d) ... """% listlen ... lcompsum=""" ... import random ... d = range(%s) ... random.shuffle(d) ... ... def lcompsum(intlist): ... return [ sum(intlist[:j+1]) for j in range(len(intlist)) ] ... ... lcompsum(d) ... """% listlen ... # test loop ... L=Timer(loop) ... print 'loop',L.timeit(100) ... # test the listcomp ... C=Timer(listcomp) ... print 'comp',C.timeit(100) ... # test the lcompsum ... S=Timer(lcompsum) ... print 'lsum',S.timeit(100) ... Testing with listlen of 1000 loop 0.173838574456 comp 0.187206195201 lsum 4.35129548588 Testing with listlen of 2000 loop 0.350709377868 comp 0.376994003428 lsum 16.9596619123 Testing with listlen of 3000 loop 0.52868730523 comp 0.5575624835 lsum 39.1358091601 Testing with listlen of 4000 loop 0.722962555297 comp 0.757179753293 lsum 69.0885824874 Testing with listlen of 5000 loop 0.932248931079 comp 0.961401798273 lsum 107.567347805 >>> ----- Emile From damontimm at gmail.com Sat Jul 4 02:24:40 2009 From: damontimm at gmail.com (Damon Timm) Date: Fri, 3 Jul 2009 20:24:40 -0400 Subject: [Tutor] fnmatch -or glob question Message-ID: <262679b50907031724m30a95dd4k718829012746e33d@mail.gmail.com> Hi - I am trying to find a group of thumbnail files for deletion -- the files all have similar naming structure (though the details vary). When the main file is deleted, I want all the little ones to go too. For example, here is a directory listing: DSC_0063.100.jpg DSC_0063.100x150.jpg DSC_0063.jpg DSC_0065.300.jpg DSC_0065.400x400.jpg DSC_0065.jpg Using os.path.splitext and os.path.split I am able to break the files down into the two parts I need: base = DSC_0065 ext = .jpg And I thought I could just construct something for glob or fnmatch like: glob.glob("DSC_0065*.jpg") --or-- fnmatch.fnmatch(file, "DSC_0065*.jpg") But I'm not getting anywhere. I feel like there is something I am missing in terms of using the wildcard correctly in the middle of a filename. Any ideas ? Thanks, Damon From bgailer at gmail.com Sat Jul 4 02:56:21 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 03 Jul 2009 20:56:21 -0400 Subject: [Tutor] list comprehension problem In-Reply-To: References: Message-ID: <4A4EA8B5.7060500@gmail.com> Dinesh B Vadhia wrote: > I'm suffering from brain failure (or most likely just being brain > less!) and need help to create a list comprehension for this problem: > > d is a list of integers: d = [0, 8, 4, 4, 4, 7, 2, 5, 1, 1, 5, 11, 11, > 1, 6, 3, 5, 6, 11, 1] > > Want to create a new list that adds the current number and the prior > number, where the prior number is the accumulation of the previous > numbers ie. > > dd = [0, 8, 12, 16, 20, 27, 29, 34, 35, 36, 41, 52, 63, 64, 70, 73, > 78, 84, 95, 96] > > A brute force solution which works is: > > >>> dd = [] > >>> y = d[0] > >>> for i, x in enumerate(d): > >>> y += x > >>> dd.append(y) > > Is there a list comprehension solution? Python has a reduce function that applies an operator (such as +) to successive elements of an iterable giving a single value (in your case that is 96). APL has both reduce and scan, where scan gives you exactly what you want. WIBNI Python had scan? -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Sat Jul 4 04:25:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 3 Jul 2009 22:25:17 -0400 Subject: [Tutor] fnmatch -or glob question In-Reply-To: <262679b50907031724m30a95dd4k718829012746e33d@mail.gmail.com> References: <262679b50907031724m30a95dd4k718829012746e33d@mail.gmail.com> Message-ID: <1c2a2c590907031925x688e746ueb93303c3bb561f7@mail.gmail.com> On Fri, Jul 3, 2009 at 8:24 PM, Damon Timm wrote: > And I thought I could just construct something for glob or fnmatch like: > > glob.glob("DSC_0065*.jpg") --or-- fnmatch.fnmatch(file, "DSC_0065*.jpg") Do you have the working directory set to the folder with the jpgs in it? If not, you have to give the full path to glob(). Kent From alan.gauld at btinternet.com Sat Jul 4 10:27:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Jul 2009 09:27:20 +0100 Subject: [Tutor] fnmatch -or glob question References: <262679b50907031724m30a95dd4k718829012746e33d@mail.gmail.com> Message-ID: "Damon Timm" wrote > And I thought I could just construct something for glob or fnmatch like: > > glob.glob("DSC_0065*.jpg") --or-- fnmatch.fnmatch(file, "DSC_0065*.jpg") > > But I'm not getting anywhere. Can you give is a clue as to what you are getting? What is happening and what do you experct to happen? Are you finding any files? some files? too many files? Do you get an error message? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From damontimm at gmail.com Sat Jul 4 13:37:01 2009 From: damontimm at gmail.com (Damon Timm) Date: Sat, 4 Jul 2009 07:37:01 -0400 Subject: [Tutor] fnmatch -or glob question In-Reply-To: References: <262679b50907031724m30a95dd4k718829012746e33d@mail.gmail.com> Message-ID: <262679b50907040437w10f5bb35q864be1a028db7bc5@mail.gmail.com> Hi Kent and Allen - thanks for the responses ... I was sure there was some part of the "search" I wasn't getting, but with your follow-up questions it seemed something else was amiss ... So, I went back to re-create the problem with some more python output to show you and realized my mistake. Sigh. All the files were DSC_00XX ... and then one I had chosen to test didn't have any thumbnails. So, of course, I wasn't getting any responses ... though, because the filenames were so close, I sure thought I should have been. Good lesson here is: check the variables ! My goal is to delete the main image plus its thumbnails in one fell swoop -- I plan to use fnmatch to do that (though glob works too). Unless there is something else I should consider? For those who stumble like me, here is what is working. Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from kissfist.read.models import Issue #custom model that stores issue info >>> import os, fnmatch, glob >>> i = Issue.objects.get(pk=1) # get the first issue (contains cover path) >>> i.cover.path '/media/uploads/issue-covers/DSC_0065.jpg' >>> working_dir, file_name = os.path.split(i.cover.path) >>> file_base, file_ext = os.path.splitext(file_name) >>> glob_text = file_base + "*" + file_ext >>> for f in os.listdir(working_dir): ... if fnmatch.fnmatch(f, glob_text): ... print f ... DSC_0065.400x400.jpg DSC_0065.jpg DSC_0065.300.jpg >>> os.chdir(working_dir) >>> glob.glob(glob_text) ['DSC_0065.400x400.jpg', 'DSC_0065.jpg', 'DSC_0065.300.jpg'] Thanks again. Damon On Sat, Jul 4, 2009 at 4:27 AM, Alan Gauld wrote: > > "Damon Timm" wrote > >> And I thought I could just construct something for glob or fnmatch like: >> >> glob.glob("DSC_0065*.jpg") --or-- fnmatch.fnmatch(file, "DSC_0065*.jpg") >> >> But I'm not getting anywhere. > > Can you give is a clue as to what you are getting? > What is happening and what do you experct to happen? > Are you finding any files? some files? too many files? > Do you get an error message? > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From angusr at bigfoot.com Sat Jul 4 14:26:12 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sat, 04 Jul 2009 13:26:12 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? Message-ID: Fear not, I won't post all my exercises to the Tutor list! But when I seem to be doing something a little elaborate, it seems a good idea to ask if I'm doing anything silly. In this exercise: (retention: 1 day) my /conscious/ worries are: (i) trapping the exception StandardError may, for all I know, be a daft thing to do; (ii) I'm not bothering to be consistent in my use of single and double string quotes (but I don't know how much difference this makes, to readability and/or reliability); (iii) some of my lines of code extend beyond 79 characters (but again, I don't know how much this matters); (iv) correlatively with (iii), my indentation perhaps looks a little extreme (perhaps suggesting a redesign, I don't know); (v) I'm bound to be doing other silly things that I don't even know about ("unknown unknowns"). Any comments? (I don't expect the Spanish Inquisition!) -- Angus Rodgers From wodemoneke at gmail.com Sat Jul 4 17:50:48 2009 From: wodemoneke at gmail.com (Daniel Woodhouse) Date: Sat, 4 Jul 2009 18:50:48 +0300 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: <4c0a037d0907040850r7874313cn4abacc7db5957950@mail.gmail.com> I had a look at your code, and refactored it a bit. See my modifications at http://python.pastebin.com/m50acb143 You'll noticed I removed one of your functions completely (it was unnecessary) and the get_dict() function is not so heavily nested. Some ideas: raw_input returns a string, so we can safely assume its a string. Whether or not its a valid name for a student is a different matter, and if you wish to check such things you may wish to look at the regular expression module (re). I wouldn't use eval as you did in the case, instead I did this to check the score is a valid int: try: val = int(val) except ValueError: print 'Invalid score' ValueError will catch invalid integers and we can ask the user to input again. Generally we should only capture Exceptions that we are expecting, though there are exceptions to this (no pun intended)... A lot of your code in get_dict() was repeated (basically the same operations to get the key and the value). You should try to avoid duplication if possible, either by putting the code in a seperate function, or just collecting everything at once as I have done. Regards, Daniel Woodhouse On Sat, Jul 4, 2009 at 3:26 PM, Angus Rodgers wrote: > > Fear not, I won't post all my exercises to the Tutor list! But > when I seem to be doing something a little elaborate, it seems a > good idea to ask if I'm doing anything silly. In this exercise: > > (retention: 1 day) > > my /conscious/ worries are: > > (i) trapping the exception StandardError may, for all I know, > be a daft thing to do; > > (ii) I'm not bothering to be consistent in my use of single and > double string quotes (but I don't know how much difference this > makes, to readability and/or reliability); > > (iii) some of my lines of code extend beyond 79 characters (but > again, I don't know how much this matters); > > (iv) correlatively with (iii), my indentation perhaps looks a > little extreme (perhaps suggesting a redesign, I don't know); > > (v) I'm bound to be doing other silly things that I don't even > know about ("unknown unknowns"). > > Any comments? (I don't expect the Spanish Inquisition!) > > -- > Angus Rodgers > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Jul 4 18:57:09 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 04 Jul 2009 18:57:09 +0200 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: References: Message-ID: <1246726629.5774.14.camel@infirit.homelinux.org> Again, You need to also post to the list!! On Fri, 2009-07-03 at 22:32 -0400, Shawn Gong wrote: > I see what you mean. However in my case the | sign simply constitute an > argument. I'm actually calling devenv.com, which is the MS VS2005's building > command. The whole command looks like: > "...\devenv.com" solution.sln /build "Debug|Win32" > If I sub "Debug|Win32" with Debug only, it works fine. But whenever I add > the |, nothing seems to run. Ah, ok now I get what your problem is. I do not know why that would not work. Can you show the actual code you have? Do you have the command in a list? See below an *untested* example, does this work? command = ['C:\\...\\devenv', 'solution.sln', '/build', 'Debug|Win32'] proc = subprocess.Popen(command, stdout=subporcess.PIPE, stderr=subporcess.PIPE, stdin=subporcess.PIPE) stdout, stderr = proc.communicate() From roadierich at googlemail.com Sat Jul 4 19:10:36 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 4 Jul 2009 18:10:36 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: 2009/7/4 Angus Rodgers : > > Fear not, I won't post all my exercises to the Tutor list! ?But > when I seem to be doing something a little elaborate, it seems a > good idea to ask if I'm doing anything silly. ?In this exercise: > > ? (retention: 1 day) > > my /conscious/ worries are: > > ?(i) trapping the exception StandardError may, for all I know, > be a daft thing to do; > > ?(ii) I'm not bothering to be consistent in my use of single and > double string quotes (but I don't know how much difference this > makes, to readability and/or reliability); > > (iii) some of my lines of code extend beyond 79 characters (but > again, I don't know how much this matters); > > ?(iv) correlatively with (iii), my indentation perhaps looks a > little extreme (perhaps suggesting a redesign, I don't know); > > ?(v) I'm bound to be doing other silly things that I don't even > know about ("unknown unknowns"). > > Any comments? (I don't expect the Spanish Inquisition!) > > -- > Angus Rodgers > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Lets consider how you handle your input. You get a string, from the user, then you pass it to eval, which runs it as if it was a python command. Consider if they put in something like the following: __import__('os').system("rm -rf /") If you know linux, you will know this is a bad thing. A similar idea on windows is __import__('os').system("format c: /q") In short, unless you really know what you're doing, never use eval(raw_input(...)) for the same reasons you should never use input(...), for in effect, that is exactly what you are using. In fact, the python 3.0 docs recommend that form (using the new name for raw_input), in expert scripts allowing interactive code entry. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From lie.1296 at gmail.com Sat Jul 4 20:14:12 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 05 Jul 2009 04:14:12 +1000 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: Angus Rodgers wrote: > > Any comments? (I don't expect the Spanish Inquisition!) > In addition to what others have mentioned: - use string formatting instead of concatenation as they're usually more readable (and faster too?): ans = raw_input(question + ' ' + true[0] + ' or ' + false[1] + '? ') to ans = raw_input('%s %s or %s?' % (question, true[0], false[1])) or in python 3.1: ans = raw_input('{} {} or {}?'.format(question, true[0], false[1])) (note: in python3.0, .format() only accepts explicitly numbered format string, e.g. '{0} {1} or {2}?') From angusr at bigfoot.com Sat Jul 4 20:36:36 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sat, 04 Jul 2009 19:36:36 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: >Date: Sat, 04 Jul 2009 13:26:12 +0100 >From: Angus Rodgers >Message-ID: > > (retention: 1 day) This is just a quick(ish!) response to the feedback so far. I realise, now, that I should have quoted what the exercise in the book was asking for, to explain why my code is more elaborate than the minimum that would be required to solve the problem at hand. >From the book (2nd ed., p. 151): "[...] we recommend that the reader convert his or her code to functions that can be used in future exercises." This requirement was uppermost in my mind. I also remembered from previous brushes with programming (mostly decades ago) that it is handy to have a little function that asks a question and won't quit until the user gives a yes-or-no answer. On the other hand, it would be overkill to try to write a program that applies a full lexical, syntactic, and semantic analysis to the text input by the user in an interactive console session. In the future I am quite likely to want to write something like that (essentially reviving a student project from 1990, on which I got a good enough mark to pass the course, but which suggested many lines of further development - and whose implementation as my first largish C++ program was simply abominable!), or else to use it off-the-shelf from some Python library or other (suggestions?), but it would take months to write (perhaps weeks in Python, or years in C++ ...), and therefore is out of the question here. So I tried to take the middle course of writing small functions that would be of use to me in future exercises (whether in this book or elsewhere). The whole thing only took me an hour or so to write (I didn't time the work, but it was certainly a matter of minutes, rather than hours), so it wasn't overkill (I think!). I did consider writing simpler code for input of strings as key values, and, in a rewrite, I think I will provide such simpler code, for this frequently-occurring default case (while still allowing for general key types). I also belatedly realised that I was stupidly duplicating code in my get_dict() function, and I will rewrite this, as Daniel Woodhouse suggests. get_dict() should make two calls to some function with a name like get_val(), with a general type as a parameter (perhaps defaulting to str - although the value type parameter of get_dict() should, on reflection, have no default). >------------------------------ > >Date: Sat, 4 Jul 2009 18:50:48 +0300 >From: Daniel Woodhouse >Message-ID: > <4c0a037d0907040850r7874313cn4abacc7db5957950 at mail.gmail.com> > >I had a look at your code, and refactored it a bit. See my modifications at >http://python.pastebin.com/m50acb143 You'll noticed I removed one of your >functions completely (it was unnecessary) and the get_dict() function is not >so heavily nested. (See comments above. I agree with the last bit, at least!) >Some ideas: >raw_input returns a string, so we can safely assume its a string. It's definitely a good idea to treat this frequently-occurring simple special case using simpler code (if only so that the user doesn't have to enter those annoying quotation marks every time). >Whether or >not its a valid name for a student is a different matter, and if you wish to >check such things you may wish to look at the regular expression module >(re). I'll certainly be investigating regular expressions (later), but I think you'll agree that it would be overkill for this exercise. >I wouldn't use eval as you did in the case, instead I did this to >check the score is a valid int: >try: > val = int(val) >except ValueError: > print 'Invalid score' I'll go halfway with you here. I still want to keep the generality of my code (for use in "future exercises"), but it shouldn't be beyond my wit to avoid the overkill (and risk - see comment below) of using eval(), and find out how to tell Python to evaluate a string /only/ as a value of a known type (respectively, key_typ or val_typ). I'll see if I can have a look at this after dinner, but I'll have to do some reading of the book or the online documentation. It's probably just as simple as this: ans = raw_input(prompt) try: key = key_typ(ans) except ValueError: (etc.) except (ouch!) that I may still need to check for some more general list of exceptions than just ValueError. (But I don't want to start serious work on this just yet.) >ValueError will catch invalid integers and we can ask the user to input >again. Generally we should only capture Exceptions that we are expecting, >though there are exceptions to this (no pun intended)... I'm sure you're right here. I had an uneasy feeling that I was doing something stupid and dangerous, which would not be a good habit to get into. >A lot of your code in get_dict() was repeated (basically the same operations >to get the key and the value). You should try to avoid duplication if >possible, either by putting the code in a seperate function, or just >collecting everything at once as I have done. Yes, I started to realise my mistake after posting. (Ain't it always the way!) >------------------------------ > >Date: Sat, 4 Jul 2009 18:10:36 +0100 >From: Rich Lovely >Message-ID: > > > >Lets consider how you handle your input. > >You get a string, from the user, then you pass it to eval, which runs >it as if it was a python command. Consider if they put in something >like the following: >__import__('os').system("rm -rf /") > >If you know linux, you will know this is a bad thing. A similar idea >on windows is __import__('os').system("format c: /q") Even the vaguely recalled bit of Unix was enough to make me sweat! >In short, unless you really know what you're doing, never use >eval(raw_input(...)) for the same reasons you should never use >input(...), for in effect, that is exactly what you are using. > >In fact, the python 3.0 docs recommend that form (using the new name >for raw_input), in expert scripts allowing interactive code entry. My response to this [but see the afterthought below!] is that I definitely need to put into the documentation string something like "*** THIS FUNCTION IS HIGHLY VULNERABLE TO A MALICIOUS USER ***", so that I will be strongly warned NEVER to incorporate it into any program that might be used by anyone other than myself. It might also be a good idea to include some kind of brief warning in the user prompts. (This won't put off a malicious user, of course, but it would help to keep me in mind of the potential danger.) On the other hand, so long as I AM only executing the function myself, I am no more at risk than I already am every single time I type a command into a Python interpreter, of any description. (A somewhat Existentialist thought, perhaps! Virtual suicide is always a possibility.) >-> Does that seem reasonable? You've made me clearly aware of a risk that I was only vaguely aware of before (I ruminated only briefly as to whether any harm might come from entering general Python expressions, but my main feeling about this facility was that it would probably be useful - in some "future exercise"), but isn't there a role for functions that one can use oneself, but never ever distribute to the "general public"? If so, are the precautions I have suggested above sufficient? (This question seems worth asking anyway, even though I have already concluded, in my response to Daniel above, that I can indeed avoid using eval() without losing anything essential.) -- Angus Rodgers From alan.gauld at btinternet.com Sat Jul 4 20:52:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Jul 2009 19:52:56 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? References: Message-ID: "Angus Rodgers" wrote > (i) trapping the exception StandardError may, for all I know, > be a daft thing to do; Not daft but not that common. Mainly because use of eval() is kind of frownedoon for security reasons. (See below.) > (iv) correlatively with (iii), my indentation perhaps looks a > little extreme (perhaps suggesting a redesign, I don't know); You can miss out a few else clauses, especially after the try/excepts: ----------- while get_bool("Continue?"): try: key = eval(raw_input("Key value of type " + key_typ.__name__ + ": ")) except StandardError: print "That's not a Python expression!" if not isinstance(key, key_typ): print "That's not a value of type", key_typ.__name__ else: # User has provided try: val = eval(raw_input("Object of type " + val_typ.__name__ + ": ")) except StandardError: print "That's not a Python expression!" if not isinstance(val, val_typ): print "That's not an object of type", val_typ.__name__ else: # User has provided an object of the correct type ans[key] = val return ans ------------ I'm hoping you know about the security issues around using eval with raw_input? The use can input any valid python code and it will be evaluated! For experimenting its OK but in live code it would be very risky. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From noufal at nibrahim.net.in Sat Jul 4 21:56:50 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sun, 05 Jul 2009 01:26:50 +0530 Subject: [Tutor] Stack unwind using exceptions. Message-ID: <4A4FB402.8030808@nibrahim.net.in> Hello everyone, Would it be considered unorthodox or 'wrong' in some sense for me to use an exception to unwind the stack and return to a caller for a recursive function? I need to do a depth first search and when I find the right element to just stop the whole thing, and get back to the caller saying that I found it. TIA. -- ~noufal http://nibrahim.net.in/ From lie.1296 at gmail.com Sat Jul 4 22:53:06 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 05 Jul 2009 06:53:06 +1000 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: Angus Rodgers wrote: >> Date: Sat, 04 Jul 2009 13:26:12 +0100 >> From: Angus Rodgers >> Message-ID: >> >> (retention: 1 day) > > This is just a quick(ish!) response to the feedback so far. > > I realise, now, that I should have quoted what the exercise in the > book was asking for, to explain why my code is more elaborate than > the minimum that would be required to solve the problem at hand. > >>From the book (2nd ed., p. 151): > > "[...] we recommend that the reader convert his or her code to > functions that can be used in future exercises." > > This requirement was uppermost in my mind. If it is the top requirement, then your code is not general enough as it can only ask for dictionaries. A general solution would be at least something like this: (now talk about bloat and overdesigning...) #!/usr/bin/env python import re from functools import partial ''' Like Swiss Army. It does everything. Includes batteries and kitchen sink. Caveat: written at 3AM in the morning. ''' class PromptError(Exception): pass def prompt(prompt='? ', reprompt='Invalid input. Try again.', validate=str, postprocess=str, tries=3, catchlist=(ValueError,), ): ''' prompt the user for input, validate, and return the result postprocess is called before returning the value if number of tries exceeds `tries` raise PromptError. Set tries to -1 to prompt infinitely ''' while tries != 0: inp = raw_input(prompt) try: validate(inp) except catchlist, e: print reprompt tries -= 1 else: return postprocess(inp) else: raise PromptError('Maximum number of tries exceeded') def expecting(s, expected=[], errmess='Invalid input'): ''' return True if `s` matches any regex pattern in `expected` raises ValueError otherwise. ''' for pat in expected: if re.compile(pat+'$', re.IGNORECASE).match(s): return True else: raise ValueError(errmess) def convert(s, convtab): ''' convert `s` into convtab's key ''' for target, pats in convtab.iteritems(): for pat in pats: if re.compile(pat+'$', re.IGNORECASE).match(s): return target else: raise ValueError('Cannot convert') def chain(*rings): ''' Calls a list of function and return their return values as a tuple ''' def _chain(): return tuple(ring() for ring in rings) return _chain def serial_prompt(mainprompt, cont_prompt='Continue? ', postprocess=lambda x: x, ): ''' Prompts for a series of values, with 'continue?'s between each prompt. Return values of the prompts are collected in a list and passed to `postprocess`. ''' def _serial_prompt(): ret = [mainprompt()] while get_bool(cont_prompt): ret.append(mainprompt()) return postprocess(ret) return _serial_prompt trues = ['1', 'ye?s?', 'tr?u?e?'] falses = ['0', 'no?', 'fa?l?s?e?'] bools = trues + falses expecting_bool = partial(expecting, expected=bools) convert_bool = partial(convert, convtab={True: trues, False: falses}) get_bool = partial(prompt, validate=expecting_bool, postprocess=convert_bool, ) get_key = prompt get_value = partial(prompt, validate=int, postprocess=int, ) get_kv = chain(partial(get_key, prompt='key (str): '), partial(get_value, prompt='value (int): '), ) get_dict = serial_prompt(get_kv, postprocess=dict) print get_bool('bool: ') print get_key('key (str): ') print get_value('value (int): ') print get_kv() print get_dict() From kent37 at tds.net Sun Jul 5 00:25:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 4 Jul 2009 18:25:17 -0400 Subject: [Tutor] Stack unwind using exceptions. In-Reply-To: <4A4FB402.8030808@nibrahim.net.in> References: <4A4FB402.8030808@nibrahim.net.in> Message-ID: <1c2a2c590907041525l7a44a9d4h1811e5fc75a427f9@mail.gmail.com> On Sat, Jul 4, 2009 at 3:56 PM, Noufal Ibrahim wrote: > Hello everyone, > > Would it be considered unorthodox or 'wrong' in some sense for me to use an > exception to unwind the stack and return to a caller for a recursive > function? > > I need to do a depth first search and when I find the right element to just > stop the whole thing, and get back to the caller saying that I found it. Why not just return the value from the function and pass it up the call chain? If a call fails return None. Something like this: def search(self, value): if self.value == value: return self for child in self.children: result = child.search(value) if result is not None: return result return None Kent From buckstec at gmail.com Sat Jul 4 18:09:57 2009 From: buckstec at gmail.com (Steven Buck) Date: Sat, 4 Jul 2009 09:09:57 -0700 Subject: [Tutor] reading variables in a data set? Message-ID: Dear Python Tutor, I'm doing econometric work and am a new user of Python. I have read several of the tutorials, but haven't found them useful for a newbie problem I've encountered. I've used a module (StataTools) from (http://presbrey.mit.edu/PyDTA ) to get a Stata ".dta" file into Python. In Stata the data set is an NXK matrix where N is the number of observations (households) and K is the number of variables. I gather it's now a list where each element of the list is an observation (a vector) for one household. The name of my list is "data"; I gather Python recognizes the first observation by: data[1] . Example, data = [X_1, X_2, X_3, . . . . , X_N] where each X_i for all i, is vector of household characteristics, eg X_1 = (age_1, wage_1, . . . , residence_1). I also have a list for variable names called "varname"; although I'm not sure the module I used to extract the ".dta" into Python also created a correspondence between the varname list and the data list--the python interpreter won't print anything when I type one of the variable names, I was hoping it would print out a vector of ages or the like. In anycase, I'd like to make a scatter plot in pylab, but don't know how to identify a variable in "data" (i.e. I'd like a vector listing the ages and another vector listing the wages of households). Perhaps, I need to run subroutine to collect each relevant data point to create a new list which I define as my variable of interest? From the above example, I'd like to create a list such as: age = [age_1, age_2, . . . , age_N] and likewise for wages. Any help you could offer would be very much appreciated. Also, this is my first time using the python tutor, so let me know if I've used it appropriately or if I should change/narrow the structure of my question. Thanks Steve -- Steven Buck Ph.D. Student Department of Agricultural and Resource Economics University of California, Berkeley -------------- next part -------------- An HTML attachment was scrubbed... URL: From angusr at bigfoot.com Sun Jul 5 01:30:57 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sun, 05 Jul 2009 00:30:57 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: >Date: Sat, 4 Jul 2009 19:52:56 +0100 >From: "Alan Gauld" >Message-ID: > >You can miss out a few else clauses, especially after >the try/excepts: > >----------- >while get_bool("Continue?"): > try: key = eval(raw_input("Key value of type " + key_typ.__name__ + ": ")) > except StandardError: print "That's not a Python expression!" > > if not isinstance(key, key_typ): > print "That's not a value of type", key_typ.__name__ else: # User has provided > try: val = eval(raw_input("Object of type " + val_typ.__name__ + ": ")) > except StandardError: print "That's not a Python expression!" > > if not isinstance(val, val_typ): > print "That's not an object of type", val_typ.__name__ > else: # User has provided an object of the correct type > ans[key] = val >return ans >------------ I don't see this, because, if an exception does occur, won't there be an attempt to access one of the objects 'key', 'val' before it has been assigned? Not that this matters in the largely rewritten "Version 0.1": (retention: 1 day) (Is it time for me to get into the comfy chair yet?) 8-P -- Angus Rodgers From alan.gauld at btinternet.com Sun Jul 5 01:59:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 5 Jul 2009 00:59:13 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? References: Message-ID: "Angus Rodgers" wrote >>You can miss out a few else clauses, especially after >>the try/excepts: >> >>----------- >>while get_bool("Continue?"): >> try: key = eval(raw_input("Key value of type " + key_typ.__name__ + >> ": ")) >> except StandardError: print "That's not a Python expression!" >> >> if not isinstance(key, key_typ): >> print "That's not a value of type", key_typ.__name__ else: # User >> has provided >> try: val = eval(raw_input("Object of type " + val_typ.__name__ + ": >> ")) >> except StandardError: print "That's not a Python expression!" >> > I don't see this, because, if an exception does occur, won't > there be an attempt to access one of the objects 'key', 'val' > before it has been assigned? There will, which will throw another exception and exit. And the exception will tell you which try failed, which is more than your generic printed error message does... Sometimes just letting Python fail is the best course. Of course your messages will be prettier than the standard stacktrace, but less useful for debugging. However you can get what you want without the else by simply inserting a break in each exception handler, which keeps the indentation under control. while get_bool("Continue?"): try: key = eval(raw_input("Key value of type " + key_typ.__name__ + ": ")) except StandardError: print "That's not a Python expression!" break if not isinstance(key, key_typ): print "That's not a value of type", key_typ.__name__ else: # User has provided etc... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Sun Jul 5 02:30:08 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 04 Jul 2009 19:30:08 -0500 Subject: [Tutor] reading variables in a data set? In-Reply-To: References: Message-ID: <4A4FF410.5040803@gmail.com> Pardon me, I don't have time to address all of your questions; however, Steven Buck wrote: > I gather it's now a list where each element of the list is an > observation (a vector) for one household. The name of my list is > "data"; I gather Python recognizes the first observation by: data[1] . No, the first item in a list is going to be data[0], not data[1]. Python counts from 0 not 1. Unless by the "first observation" you mean the "one after the zeroth observation" but that is not the common usage of that term. > Example, > data = [X_1, X_2, X_3, . . . . , X_N] where each X_i for all i, is > vector of household characteristics, eg X_1 = (age_1, wage_1, . . . , > residence_1). > > I also have a list for variable names called "varname"; although I'm > not sure the module I used to extract the ".dta" into Python also > created a correspondence between the varname list and the data > list--the python interpreter won't print anything when I type one of > the variable names, I was hoping it would print out a vector of ages > or the like. It should output whatever is contained in the variable, if you're at the interpreter. Sounds like you're not getting your data in. >>> x = ["hello", "world!", 42] >>> x ['hello', 'world!', 42] Hope that helps a litttle bit, good luck! -Luke From emile at fenx.com Sun Jul 5 02:39:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 04 Jul 2009 17:39:27 -0700 Subject: [Tutor] reading variables in a data set? In-Reply-To: References: Message-ID: On 7/4/2009 9:09 AM Steven Buck said... > Dear Python Tutor, > I'm doing econometric work and am a new user of Python. I have read > several of the tutorials, but haven't found them useful for a newbie > problem I've encountered. > I've used a module (StataTools) from (http://presbrey.mit.edu/PyDTA ) to > get a Stata ".dta" file into Python. In Stata the data set is an NXK > matrix where N is the number of observations (households) and K is the > number of variables. > I gather it's now a list where each element of the list is an > observation (a vector) for one household. The name of my list is > "data"; I gather Python recognizes the first observation by: data[1] . > Example, > data = [X_1, X_2, X_3, . . . . , X_N] where each X_i for all i, is > vector of household characteristics, eg X_1 = (age_1, wage_1, . . . , > residence_1). > > I also have a list for variable names called "varname"; although I'm not > sure the module I used to extract the ".dta" into Python also created a > correspondence between the varname list and the data list--the python > interpreter won't print anything when I type one of the variable names, > I was hoping it would print out a vector of ages or the like. Assuming you're working in the python console somewhat from the example on the source website for PyDTA: from PyDTA import Reader dta = Reader(file('input.dta')) fields = ','.join(['%s']*len(dta.variables())) ... you might try starting at dir|help (dta.variables) I didn't look, but the sources are available as well. > > In anycase, I'd like to make a scatter plot in pylab, I think I'd use dictionaries along these lines: wages = { age_1: [ X_1, X_15, X_3...], age_2: [ X_2, X_5... ], ] > but don't know how > to identify a variable in "data" (i.e. I'd like a vector listing the > ages and another vector listing the wages of households). I think poking into dta.variables will answer this one. HTH, Emile > Perhaps, I > need to run subroutine to collect each relevant data point to create a > new list which I define as my variable of interest? From the above > example, I'd like to create a list such as: age = [age_1, age_2, . . . , > age_N] and likewise for wages. > > Any help you could offer would be very much appreciated. Also, this is > my first time using the python tutor, so let me know if I've used it > appropriately or if I should change/narrow the structure of my question. > > Thanks > Steve > > -- > Steven Buck > Ph.D. Student > Department of Agricultural and Resource Economics > University of California, Berkeley > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From roadierich at googlemail.com Sun Jul 5 07:48:39 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 5 Jul 2009 06:48:39 +0100 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: 2009/7/4 Angus Rodgers : >>Date: Sat, 04 Jul 2009 13:26:12 +0100 >>From: Angus Rodgers >>Message-ID: > My response to this [but see the afterthought below!] is that I > definitely need to put into the documentation string something > like "*** THIS FUNCTION IS HIGHLY VULNERABLE TO A MALICIOUS USER > ***", so that I will be strongly warned NEVER to incorporate it > into any program that might be used by anyone other than myself. > > It might also be a good idea to include some kind of brief warning > in the user prompts. (This won't put off a malicious user, of course, > but it would help to keep me in mind of the potential danger.) I personally would never release code to any sort of public calling eval on user-inputted (or even user-accessible) strings or using input(), even if you had to go through fifteen different dialogue boxes first (see below). Also, at a beginner level, as soon as you can manage without these, you should, perhaps even going so far as to delete the old function, so you never run the risk of copy and pasting when not paying much attention. There are always ignorant users, who can influenced by malicious users, and might not know what I mentioned in my previous is wrong, therefore making warnings irrelevant. To give a classic example, as seen in IRC channels across the web: How do I do XYZ in ABC? NewUser: Press Alt+F4 if you're on windows. Thanks. #NewUser has quit - connection reset by peer# Later... #NewUser has joined the channel# Everytime I try to do XYZ, my IRC client shuts down. NewUser: What command are you using? CodeChimp: Alt+F4 lol NewUser: That's a common problem. You can fix it in the config screen. Bring it up by holding down Ctrl and Alt, and pressing Del twice quickly. ok #NewUser has quit - connection reset by peer# lol Perhaps I enjoyed writing that a little too much... and I could easily go on. But I won't. Email me for the continuing saga of NewUser. Anyone at a level to need to use input() appropriatly is usually capable of writing their own script to do so, and would probably just be annoyed at any warnings you chose to stick in. I've never gotten to the point where I've needed input(). I'm curious to know whether anyone on the list has. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From noufal at nibrahim.net.in Sun Jul 5 09:00:13 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sun, 05 Jul 2009 12:30:13 +0530 Subject: [Tutor] Stack unwind using exceptions. In-Reply-To: <1c2a2c590907041525l7a44a9d4h1811e5fc75a427f9@mail.gmail.com> References: <4A4FB402.8030808@nibrahim.net.in> <1c2a2c590907041525l7a44a9d4h1811e5fc75a427f9@mail.gmail.com> Message-ID: <4A504F7D.8090506@nibrahim.net.in> Kent Johnson wrote: [..] > Why not just return the value from the function and pass it up the > call chain? If a call fails return None. Something like this: That's what I ended up doing but the first thing occurred to me and I was just wondering if there's any production code that relies on the technique. -- ~noufal http://nibrahim.net.in/ From kent37 at tds.net Sun Jul 5 17:02:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 5 Jul 2009 11:02:12 -0400 Subject: [Tutor] reading variables in a data set? In-Reply-To: References: Message-ID: <1c2a2c590907050802i3d1c1ab8t2b9db0f2857ae8d1@mail.gmail.com> On Sat, Jul 4, 2009 at 12:09 PM, Steven Buck wrote: > I've used a module (StataTools) from (http://presbrey.mit.edu/PyDTA?)?to get > a Stata ".dta" file into Python.?In Stata the?data set is an NXK matrix > where N is the number of observations (households) and K is the number of > variables. > I gather it's now a list where each element of the list is an observation (a > vector) for one household.? The name of my list is "data";?I gather Python > recognizes?the first observation by: data[1] . > Example, > data = [X_1, X_2, X_3, . . . . , X_N]? where each X_i for all i,?is vector > of household characteristics, eg X_1 = (age_1, wage_1, . . . , residence_1). > > I also have a list for variable names called "varname"; although I'm not > sure the module I used to extract the ".dta" into Python also created a > correspondence between the?varname list and the data list--the python > interpreter?won't print anything when I type one of the variable names, I > was hoping it would print out a vector of ages or the like. varname is probably just a list of strings without any direct connection to the data. > In anycase,?I'd like to make a scatter plot in pylab, but don't know how to > identify a variable in "data" (i.e.? I'd like a vector listing the ages and > another vector listing the?wages?of??households).? Perhaps, I need to run > subroutine to collect each relevant?data point to create a new list which I > define as my variable of interest???From the above example, I'd like to > create a list?such as:?age = [age_1, age_2, . . . , age_N] and likewise for > wages. You can use a list comprehension to collect columns from the data. If age is the first element of each observation (index 0), and wages the second (index 1), then ages = [ observation[0] for observation in data ] wages = [ observation[1] for observation in data ] > Any help you could offer would be very much appreciated.? Also, this is my > first time using the python tutor, so let me know if I've used it > appropriately or if I should change/narrow the structure of my question. It's very helpful if you show us the code you have so far. Kent From bgailer at gmail.com Sun Jul 5 19:59:08 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 05 Jul 2009 13:59:08 -0400 Subject: [Tutor] Stack unwind using exceptions. In-Reply-To: <4A504F7D.8090506@nibrahim.net.in> References: <4A4FB402.8030808@nibrahim.net.in> <1c2a2c590907041525l7a44a9d4h1811e5fc75a427f9@mail.gmail.com> <4A504F7D.8090506@nibrahim.net.in> Message-ID: <4A50E9EC.9000403@gmail.com> Noufal Ibrahim wrote: > Kent Johnson wrote: > [..] >> Why not just return the value from the function and pass it up the >> call chain? If a call fails return None. Something like this: > > That's what I ended up doing but the first thing occurred to me and I > was just wondering if there's any production code that relies on the > technique. > I use the exception technique in my Python Pipelines parser. The recursive routine has 6 raise statements. The exceptions are caught by the program that calls the recursive routine. There would be more code and complexity to work back up the call chain. -- Bob Gailer Chapel Hill NC 919-636-4239 From angusr at bigfoot.com Sun Jul 5 20:48:37 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sun, 05 Jul 2009 19:48:37 +0100 Subject: [Tutor] Poor style to use list as "array"? Message-ID: The problem this time is, given an amount of US currency in cents (and less than a dollar), to print out a description of the coins needed to represent it, using the smallest number of coins. E.g.: How many cents this time? 59 2 quarters, 1 nickel and 4 pennies. How many cents this time? 55 2 quarters and 1 nickel. How many cents this time? 75 3 quarters. My program relaxes the restriction to amounts less than a dollar, and initialises the necessary data structures as follows: denom = ['dollar', 'quarter', 'dime', 'nickel', 'penny'] value = [100, 25, 10, 5, 1] LEN = 5 plural = [None] * LEN plural[-1] = 'pennies' count = [None] * LEN # Kludge I use the list 'count' as a kind of array, so that e.g. count[-1] is the number of pennies needed, count[2] is the number of dimes needed, and so on. Any initial values I might store as elements of the list are never used, hence the use of 'None'. (The use of 'None' in the list 'plural' is much more defensible, I think, as it is used to denote the formation of a regular plural by adding 's' to the name.) Instead, the actual values are assigned in a 'for' loop, as follows: for i in range(LEN - 1): (count[i], amnt) = divmod(amnt, value[i]) This feels like a bit of a cheat, as if I am trying to program in Python as if it were some other more familiar language. Should I have coded this differently? The full source code is here, in case anyone wants to look at it (but I'm not soliciting any more attention, as I've already been given quite a lot of it, and fear being offered the comfy chair!): (retention: 1 day) Could I have used dictionaries instead, with the denomination names as keys? Is it possible to guarantee a sequence in which the keys of a dictionary are iterated through? (If not, I suppose I could keep the list 'denom' as it is here, and iterate through it with "for key in denom:", although this seems a bit redundant.) -- Angus Rodgers From noufal at nibrahim.net.in Sun Jul 5 21:30:58 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Mon, 06 Jul 2009 01:00:58 +0530 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: References: Message-ID: <4A50FF72.6070303@nibrahim.net.in> Angus Rodgers wrote: [..] > > This feels like a bit of a cheat, as if I am trying to program in > Python as if it were some other more familiar language. Should I > have coded this differently? I can't offer anything concrete but here are some things that occur to me at a glance. 0. You can try to use the collections module in 2.6 (especially the namedtuple object which gives you access to things through attributes as well as through order. 1. You have 3 lists (denom, plural and count) which you will iterate through in lockstep as far as I can tell. It's an option to use a list of 3-tuples or a list of dictionaries with three keys (denomination, plural and count). Thanks. -- ~noufal http://nibrahim.net.in/ From tim.peters at gmail.com Sun Jul 5 22:12:49 2009 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 5 Jul 2009 16:12:49 -0400 Subject: [Tutor] Is my style OK in this elementary student exercise? In-Reply-To: References: Message-ID: <1f7befae0907051312v276ff95dw14d2121c36254291@mail.gmail.com> [Angus Rogers, suffering eval-angst] > ... > On the other hand, so long as I AM only executing the function > myself, I am no more at risk than I already am every single time > I type a command into a Python interpreter, of any description. > (A somewhat Existentialist thought, perhaps! ?Virtual suicide > is always a possibility.) >-> > > Does that seem reasonable? ?You've made me clearly aware of a > risk that I was only vaguely aware of before (I ruminated only > briefly as to whether any harm might come from entering general > Python expressions, but my main feeling about this facility was > that it would probably be useful - in some "future exercise"), > but isn't there a role for functions that one can use oneself, > but never ever distribute to the "general public"? Certainly! I use eval() and input() all the time in my private code (but never in released code), and you're never going to screw yourself "by accident" doing so. Especially if you have an interest in writing mathematical code, it's a tremendous convenience for prompted input to support arbitrary computation. >?If so, are the precautions I have suggested above sufficient? In private code, any precautions are probably just a waste of time. You really don't, for example, need to remind /yourself/ not to enter a convoluted expression that emails your credit card info to a hacker site in Nigeria. Or if you do need to remind yourself not to do things like that, you probably shouldn't be using a computer to begin with ;-) From eike.welk at gmx.net Sun Jul 5 23:29:45 2009 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 05 Jul 2009 23:29:45 +0200 Subject: [Tutor] Stack unwind using exceptions. In-Reply-To: <4A504F7D.8090506@nibrahim.net.in> References: <4A4FB402.8030808@nibrahim.net.in> <1c2a2c590907041525l7a44a9d4h1811e5fc75a427f9@mail.gmail.com> <4A504F7D.8090506@nibrahim.net.in> Message-ID: <200907052329.45546.eike.welk@gmx.net> On Sunday 05 July 2009, Noufal Ibrahim wrote: > Kent Johnson wrote: > [..] > > > Why not just return the value from the function and pass it up > > the call chain? If a call fails return None. Something like this: > > That's what I ended up doing but the first thing occurred to me and > I was just wondering if there's any production code that relies on > the technique. The Pyparsing library uses exceptions a lot internally. If I understood it right, exceptions are used to tell that a pattern does not match. If the pattern matches the results are transported with a regular 'return'. As it happens quite often that a pattern does not match, exceptions can be considered a regular mechanism for information transport in Pyparsing. There are two types of exceptions in Pyparsing. An exception that means: try the next pattern; and there are exceptions that mean: there was a fatal error, stop parsing. Pyparsing: http://pyparsing.wikispaces.com/ Kind regards, Eike. From kent37 at tds.net Mon Jul 6 00:49:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 5 Jul 2009 18:49:32 -0400 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: References: Message-ID: <1c2a2c590907051549j6da673dere006318f70568ef7@mail.gmail.com> On Sun, Jul 5, 2009 at 2:48 PM, Angus Rodgers wrote: > for i in range(LEN - 1): > ? ?(count[i], amnt) = divmod(amnt, value[i]) How about this: counts = [] for val in value: count, amnt = divmod(amnt, val) counts.append(count) > This feels like a bit of a cheat, as if I am trying to program in > Python as if it were some other more familiar language. ?Should I > have coded this differently? Generally it's more straighforward to iterate over a list directly rather than using an index. > The full source code is here, in case anyone wants to look at it > (but I'm not soliciting any more attention, as I've already been > given quite a lot of it, and fear being offered the comfy chair!): Don't worry, we have retired the comfy chair. > Could I have used dictionaries instead, with the denomination names > as keys? ?Is it possible to guarantee a sequence in which the keys > of a dictionary are iterated through? In general no. Python 2.7 and 3.1 do have an ordered dictionary: http://www.python.org/dev/peps/pep-0372/ Kent From alan.gauld at btinternet.com Mon Jul 6 01:16:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Jul 2009 00:16:26 +0100 Subject: [Tutor] Poor style to use list as "array"? References: Message-ID: "Angus Rodgers" wrote > as keys? Is it possible to guarantee a sequence in which the keys > of a dictionary are iterated through? Indirectly yes: for key in sorted( dct ): print key I would definitely tend to go with a dictionary for the denominations/values in this case (Actually I'd probably go for a class but that's another ball game entirely!) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From buckstec at gmail.com Mon Jul 6 00:57:42 2009 From: buckstec at gmail.com (Steven Buck) Date: Sun, 5 Jul 2009 15:57:42 -0700 Subject: [Tutor] append question Message-ID: Hi Python Tutors: I have a data structure that looks like: >>> test=[[1,2,3],[4,5,6],[7,8,9]] I want to define a new variable that captures the second element of each sublist from above: >>> testvar2 = [] Next I try to capture the aforementioned elements: >>> for i in len(test): testvar2.append(test[i][2]) I want testvar2 = [2,5,8] but instead I get the following error message: Traceback (most recent call last): File "", line 1, in for i in len(test): TypeError: 'int' object is not iterable Any insight would be appreciated. Thanks Steve -- Steven Buck Ph.D. Student Department of Agricultural and Resource Economics University of California, Berkeley -------------- next part -------------- An HTML attachment was scrubbed... URL: From angusr at bigfoot.com Mon Jul 6 02:02:10 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Mon, 06 Jul 2009 01:02:10 +0100 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: <1c2a2c590907051549j6da673dere006318f70568ef7@mail.gmail.com> References: <1c2a2c590907051549j6da673dere006318f70568ef7@mail.gmail.com> Message-ID: <7be2551mqdvmk0lj02a90gsde2l036dojc@4ax.com> On Sun, 5 Jul 2009 18:49:32 -0400, Kent Johnson wrote: >On Sun, Jul 5, 2009 at 2:48 PM, Angus Rodgers wrote: > >> for i in range(LEN - 1): >> ? ?(count[i], amnt) = divmod(amnt, value[i]) Incidentally, I forgot to quote the next line: count[-1] = m Of course, this is much better incorporated into the loop, thus: for i in range(LEN): (count[i], amnt) = divmod(amnt, value[i]) and this lends itself to being rewritten in terms of some other kind of iteration (as below). >How about this: >counts = [] >for val in value: > count, amnt = divmod(amnt, val) > counts.append(count) I like that very much, because it is in the nature of the problem that the numbers in the list 'value' are all distinct, and so can be used as keys. However, as this remark suggests, I think I am going to need 'count' to be a dictionary, rather than a list, and the same goes for 'denom', and 'plural' (although this should be keyed by the strings in 'denom', and we don't need the 'None's). So it looks like we should have something like: plural = {'penny':'pennies'} counts = {} for val in value: (count, amnt) = divmod(amnt, val) counts[val] = count and, later in the program, something like this (comments stripped for brevity, and one new comment added): for val in value: amnt = counts[val] name = denom[val] if amnt: to_print -= 1 if printed: if to_print: buff += ", " else: buff += " and " printed += 1 if amnt > 1: # This should become a function if name in plural: name = plural[name] else: name += 's' buff += "%d %s" % (amnt, name) I haven't run this, but I'll try rewriting the program tomorrow. It looks like there's nothing to it. I'm much happier now, thanks! -- Angus Rodgers From rabidpoobear at gmail.com Mon Jul 6 02:06:13 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 5 Jul 2009 19:06:13 -0500 Subject: [Tutor] append question In-Reply-To: References: Message-ID: Read your error message... It highlighted the first line of your for loop ansd said ints aren't iterable. len(list) returns an integer. You want a list of items... for i in range(len(list)): On 7/5/09, Steven Buck wrote: > Hi Python Tutors: > > I have a data structure that looks like: > >>>> test=[[1,2,3],[4,5,6],[7,8,9]] > > I want to define a new variable that captures the second element of each > sublist from above: > >>>> testvar2 = [] > > Next I try to capture the aforementioned elements: > >>>> for i in len(test): > testvar2.append(test[i][2]) > > I want testvar2 = [2,5,8] but instead I get the following error message: > > Traceback (most recent call last): > File "", line 1, in > for i in len(test): > TypeError: 'int' object is not iterable > > Any insight would be appreciated. > Thanks > Steve > > > > > > > > > -- > Steven Buck > Ph.D. Student > Department of Agricultural and Resource Economics > University of California, Berkeley > -- Sent from my mobile device From angusr at bigfoot.com Mon Jul 6 02:14:50 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Mon, 06 Jul 2009 01:14:50 +0100 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: <7be2551mqdvmk0lj02a90gsde2l036dojc@4ax.com> References: <1c2a2c590907051549j6da673dere006318f70568ef7@mail.gmail.com> <7be2551mqdvmk0lj02a90gsde2l036dojc@4ax.com> Message-ID: On Mon, 06 Jul 2009 01:02:10 +0100, I hastily wrote: >Incidentally, I forgot to quote the next line: > >count[-1] = m That was copied-and-pasted from an older version of the program, with less descriptive identifiers. 'm' should be 'amnt'. >Of course, this is much better incorporated into the loop, thus: > >for i in range(LEN): > (count[i], amnt) = divmod(amnt, value[i]) > >[...] > >So it looks like we should have something like: > >plural = {'penny':'pennies'} > >counts = {} >for val in value: > (count, amnt) = divmod(amnt, val) > counts[val] = count Better, of course (I still haven't run it, but it should work): counts = {} for val in value: (counts[val], amnt) = divmod(amnt, val) >I'm much happier now, thanks! ... but also rather annoyed with myself. -- Angus Rodgers From roadierich at googlemail.com Mon Jul 6 02:19:51 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 6 Jul 2009 01:19:51 +0100 Subject: [Tutor] append question In-Reply-To: References: Message-ID: 2009/7/5 Steven Buck : >>>> for i in len(test): > ??????????? testvar2.append(test[i][2]) > > I want testvar2 = [2,5,8] but instead I get the following error message: > > Traceback (most recent call last): > ? File "", line 1, in > ??? for i in len(test): > TypeError: 'int' object is not iterable > > Any insight would be appreciated. > Thanks > Steve > -- > Steven Buck > Ph.D. Student > Department of Agricultural and Resource Economics > University of California, Berkeley This sounds like a homework assignment, and we're not supposed to give out answers to homework. The error message and the docs explain what you're doing wrong if you take a moment to look. from http://www.python.org/doc/2.6/reference/compound_stmts.html#for """for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] The expression list is evaluated once; it should yield an iterable object. An iterator is created for the result of the expression_list. The suite is then executed once for each item provided by the iterator, in the order of ascending indices. Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed.""" As Luke said, len returns an int, which as your error tells you, is not iterable. From the same page: """The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object:""" Therefore you have an iterable, there is no need to try and construct a new one. Does that help? It is extremly unpythonic to iterate over range(len(...)), as it adds in the overhead of two function calls, and ruins the readability of code. The latter is probably the most important of the two. An even more pythonic way to do this would be a list comprehension, http://www.python.org/doc/2.6/tutorial/datastructures.html#list-comprehensions If it's not homework, let us know, and we'll be more than willing to give you code if you still need it. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From bermanrl at cfl.rr.com Mon Jul 6 02:32:03 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 05 Jul 2009 20:32:03 -0400 Subject: [Tutor] append question In-Reply-To: References: Message-ID: <1246840323.18124.5.camel@bermanrl-desktop> In [1]: test=[[1,2,3],[4,5,6],[7,8,9]] In [3]: testvar2 = [] In [16]: for i in range(len(test)): ....: testvar2.append(test[i][1]) ....: ....: In [17]: testvar2 Out[17]: [2, 5, 8] Robert On Sun, 2009-07-05 at 15:57 -0700, Steven Buck wrote: > Hi Python Tutors: > > I have a data structure that looks like: > > >>> test=[[1,2,3],[4,5,6],[7,8,9]] > > I want to define a new variable that captures the second element of > each sublist from above: > > >>> testvar2 = [] > > Next I try to capture the aforementioned elements: > > >>> for i in len(test): > testvar2.append(test[i][2]) > > I want testvar2 = [2,5,8] but instead I get the following error > message: > > Traceback (most recent call last): > File "", line 1, in > for i in len(test): > TypeError: 'int' object is not iterable > > Any insight would be appreciated. > Thanks > Steve > > > > > > > > > > -- > Steven Buck > Ph.D. Student > Department of Agricultural and Resource Economics > University of California, Berkeley > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From roadierich at googlemail.com Mon Jul 6 02:51:22 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 6 Jul 2009 01:51:22 +0100 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: <7be2551mqdvmk0lj02a90gsde2l036dojc@4ax.com> References: <1c2a2c590907051549j6da673dere006318f70568ef7@mail.gmail.com> <7be2551mqdvmk0lj02a90gsde2l036dojc@4ax.com> Message-ID: > ? ? ? ? ? ? ? ?if name in plural: > ? ? ? ? ? ? ? ? ? ?name = plural[name] > ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ?name += 's' This could be written more cleanly (although arguably not as readably) as name = plural.get(name, name + "s") d.get(key, default) returns the value from d mapped to key if it exists, or default otherwise. You might also want to split your calculation and display code into two separate loops. This might seem wasteful, but it will make your code easier to read and maintain, and the waste is only marginal with the loops you're running - there is a maximum of only 17 passes (once for each value of coin and note) -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From bgailer at gmail.com Mon Jul 6 05:19:10 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 05 Jul 2009 23:19:10 -0400 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: References: Message-ID: <4A516D2E.7040702@gmail.com> Angus Rodgers wrote: > The problem this time is, given an amount of US currency in cents > (and less than a dollar), to print out a description of the coins > needed to represent it, using the smallest number of coins. E.g.: > > How many cents this time? 59 > 2 quarters, 1 nickel and 4 pennies. > > How many cents this time? 55 > 2 quarters and 1 nickel. > > How many cents this time? 75 > 3 quarters. > > My program relaxes the restriction to amounts less than a dollar, > and initialises the necessary data structures as follows: > > denom = ['dollar', 'quarter', 'dime', 'nickel', 'penny'] > value = [100, 25, 10, 5, 1] > LEN = 5 > plural = [None] * LEN > plural[-1] = 'pennies' > count = [None] * LEN # Kludge > I'm inclined to use a class. I omitted the input and loop for "simplicity". class Coin: def __init__(self, name, value, plural=None): self.name = name self.value = value if plural: self.plural = plural else: self.plural = self.name + 's' self.count = 0 def display(self): if self.count == 0: return None if self.count == 1: return "%d %s" % (self.count, name) else: return "%d %s" % (self.count, self.plural) coins = Coin('dollar', 100), Coin('quarter', 25), Coin('dime', 10), Coin('nickel', 5), Coin('penny', 1, 'pennies') amnt = 99 buff = [] for coin in coins: (coin.count, amnt) = divmod(amnt, coin.value) d = coin.display() if d: buff.append(d) if len(buff) < 2: print buff else: print ', '.join(buff[:-1]) + " and " + buff[-1] > I use the list 'count' as a kind of array, so that e.g. count[-1] > is the number of pennies needed, count[2] is the number of dimes > needed, and so on. Any initial values I might store as elements > of the list are never used, hence the use of 'None'. (The use of > 'None' in the list 'plural' is much more defensible, I think, as > it is used to denote the formation of a regular plural by adding > 's' to the name.) Instead, the actual values are assigned in a > 'for' loop, as follows: > > for i in range(LEN - 1): > (count[i], amnt) = divmod(amnt, value[i]) > > This feels like a bit of a cheat, as if I am trying to program in > Python as if it were some other more familiar language. Should I > have coded this differently? > > The full source code is here, in case anyone wants to look at it > (but I'm not soliciting any more attention, as I've already been > given quite a lot of it, and fear being offered the comfy chair!): > (retention: 1 day) > > Could I have used dictionaries instead, with the denomination names > as keys? Is it possible to guarantee a sequence in which the keys > of a dictionary are iterated through? (If not, I suppose I could > keep the list 'denom' as it is here, and iterate through it with > "for key in denom:", although this seems a bit redundant.) > -- Bob Gailer Chapel Hill NC 919-636-4239 From roadierich at googlemail.com Mon Jul 6 06:22:50 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 6 Jul 2009 05:22:50 +0100 Subject: [Tutor] append question In-Reply-To: References: Message-ID: 2009/7/6 Steven Buck : > Thanks for the previous?responses.? This isn't homework--I'm beyond > coursework, although I am a newbie to Python (and I've never had to do much > real programming since I've just used Stata for econometric analysis).? I'm > testing Python as a more powerful alternative to Stata. > > I've learned from the responses I received, although now see my problem > differently.? The data structure I have?uses a dictionary and?know now > that?the append command?doesn't work.??Having said that, perhaps my > variables of interest have already been created--perhaps I just don't know > how to identify them.? I've been using some borrowed code to get me started; > my modified version is below: > > > import sys > > # The modules below help me get a .dta file into Python. > # Although I'm not sure what form they take; I suppose a list of lists??? > from StataTools import Reader > from StataTypes import MissingValue > > # I call my data set the psid (Panel Study of Income Dynamics) > # In Stata this would look like and NXK matrix (N observations and K > variables) > psid=Reader(file('data3.dta')) > > # I gather this next just creates a list of the variable names. > varnames=[x.name for x in psid.variables()] > > # It's not clear what these next two lines gain me. > labels=psid.file_headers()['vlblist'] > Labels=dict(zip(varnames,labels)) > > > ?From here, I'd like Python to identify the Nx1 vectors (or n-tuples) that > correspond to the varnames list defined above.? I can't seem grab the > vectors representing age, wage, etc..? I've tried things like > age,?psid['age'], psid.age.? My last email was an attempt to create the > vectors myself, although the Reader module puts the data in a dictionary > structure so the append command I was trying to use doesn't work. > > Hopefully once I learn to create and call on?my own vectors and matrices > I'll be better off--I'm comfortable working with these in MATLAB and Stata. > > Bottom line:? Given the above data I've imported/extracted from Stata .dta > file, how do I create an Nx1 vector? which I call 'age'? > > Thanks for your patience with this newbie. > Steve Sorry about suggesting this was homework... I noticed the word University, but not the line above it saying "PhD student"... If you're new to python, the standard path we recommend is to take an online tutorial. Dive into Python (http://www.diveintopython.org/) has been recommended for people with some programming experience, and Think Python for those without, although I'm sure that if you ask 10 members of this list, you'll get 20 different suggestions. Real veterans get pointed at the standard libraries, which are extremly well commented in the most part. I personally learned from the tutorial in the python documentation, but it does leave a fair bit of the thought processes involved in programming out. See what I mean? One person, three recomendations. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From cynicalairrick at gmail.com Mon Jul 6 08:48:11 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Sun, 5 Jul 2009 23:48:11 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? Message-ID: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> Hello all, this is my first time using a mailing list, so I'm not sure if I'm doing this right! Anyway, I have a wee bit of a problem. I've recently completed watching a Youtube video series on Python 2.6 by thenewboston which helped me a TON with learning Python's syntax and how to use some of the various builtin modules. I am very thankful for his tutorials, but the only thing that I need is something to help me really grasp onto the world of programming. (I'm new to programming) What I'm looking for is a tutorial series that walks you through the steps of writing a useful program in Python. Whether it be a text editor, a simple browser, etc, it doesn't really matter. I learned the syntax (at least most of it), but I guess I'm just looking for something to help me learn to "utilize it". Something to teach me how I can use everything I learned about manipulating strings, creating classes, and importing modules and how to stir it all up into something meaningful. Most people's answer to this kind of question is that the best way to learn is to "play around with it", but personally I believe that you can't really play with it if it you don't know where to start. If anyone has any idea on how I can really get started with programming useful programs, please do let me know! Any help would be immensely appreciated! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Mon Jul 6 10:37:10 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 06 Jul 2009 03:37:10 -0500 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> Message-ID: <4A51B7B6.7060805@gmail.com> Luis Galvan wrote: > Hello all, this is my first time using a mailing list, so I'm not sure > if I'm doing this right! Everything's fine except perhaps your formatting - it's easier to read e-mails that are delineated into paragraphs rather than just a single block of text. That may be a problem on my end, I'm not sure. > If anyone has any idea on how I can really get started with > programming useful programs, please do let me know! Any help would be > immensely appreciated! What sorts of things do you want to make? The most successful projects are usually borne from people's desire for a tool that doesn't exist yet. Or have you always wanted to make a video game? Those can be very satisfying first projects. There are very good tutorials available for beginning game development with Python + Pygame, and also look into Pyglet. One thing games do well is let you make that leap of understanding from just manipulating variables and lists and such to actually seeing the bigger picture and having those manipulations just be the behind-the-scenes implementation details to get to what you are really trying to do. From timomlists at gmail.com Mon Jul 6 10:48:48 2009 From: timomlists at gmail.com (Timo) Date: Mon, 06 Jul 2009 10:48:48 +0200 Subject: [Tutor] int to bytes and the other way around Message-ID: <4A51BA70.4080208@gmail.com> I have written a program that uses a C++ module as backend. Now I found out that I can use Python to call an underneath C lib. That's nice, so I don't need to Popen() the C++ module. I have a problem though with some info that is returned (always an integer). I'll try to explain a bit, this is what I found out so far. There are 4 options in the program. The first 3 options go up to 18 and the fourth to 7. If all options are set to 0, the returned int is 0. If the first option is set from 1 to 18, this is what I get returned. However, for option 2, I get 256, 512, 768, 1024, etc. For option 3 I get 65536, 131072, 196608, etc, etc. And for option 4: 16777216, 33554432, etc. Ok, that's nice so far. But if option 1 is set to 4 and option 2 is set to 8 and option 3 is set to 10 (for example), I get this returned: 657412 The C++ module counts the bytes. First byte = option1, second byte = option2 etc. u8 *options = (u8 *)&result[1]; option1 = options[0] option2 = options[1] option3 = options[2] option4 = options[3] How will I approach this in Python? From alan.gauld at btinternet.com Mon Jul 6 11:02:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Jul 2009 10:02:58 +0100 Subject: [Tutor] Python Tutorials: How to create useful programs afterlearning the syntax? References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> Message-ID: "Luis Galvan" wrote > Hello all, this is my first time using a mailing list, so I'm not sure if > I'm doing this right! Yep. You send a mail to the list, we reply,. Easy :-) One thing to remember is when you reply use "ReplyAll" on your mail tool, not simple Reply. > of programming. (I'm new to programming) What I'm looking for is a > tutorial > series that walks you through the steps of writing a useful program in > Python. Try the Case Study in my tutorial, iot tales you through what is supposed to be the typical evolution of an idea from a simple concept (a word counter) to something grander (a grammar counter) then adding a GUI front end. It is still somewhat contrioved since it is a beginners tutorial adfter all, but it might give you some ideas. There are also two rolling examples throughout the tutorial: - a simple multiplication table printer in the early topics - an address book which extends all the way to a full client-server database driven program. (Eventually it will have a GUI and web front end too! :-) > Whether it be a text editor, a simple browser, etc, Neither of those is particularly "simple"! You probably want to moderate your expectations for your first projects. > teach me how I can use everything I learned about manipulating strings, > creating classes, and importing modules and how to stir it all up into > something meaningful. Hopefully my case study covers all of those. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From buckstec at gmail.com Mon Jul 6 05:06:37 2009 From: buckstec at gmail.com (Steven Buck) Date: Sun, 5 Jul 2009 20:06:37 -0700 Subject: [Tutor] append question In-Reply-To: References: Message-ID: Thanks for the previous responses. This isn't homework--I'm beyond coursework, although I am a newbie to Python (and I've never had to do much real programming since I've just used Stata for econometric analysis). I'm testing Python as a more powerful alternative to Stata. I've learned from the responses I received, although now see my problem differently. The data structure I have uses a dictionary and know now that the append command doesn't work. Having said that, perhaps my variables of interest have already been created--perhaps I just don't know how to identify them. I've been using some borrowed code to get me started; my modified version is below: import sys # The modules below help me get a .dta file into Python. # Although I'm not sure what form they take; I suppose a list of lists??? from StataTools import Reader from StataTypes import MissingValue # I call my data set the psid (Panel Study of Income Dynamics) # In Stata this would look like and NXK matrix (N observations and K variables) psid=Reader(file('data3.dta')) # I gather this next just creates a list of the variable names. varnames=[ x.name for x in psid.variables()] # It's not clear what these next two lines gain me. labels=psid.file_headers()['vlblist'] Labels=dict(zip(varnames,labels)) From here, I'd like Python to identify the Nx1 vectors (or n-tuples) that correspond to the varnames list defined above. I can't seem grab the vectors representing age, wage, etc.. I've tried things like age, psid['age'], psid.age. My last email was an attempt to create the vectors myself, although the Reader module puts the data in a dictionary structure so the append command I was trying to use doesn't work. Hopefully once I learn to create and call on my own vectors and matrices I'll be better off--I'm comfortable working with these in MATLAB and Stata. Bottom line: Given the above data I've imported/extracted from Stata .dta file, how do I create an Nx1 vector which I call 'age'? Thanks for your patience with this newbie. Steve On Sun, Jul 5, 2009 at 5:19 PM, Rich Lovely wrote: > 2009/7/5 Steven Buck : > >>>> for i in len(test): > testvar2.append(test[i][2]) > > > > I want testvar2 = [2,5,8] but instead I get the following error message: > > > > Traceback (most recent call last): > > File "", line 1, in > > for i in len(test): > > TypeError: 'int' object is not iterable > > > > Any insight would be appreciated. > > Thanks > > Steve > > -- > > Steven Buck > > Ph.D. Student > > Department of Agricultural and Resource Economics > > University of California, Berkeley > > > This sounds like a homework assignment, and we're not supposed to give out > answers to homework. > > The error message and the docs explain what you're doing wrong if you > take a moment to look. > from http://www.python.org/doc/2.6/reference/compound_stmts.html#for > > """for_stmt ::= "for" target_list "in" expression_list ":" suite > ["else" ":" suite] > > The expression list is evaluated once; it should yield an iterable > object. An iterator is created for the result of the expression_list. > The suite is then executed once for each item provided by the > iterator, in the order of ascending indices. Each item in turn is > assigned to the target list using the standard rules for assignments, > and then the suite is executed.""" > > As Luke said, len returns an int, which as your error tells you, is > not iterable. From the same page: > """The for statement is used to iterate over the elements of a > sequence (such as a string, tuple or list) or other iterable > object:""" > > Therefore you have an iterable, there is no need to try and construct a new > one. > > Does that help? > > It is extremly unpythonic to iterate over range(len(...)), as it adds > in the overhead of two function calls, and ruins the readability of > code. The latter is probably the most important of the two. > > An even more pythonic way to do this would be a list comprehension, > > http://www.python.org/doc/2.6/tutorial/datastructures.html#list-comprehensions > > If it's not homework, let us know, and we'll be more than willing to > give you code if you still need it. > > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jul 6 12:50:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 6 Jul 2009 06:50:58 -0400 Subject: [Tutor] append question In-Reply-To: References: Message-ID: <1c2a2c590907060350h49c6050cqc783d8b1f5c38c56@mail.gmail.com> > 2009/7/6 Steven Buck : >> # I call my data set the psid (Panel Study of Income Dynamics) >> # In Stata this would look like and NXK matrix (N observations and K >> variables) >> psid=Reader(file('data3.dta')) >> >> # I gather this next just creates a list of the variable names. >> varnames=[x.name for x in psid.variables()] Yes, but psid.variables() is already a list of variable names, so you could just say varnames = psid.variables() >> ?From here, I'd like Python to identify the Nx1 vectors (or n-tuples) that >> correspond to the varnames list defined above.? I can't seem grab the >> vectors representing age, wage, etc..? I've tried things like >> age,?psid['age'], psid.age.? My last email was an attempt to create the >> vectors myself, although the Reader module puts the data in a dictionary >> structure so the append command I was trying to use doesn't work. psid.dataset() is the list of lists that you need to start. Try this: data = psid.dataset() ages = [ item[0] for item in data ] wages = [ item[1] for item in data ] This way of making a list is called a list comprehension, you can read about them here: http://docs.python.org/tutorial/datastructures.html#list-comprehensions Kent From kent37 at tds.net Mon Jul 6 13:04:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 6 Jul 2009 07:04:58 -0400 Subject: [Tutor] int to bytes and the other way around In-Reply-To: <4A51BA70.4080208@gmail.com> References: <4A51BA70.4080208@gmail.com> Message-ID: <1c2a2c590907060404h5493cdb2t4cc32303385dd5cb@mail.gmail.com> On Mon, Jul 6, 2009 at 4:48 AM, Timo wrote: > I have written a program that uses a C++ module as backend. Now I found out > that I can use Python to call an underneath C lib. That's nice, so I don't > need to Popen() the C++ module. > > I have a problem though with some info that is returned (always an integer). > I'll try to explain a bit, this is what I found out so far. > There are 4 options in the program. The first 3 options go up to 18 and the > fourth to 7. > If all options are set to 0, the returned int is 0. > If the first option is set from 1 to 18, this is what I get returned. > However, for option 2, I get 256, 512, 768, 1024, etc. > For option 3 I get 65536, 131072, 196608, etc, etc. > And for option 4: 16777216, 33554432, etc. > > Ok, that's nice so far. But if option 1 is set to 4 and option 2 is set to 8 > and option 3 is set to 10 (for example), I get this returned: 657412 > > The C++ module counts the bytes. First byte = option1, second byte = option2 > etc. > ? ? ? u8 *options = (u8 *)&result[1]; > ? ? ? option1 = options[0] > ? ? ? option2 = options[1] > ? ? ? option3 = options[2] > ? ? ? option4 = options[3] > > How will I approach this in Python? Looks like you need the struct module. Kent From bgailer at gmail.com Mon Jul 6 15:04:05 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 06 Jul 2009 09:04:05 -0400 Subject: [Tutor] Poor style to use list as "array"? CORRECTION In-Reply-To: <4A516D2E.7040702@gmail.com> References: <4A516D2E.7040702@gmail.com> Message-ID: <4A51F645.1050709@gmail.com> class Coin: def __init__(self, name, value, plural=None): self.name = name self.value = value if plural: self.plural = plural else: self.plural = self.name + 's' self.count = 0 def display(self): if self.count == 0: return None if self.count == 1: return "%d %s" % (self.count, name) else: return "%d %s" % (self.count, self.plural) #### next line unindented ### coins = Coin('dollar', 100), Coin('quarter', 25), Coin('dime', 10), Coin('nickel', 5), Coin('penny', 1, 'pennies') amnt = 99 buff = [] for coin in coins: (coin.count, amnt) = divmod(amnt, coin.value) d = coin.display() if d: buff.append(d) if len(buff) < 2: print buff else: print ', '.join(buff[:-1]) + " and " + buff[-1] -- Bob Gailer Chapel Hill NC 919-636-4239 From hyou00 at hotmail.com Mon Jul 6 15:50:01 2009 From: hyou00 at hotmail.com (hyou) Date: Mon, 6 Jul 2009 09:50:01 -0400 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: <1246726629.5774.14.camel@infirit.homelinux.org> References: <1246726629.5774.14.camel@infirit.homelinux.org> Message-ID: Hi Sander, Do I post to the list by also replying to Python Tutor List? Thanks for the answer! I found the problem was because I put the 2nd argument to Popen with Shell = true. Though I'm not sure why it doesn't work with Shell = true while the same setting works for other commands. Thanks again and have a great week! Cheers, Shawn P.S. If you know the reason why some command works for Shell = true some not, please let me know! -----Original Message----- From: Sander Sweers [mailto:sander.sweers at gmail.com] Sent: Saturday, July 04, 2009 12:57 PM To: Shawn Gong Cc: Python Tutor List Subject: Re: [Tutor] Popen problem with a pipe sign "|" Again, You need to also post to the list!! On Fri, 2009-07-03 at 22:32 -0400, Shawn Gong wrote: > I see what you mean. However in my case the | sign simply constitute an > argument. I'm actually calling devenv.com, which is the MS VS2005's building > command. The whole command looks like: > "...\devenv.com" solution.sln /build "Debug|Win32" > If I sub "Debug|Win32" with Debug only, it works fine. But whenever I add > the |, nothing seems to run. Ah, ok now I get what your problem is. I do not know why that would not work. Can you show the actual code you have? Do you have the command in a list? See below an *untested* example, does this work? command = ['C:\\...\\devenv', 'solution.sln', '/build', 'Debug|Win32'] proc = subprocess.Popen(command, stdout=subporcess.PIPE, stderr=subporcess.PIPE, stdin=subporcess.PIPE) stdout, stderr = proc.communicate() From sander.sweers at gmail.com Mon Jul 6 16:22:46 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 6 Jul 2009 16:22:46 +0200 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: References: <1246726629.5774.14.camel@infirit.homelinux.org> Message-ID: 2009/7/6 hyou : > Do I post to the list by also replying to Python Tutor List? Yes, thanks. > Thanks for the answer! I found the problem was because I put the 2nd > argument to Popen with Shell = true. Though I'm not sure why it doesn't work > with Shell = true while the same setting works for other commands. You can read up on subprocess on [1]. I do not understand why this does not work with shell=True. My best guess is that it gets interpreted as a pipe. Greets Sander [1] http://docs.python.org/library/subprocess.html From mail at timgolden.me.uk Mon Jul 6 16:27:02 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 06 Jul 2009 15:27:02 +0100 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: References: <1246726629.5774.14.camel@infirit.homelinux.org> Message-ID: <4A5209B6.5070301@timgolden.me.uk> hyou wrote: > Thanks for the answer! I found the problem was because I put the 2nd > argument to Popen with Shell = true. Though I'm not sure why it doesn't work > with Shell = true while the same setting works for other commands. There's a long-outstanding bug when shell=True is passed to subprocess.Popen on Windows such that the rest of the line isn't quoted correctly (ie doesn't cope with special chars such as space, pipe and ampersand). In general, you almost never need to pass shell=True on Windows. The latest docs have just been updated with a patch I wrote to that effect, but it basically says: don't use shell=True unless you know you need to. TJG From bermanrl at cfl.rr.com Mon Jul 6 17:09:40 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Mon, 06 Jul 2009 11:09:40 -0400 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> Message-ID: <1246892980.14209.29.camel@bermanrl-desktop> I have programmed since I was 21. Since I am now retired; that gives me a tad of experience in some aspects of coding. I have only been using Python for two years and I enjoy it for two reasons; the first and most important is it is fun. if you don't enjoy the language, find another one you do enjoy. And, finally, it is a language that lends itself to some really creative solutions. I do not know if your interest extends to games, designing user Graphical input programs, or puzzle solving. I have done two for most of my professional life; games are not at all my forte. I am impressed with them (my wife loves them, but I have neither the artistic design skills or the patience). I have worked primarily as a consultant to law enforcement and have designed and implemented juvenile justice systems, and done work in both drug rehabilitation database studies, and child support studies as well. Now, my interest has turned to puzzle solving and I feel this is a wonderful method to hone your skills. I would suggest, if this at all piques your interest, you take a look at the following sites. The order is of no bearing at all. What I find complex you will not, so these suggestions I simply pulled from my bookmarks and hope they might give you both asistance and simple pleasure 1. http://www.challenge-you.com/ 2. http://projecteuler.net/index.php?section=logout 3. http://www.spoj.pl/problems/classical/ 4. http://codegolf.com/ 5. http://www.codechef.com/ These will certainly keep you occupied for many hours, days, weeks, etc. Enjoy, Robert On Sun, 2009-07-05 at 23:48 -0700, Luis Galvan wrote: > Hello all, this is my first time using a mailing list, so I'm not sure > if I'm doing this right! Anyway, I have a wee bit of a problem. I've > recently completed watching a Youtube video series on Python 2.6 by > thenewboston which helped me a TON with learning Python's syntax and > how to use some of the various builtin modules. I am very thankful > for his tutorials, but the only thing that I need is something to help > me really grasp onto the world of programming. (I'm new to > programming) What I'm looking for is a tutorial series that walks you > through the steps of writing a useful program in Python. Whether it > be a text editor, a simple browser, etc, it doesn't really matter. I > learned the syntax (at least most of it), but I guess I'm just looking > for something to help me learn to "utilize it". Something to teach me > how I can use everything I learned about manipulating strings, > creating classes, and importing modules and how to stir it all up into > something meaningful. Most people's answer to this kind of question > is that the best way to learn is to "play around with it", but > personally I believe that you can't really play with it if it you > don't know where to start. If anyone has any idea on how I can really > get started with programming useful programs, please do let me know! > Any help would be immensely appreciated! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From hyou00 at hotmail.com Mon Jul 6 16:40:35 2009 From: hyou00 at hotmail.com (hyou) Date: Mon, 6 Jul 2009 10:40:35 -0400 Subject: [Tutor] Popen problem with a pipe sign "|" In-Reply-To: References: <1246726629.5774.14.camel@infirit.homelinux.org> Message-ID: Hi Sander, My guess is that the two shell options must be treating the command string differently, thus the "|" sign has different functionalities on them. Thanks! Shawn -----Original Message----- From: Sander Sweers [mailto:sander.sweers at gmail.com] Sent: Monday, July 06, 2009 10:23 AM To: hyou Cc: Python Tutor List Subject: Re: [Tutor] Popen problem with a pipe sign "|" 2009/7/6 hyou : > Do I post to the list by also replying to Python Tutor List? Yes, thanks. > Thanks for the answer! I found the problem was because I put the 2nd > argument to Popen with Shell = true. Though I'm not sure why it doesn't work > with Shell = true while the same setting works for other commands. You can read up on subprocess on [1]. I do not understand why this does not work with shell=True. My best guess is that it gets interpreted as a pipe. Greets Sander [1] http://docs.python.org/library/subprocess.html From angusr at bigfoot.com Mon Jul 6 17:48:13 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Mon, 06 Jul 2009 16:48:13 +0100 Subject: [Tutor] Poor style to use list as "array"? In-Reply-To: References: <1c2a2c590907051549j6da673dere006318f70568ef7@mail.gmail.com> <7be2551mqdvmk0lj02a90gsde2l036dojc@4ax.com> Message-ID: On Mon, 6 Jul 2009 01:51:22 +0100, Rich Lovely wrote: [I wrote:] >> ? ? ? ? ? ? ? ?if name in plural: >> ? ? ? ? ? ? ? ? ? ?name = plural[name] >> ? ? ? ? ? ? ? ?else: >> ? ? ? ? ? ? ? ? ? ?name += 's' >This could be written more cleanly (although arguably not as readably) as > >name = plural.get(name, name + "s") Nice, and readable enough, I think. >d.get(key, default) returns the value from d mapped to key if it >exists, or default otherwise. > >You might also want to split your calculation and display code into >two separate loops. This might seem wasteful, but it will make your >code easier to read and maintain, and the waste is only marginal with >the loops you're running - there is a maximum of only 17 passes (once >for each value of coin and note) If I understand you correctly, this is the same idea as Bob Gailer used in his code - in which 'buff' becomes a list, instead of (as in my code) a string, formatted for printing. It certainly seems to simplify the whole thing enormously: (retention: 1 day) (Ignore the boilerplate!) Thanks to all of you. I haven't adopted the suggestion of using classes, which I think I'll leave for when I'm reading the later chapters of the book (although I do get the gist of the idea). -- Angus Rodgers From roadierich at googlemail.com Mon Jul 6 18:24:52 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Mon, 6 Jul 2009 17:24:52 +0100 Subject: [Tutor] int to bytes and the other way around In-Reply-To: <4A51BA70.4080208@gmail.com> References: <4A51BA70.4080208@gmail.com> Message-ID: 2009/7/6 Timo : > I have written a program that uses a C++ module as backend. Now I found out > that I can use Python to call an underneath C lib. That's nice, so I don't > need to Popen() the C++ module. > > I have a problem though with some info that is returned (always an integer). > I'll try to explain a bit, this is what I found out so far. > There are 4 options in the program. The first 3 options go up to 18 and the > fourth to 7. > If all options are set to 0, the returned int is 0. > If the first option is set from 1 to 18, this is what I get returned. > However, for option 2, I get 256, 512, 768, 1024, etc. > For option 3 I get 65536, 131072, 196608, etc, etc. > And for option 4: 16777216, 33554432, etc. > > Ok, that's nice so far. But if option 1 is set to 4 and option 2 is set to 8 > and option 3 is set to 10 (for example), I get this returned: 657412 > > The C++ module counts the bytes. First byte = option1, second byte = option2 > etc. > ? ? ? u8 *options = (u8 *)&result[1]; > ? ? ? option1 = options[0] > ? ? ? option2 = options[1] > ? ? ? option3 = options[2] > ? ? ? option4 = options[3] > > How will I approach this in Python? > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > import itertools i = iter(reversed(hex(657412)[2:])) optlList = map(lambda (m, n): int(n+m, 16), itertools.izip_longest(i,i, fillvalue="0")) This will give you a list of the options. You will need to check to see if all four options are present. Another way would be to use bitshifting and masking: opt1= options & 0xff opt2 = (options >> 8) & 0xff opt3 = (options >> 16) & 0xff opt4 = (options >> 24) & 0xff I personally prefer the former method, as you won't need to change it if you introduce a fifth (or more) options, but I think the second is probably more reliable, and easier to extend if you need options that use more than a single byte. It is also maybe slightly easier to read and understand. Alternatively, to go the otherway (you aren't quite clear which way you want to go) opt1 thru opt4 are the original values (1-18 or 1-7) options = opt1 | (opt2<<8) | (opt3<<16) | (opt4<<24) Or, you seeing as you appear to be treating your options as (effectively) a char[]: options = "".join(chr(x) for x in (opt4, opt3, opt2, opt1)) Alternatively, like Kent said, take a look at the struct module, which will do all this for you, but is not so educational. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From cfuller084 at thinkingplanet.net Mon Jul 6 19:39:44 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 6 Jul 2009 12:39:44 -0500 Subject: [Tutor] int to bytes and the other way around In-Reply-To: <4A51BA70.4080208@gmail.com> References: <4A51BA70.4080208@gmail.com> Message-ID: <200907061239.44414.cfuller084@thinkingplanet.net> The only things that matter are the arguments and the result. It sounds to me like a good case use for SWIG (http:://www.swig.org). You can do really complicated stuff with swig, and it takes a correspondingly steep learning curve to achieve, but doing simple stuff is really simple. It sounds like the first example in the SWIG docs could be straightforwardly adapted to your problem. Cheers From davidkim05 at gmail.com Mon Jul 6 23:54:58 2009 From: davidkim05 at gmail.com (David Kim) Date: Mon, 6 Jul 2009 17:54:58 -0400 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! Message-ID: Hello all, I have two questions I'm hoping someone will have the patience to answer as an act of mercy. I. How to get past a Terms of Service page? I've just started learning python (have never done any programming prior) and am trying to figure out how to open or download a website to scrape data. The only problem is, whenever I try to open the link (via urllib2, for example) I'm after, I end up getting the HTML to a Terms of Service Page (where one has to click an "I Agree" button) rather than the actual target page. I've seen examples on the web on providing data for forms (typically by finding the name of the form and providing some sort of dictionary to fill in the form fields), but this simple act of getting past "I Agree" is stumping me. Can anyone save my sanity? As a workaround, I've been using os.popen('curl ' + url ' >' filename) to save the html in a txt file for later processing. I have no idea why curl works and urllib2, for example, doesn't (I use OS X). I even tried to use Yahoo Pipes to try and sidestep coding anything altogether, but ended up looking at the same Terms of Service page anyway. Here's the code (tho it's probably not that illuminating since it's basically just opening a url): import urllib2 url = 'http://www.dtcc.com/products/derivserv/data_table_i.php?id=table1' #the first of 23 tables html = urllib2.urlopen(url).read() II. How to parse html tables with lxml, beautifulsoup? (for dummies) Assuming i get past the Terms of Service, I'm a bit overwhelmed by the need to know XPath, CSS, XML, DOM, etc. to scrape data from the web. I've tried looking at the documentation included with different python libraries, but just got more confused. The basic tutorials show something like the following: from lxml import html doc = html.parse("/path/to/test.txt") #the file i downloaded via curl root = doc.getroot() #what is this root business? tables = root.cssselect('table') I understand that selecting all the table tags will somehow target however many tables on the page. The problem is the table has multiple headers, empty cells, etc. Most of the examples on the web have to do with scraping the web for search results or something that don't really depend on the table format for anything other than layout. Are there any resources out there that are appropriate for web/python illiterati like myself that deal with structured data as in the url above? FYI, the data in the url above goes up in smoke every week, so I'm trying to capture it automatically on a weekly basis. Getting all of it into a CSV or database would be a personal cause for celebration as it would be the first really useful thing I've done with python since starting to learn it a few months ago. For anyone who is interested, here is the code that uses "curl" to pull the webpages. It basically just builds the url string for the different table-pages and saves down the file with a timestamped filename: import os from time import strftime BASE_URL = 'http://www.dtcc.com/products/derivserv/data_table_' SECTIONS = {'section1':{'select':'i.php?id=table', 'id':range(1,9)}, 'section2':{'select':'ii.php?id=table', 'id':range(9,17)}, 'section3':{'select':'iii.php?id=table', 'id':range(17,24)} } def get_pages(): filenames = [] path = '~/Dev/Data/DTCC_DerivServ/' #os.popen('cd ' + path) for section in SECTIONS: for id in SECTIONS[section]['id']: #urlList.append(BASE_URL + SECTIONS[section]['select']+str(id)) url = BASE_URL + SECTIONS[section]['select'] + str(id) timestamp = strftime('%Y%m%d_') #sectionName = BASE_URL.split('/')[-1] sectionNumber = SECTIONS[section]['select'].split('.')[0] tableNumber = str(id) + '_' filename = timestamp + tableNumber + sectionNumber + '.txt' os.popen('curl ' + url + '> ' + path + filename) filenames.append(filename) return filenames if (__name__ == '__main__'): get_pages() -- morenotestoself.wordpress.com From stefan_ml at behnel.de Tue Jul 7 07:35:07 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 07 Jul 2009 07:35:07 +0200 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! In-Reply-To: References: Message-ID: Hi, David Kim wrote: > I have two questions I'm hoping someone will have the patience to > answer as an act of mercy. > > I. How to get past a Terms of Service page? > > I've just started learning python (have never done any programming > prior) and am trying to figure out how to open or download a website > to scrape data. The only problem is, whenever I try to open the link > (via urllib2, for example) I'm after, I end up getting the HTML to a > Terms of Service Page (where one has to click an "I Agree" button) > rather than the actual target page. One comment to make here is that you should first read that page and check if the provider of the service actually allows you to automatically download content, or to use the service in the way you want. This is totally up to them, and if their terms of service state that you must not do that, well, then you must not do that. Once you know that it's permitted, you can read the ToS page and search for the form that the "Agree" button triggers. The URL given there is the one you have to read next, but augmented with the parameter ("?xyz=...") that the button sends. > I've seen examples on the web on providing data for forms (typically > by finding the name of the form and providing some sort of dictionary > to fill in the form fields), but this simple act of getting past "I > Agree" is stumping me. Can anyone save my sanity? As a workaround, > I've been using os.popen('curl ' + url ' >' filename) to save the html > in a txt file for later processing. I have no idea why curl works and > urllib2, for example, doesn't (I use OS X). There may be different reasons for that. One is that web servers often present different content based on the client identifier. So if you see one page with one client, and another page with a different client, that may be the reason. > Here's the code (tho it's probably not that illuminating since it's > basically just opening a url): > > import urllib2 > url = 'http://www.dtcc.com/products/derivserv/data_table_i.php?id=table1' > #the first of 23 tables > html = urllib2.urlopen(url).read() Hmmm, if what you want is to read a stock ticker or something like that, you should *really* read their ToS first and make sure they do not disallow automated access. Because it's actually quite likely that they do. > II. How to parse html tables with lxml, beautifulsoup? (for dummies) > > Assuming i get past the Terms of Service, I'm a bit overwhelmed by the > need to know XPath, CSS, XML, DOM, etc. to scrape data from the web. Using CSS selectors (lxml.cssselect) is not at all hard. You basically express the page structure in a *very* short and straight forward way. Searching the web for a CSS selectors tutorial should give you a few hits. > The basic tutorials show something like the following: > > from lxml import html > doc = html.parse("/path/to/test.txt") #the file i downloaded via curl ... or read from the standard output pipe of curl. Note that there is a stdlib module called "subprocess", which may make running curl easier. Once you've determined the final URL to parse, you can also push it right into lxml's parse() function, instead of going through urllib2 or an external tool. Example: url = "http://pypi.python.org/pypi?%3Aaction=search&term=lxml" doc = html.parse(url) > root = doc.getroot() #what is this root business? The root (or top-most) node of the document you just parsed. Usually an "html" tag in HTML pages. > tables = root.cssselect('table') Simple, isn't it? :) BTW, did you look at this? http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/ > I understand that selecting all the table tags will somehow target > however many tables on the page. The problem is the table has multiple > headers, empty cells, etc. Most of the examples on the web have to do > with scraping the web for search results or something that don't > really depend on the table format for anything other than layout. That's because in cases like yours, you have to do most of the work yourself anyway. No page is like the other, so you have to find your way through the structure and figure out fixed points that allow you to get to the data. Stefan From stefan_ml at behnel.de Tue Jul 7 07:48:43 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 07 Jul 2009 07:48:43 +0200 Subject: [Tutor] int to bytes and the other way around In-Reply-To: <200907061239.44414.cfuller084@thinkingplanet.net> References: <4A51BA70.4080208@gmail.com> <200907061239.44414.cfuller084@thinkingplanet.net> Message-ID: Chris Fuller wrote: > The only things that matter are the arguments and the result. It sounds to me > like a good case use for SWIG (http:://www.swig.org). You can do really > complicated stuff with swig, and it takes a correspondingly steep learning > curve to achieve, but doing simple stuff is really simple. It sounds like > the first example in the SWIG docs could be straightforwardly adapted to your > problem. I think the OP was already talking about a ctypes based solution. If that's all the OP needs, that's just fine, and will work out-of-the-box without depending on things like a C++ compiler. Regarding SWIG, you are definitely right about the "steep learning curve" and the "complicated stuff". If you want to just get your work done, it's usually better to go with Cython directly, instead of trying hard to make SWIG do what you want. Because once you get to the "complicated stuff", you will (hopefully) take the shortcut of rewriting your code in Cython anyway. Stefan From cynicalairrick at gmail.com Tue Jul 7 09:11:17 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Tue, 7 Jul 2009 00:11:17 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <4A51B7B6.7060805@gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <4A51B7B6.7060805@gmail.com> Message-ID: <5cd723fd0907070011n22ec64eake423c1f044d91564@mail.gmail.com> Thanks for the responses! :) Hopefully Gmail's quoting feature shows up just fine. 1. http://www.challenge-you.com/ >> 2. http://projecteuler.net/index.php?section=logout >> 3. http://www.spoj.pl/problems/classical/ >> 4. http://codegolf.com/ >> 5. http://www.codechef.com/ >> >> These will certainly keep you occupied for many hours, days, weeks, etc >> > Simply a very interesting way to learn Python! Thank you for these links! Definitely will have to check them out. Try the Case Study in my tutorial, iot tales you through what is > supposed to be the typical evolution of an idea from a simple concept > (a word counter) to something grander (a grammar counter) then > adding a GUI front end. It is still somewhat contrioved since it is a > beginners tutorial adfter all, but it might give you some ideas. > > There are also two rolling examples throughout the tutorial: > - a simple multiplication table printer in the early topics > - an address book which extends all the way to a full client-server > database driven program. (Eventually it will have a GUI and web > front end too! :-) Can't believe I've never bumped into your tutorial, simply a very informative read. I've skimmed over some and I've got to say that it does help quite a bit, being an aspiring "hobbyist" programmer. Once I get more free time I'll definitely have to give it a deeper read. Thanks! Whether it be a text editor, a simple browser, etc, >> > > Neither of those is particularly "simple"! You probably want to > moderate your expectations for your first projects. Sorry about that. Being a new programmer, you tend to underestimate the difficulty various applications take to write. Point taken though, I'm definitely starting small. I guess what I meant by that small string of text you quoted is "Where can I start?", though your Case Study seems to be a very descriptive text on this subject. What sorts of things do you want to make? The most successful projects are > usually borne from people's desire for a tool that doesn't exist yet. > Or have you always wanted to make a video game? Those can be very > satisfying first projects. There are very good tutorials available for > beginning game development with Python + Pygame, and also look into Pyglet. > Thanks for that question actually, forgot to mention what my goals are. The reason I became interested in programming is from my desire for an XML editor for a PC game I enjoy playing (Zoo Tycoon 2). The game's various attributes such as life, hunger, cost for adoption, etc are stored as XML elements and by modifying these elements it's possible to create new animals or other content (I just add the 3D models). All this isn't new in PC games of course, but the modding community for ZT2 doesn't really have any programmers that I know of, so any similar editor such as the one I want to make doesn't exist for us. To achieve this goal, apart from starting small with simple applications, I began to study XML parsing. It's a bit daunting to me for now, but I think I can make it if I refer to my Python notes (I took notes while watching the Python video series) to keep my knowledge "fresh" :). What else would you recommend I study aside from XML parsing? (Am I doing good in learning XML parsing for this to begin with?) -------------- next part -------------- An HTML attachment was scrubbed... URL: From cynicalairrick at gmail.com Tue Jul 7 09:11:29 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Tue, 7 Jul 2009 00:11:29 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <1246892980.14209.29.camel@bermanrl-desktop> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <1246892980.14209.29.camel@bermanrl-desktop> Message-ID: <5cd723fd0907070011k6fcf6c3fi6004b4fe68f8cc72@mail.gmail.com> Thanks for the responses! :) Hopefully Gmail's quoting feature shows up just fine. 1. http://www.challenge-you.com/ >> 2. http://projecteuler.net/index.php?section=logout >> 3. http://www.spoj.pl/problems/classical/ >> 4. http://codegolf.com/ >> 5. http://www.codechef.com/ >> >> These will certainly keep you occupied for many hours, days, weeks, etc >> > Simply a very interesting way to learn Python! Thank you for these links! Definitely will have to check them out. Try the Case Study in my tutorial, iot tales you through what is > supposed to be the typical evolution of an idea from a simple concept > (a word counter) to something grander (a grammar counter) then > adding a GUI front end. It is still somewhat contrioved since it is a > beginners tutorial adfter all, but it might give you some ideas. > > There are also two rolling examples throughout the tutorial: > - a simple multiplication table printer in the early topics > - an address book which extends all the way to a full client-server > database driven program. (Eventually it will have a GUI and web > front end too! :-) Can't believe I've never bumped into your tutorial, simply a very informative read. I've skimmed over some and I've got to say that it does help quite a bit, being an aspiring "hobbyist" programmer. Once I get more free time I'll definitely have to give it a deeper read. Thanks! Whether it be a text editor, a simple browser, etc, >> > > Neither of those is particularly "simple"! You probably want to > moderate your expectations for your first projects. Sorry about that. Being a new programmer, you tend to underestimate the difficulty various applications take to write. Point taken though, I'm definitely starting small. I guess what I meant by that small string of text you quoted is "Where can I start?", though your Case Study seems to be a very descriptive text on this subject. What sorts of things do you want to make? The most successful projects are > usually borne from people's desire for a tool that doesn't exist yet. > Or have you always wanted to make a video game? Those can be very > satisfying first projects. There are very good tutorials available for > beginning game development with Python + Pygame, and also look into Pyglet. > Thanks for that question actually, forgot to mention what my goals are. The reason I became interested in programming is from my desire for an XML editor for a PC game I enjoy playing (Zoo Tycoon 2). The game's various attributes such as life, hunger, cost for adoption, etc are stored as XML elements and by modifying these elements it's possible to create new animals or other content (I just add the 3D models). All this isn't new in PC games of course, but the modding community for ZT2 doesn't really have any programmers that I know of, so any similar editor such as the one I want to make doesn't exist for us. To achieve this goal, apart from starting small with simple applications, I began to study XML parsing. It's a bit daunting to me for now, but I think I can make it if I refer to my Python notes (I took notes while watching the Python video series) to keep my knowledge "fresh" :). What else would you recommend I study aside from XML parsing? (Am I doing good in learning XML parsing for this to begin with?) -------------- next part -------------- An HTML attachment was scrubbed... URL: From vishnu.s.16 at gmail.com Tue Jul 7 12:09:47 2009 From: vishnu.s.16 at gmail.com (Vishnu S) Date: Tue, 7 Jul 2009 15:39:47 +0530 Subject: [Tutor] HI Message-ID: Sir/Madame, i'm a begginner to Python help me in putting the first step to this world With regards Vishnu S -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Tue Jul 7 12:16:41 2009 From: washakie at gmail.com (John [H2O]) Date: Tue, 7 Jul 2009 03:16:41 -0700 (PDT) Subject: [Tutor] using datetime and calculating hourly average Message-ID: <24370537.post@talk.nabble.com> Here's a function I wrote to calculate hourly averages: It seems a bit slow, however... any thoughts on how to improve it? def calc_hravg(X): """Calculates hourly average from input data""" X_hr = [] minX = X[:,0].min() hr = dt.datetime(*minX.timetuple()[0:4]) while hr <= dt.datetime(*X[-1,0].timetuple()[0:4]): nhr = hr + dt.timedelta(hours=1) ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) vals = X[ind,1][0].T try: #hr_avg = np.sum(vals) / len(vals) hr_avg = np.average(vals) except: hr_avg = np.nan X_hr.append([hr,hr_avg]) hr = hr + dt.timedelta(hours=1) return np.array(X_hr) -- View this message in context: http://www.nabble.com/using-datetime-and-calculating-hourly-average-tp24370537p24370537.html Sent from the Python - tutor mailing list archive at Nabble.com. From a.t.hofkamp at tue.nl Tue Jul 7 12:39:33 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 07 Jul 2009 12:39:33 +0200 Subject: [Tutor] HI In-Reply-To: References: Message-ID: <4A5325E5.9060809@tue.nl> Vishnu S wrote: > Sir/Madame, > i'm a begginner to Python > help me in putting the first step to this world Welcome! A useful first page may be http://wiki.python.org/moin/BeginnersGuide for an overview, and http://wiki.python.org/moin/BeginnersGuide/NonProgrammers where you can find a lot of links to Python tutorials. Read one you like, download Python, and start experimenting and/or solving exercises and/or solving problems you like to solve. When you get stuck, explain us your problem (usually wih a example program), and we will try to answer your question. Albert From kent37 at tds.net Tue Jul 7 13:26:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 7 Jul 2009 07:26:10 -0400 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! In-Reply-To: References: Message-ID: <1c2a2c590907070426m40f74bbdm5bb65a38634293a1@mail.gmail.com> On Mon, Jul 6, 2009 at 5:54 PM, David Kim wrote: > Hello all, > > I have two questions I'm hoping someone will have the patience to > answer as an act of mercy. > > I. How to get past a Terms of Service page? > > I've just started learning python (have never done any programming > prior) and am trying to figure out how to open or download a website > to scrape data. The only problem is, whenever I try to open the link > (via urllib2, for example) I'm after, I end up getting the HTML to a > Terms of Service Page (where one has to click an "I Agree" button) > rather than the actual target page. > > I've seen examples on the web on providing data for forms (typically > by finding the name of the form and providing some sort of dictionary > to fill in the form fields), but this simple act of getting past "I > Agree" is stumping me. Can anyone save my sanity? As a workaround, > I've been using os.popen('curl ' + url ' >' filename) to save the html > in a txt file for later processing. I have no idea why curl works and > urllib2, for example, doesn't (I use OS X). curl works because it ignores the redirect to the ToS page, and the site is (astoundingly) dumb enough to serve the content with the redirect. You could make urllib2 behave the same way by defining a 302 handler that does nothing. > I even tried to use Yahoo > Pipes to try and sidestep coding anything altogether, but ended up > looking at the same Terms of Service page anyway. > > Here's the code (tho it's probably not that illuminating since it's > basically just opening a url): > > import urllib2 > url = 'http://www.dtcc.com/products/derivserv/data_table_i.php?id=table1' > #the first of 23 tables > html = urllib2.urlopen(url).read() Generally you have to post to the same url as the form, giving the same data the form does. You can inspect the source of the form to figure this out. In this case the form is
You generally need to enable cookie support in urllib2 as well, because the site will use a cookie to flag that you saw the consent form. This tutorial shows how to enable cookies and submit form data: http://personalpages.tds.net/~kent37/kk/00010.html Kent From M8R-sjkk73 at mailinator.com Tue Jul 7 14:54:02 2009 From: M8R-sjkk73 at mailinator.com (M8R-sjkk73) Date: Tue, 7 Jul 2009 05:54:02 -0700 (PDT) Subject: [Tutor] cx_oracle module problems In-Reply-To: <1223405199.21522.4.camel@jeremiah-laptop> References: <1223405199.21522.4.camel@jeremiah-laptop> Message-ID: <24372780.post@talk.nabble.com> The $ORACLE_HOME variable probably isn't set for root. Try passing sudo the $ORACLE_HOME variable. sudo env ORACLE_HOME=$ORACLE_HOME python setup.py install - or - sudo env ORACLE_HOME=/path/to/instantclient python setup.py install Jeremiah Jester wrote: > > I've downloaded the cx_oracle source module for python, howerver every > time i try to build it, it keeps on failing. I've been unable to find a > port for Ubuntu. Is there one? Anyone know how to get this properly > installed? > > # sudo python setup.py install > Traceback (most recent call last): > File "setup.py", line 36, in > oracleHome = os.environ["ORACLE_HOME"] > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'ORACLE_HOME' > > > Link: > http://prdownloads.sourceforge.net/cx-oracle/cx_Oracle-4.2.tar.gz?download > > Thanks, > JJ > > > > Disclaimer: The information contained in this transmission, including any > attachments, may contain confidential information of Panasonic Avionics > Corporation. This transmission is intended only for the use of the > addressee(s) listed above. Unauthorized review, dissemination or other > use > of the information contained in this transmission is strictly prohibited. > If you have received this transmission in error or have reason to believe > you are not authorized to receive it, please notify the sender by return > email and promptly delete the transmission. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- View this message in context: http://www.nabble.com/cx_oracle-module-problems-tp19864731p24372780.html Sent from the Python - tutor mailing list archive at Nabble.com. From bgailer at gmail.com Tue Jul 7 17:09:57 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 07 Jul 2009 11:09:57 -0400 Subject: [Tutor] using datetime and calculating hourly average In-Reply-To: <24370537.post@talk.nabble.com> References: <24370537.post@talk.nabble.com> Message-ID: <4A536545.7060705@gmail.com> John [H2O] wrote: > Here's a function I wrote to calculate hourly averages: > > It seems a bit slow, however... any thoughts on how to improve it? > > def calc_hravg(X): > """Calculates hourly average from input data""" > > X_hr = [] > minX = X[:,0].min() > hr = dt.datetime(*minX.timetuple()[0:4]) > > while hr <= dt.datetime(*X[-1,0].timetuple()[0:4]): > nhr = hr + dt.timedelta(hours=1) > ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) > vals = X[ind,1][0].T > try: > #hr_avg = np.sum(vals) / len(vals) > hr_avg = np.average(vals) > > except: > hr_avg = np.nan > X_hr.append([hr,hr_avg]) > hr = hr + dt.timedelta(hours=1) > > return np.array(X_hr) > > > Someone else may know exactly what data you are working with and what you have imported, but I, for one?, don't. Please show us more of the program, including the import statement(s), and some sample input data. What leads you to think is is slow? One opportunity for improvement - take the invariant out of the while statement. q = dt.datetime(*X[-1,0].timetuple()[0:4]) while hr q: -- Bob Gailer Chapel Hill NC 919-636-4239 From washakie at gmail.com Tue Jul 7 17:33:03 2009 From: washakie at gmail.com (John [H2O]) Date: Tue, 7 Jul 2009 08:33:03 -0700 (PDT) Subject: [Tutor] using datetime and calculating hourly average In-Reply-To: <4A536545.7060705@gmail.com> References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com> Message-ID: <24375619.post@talk.nabble.com> The data is just x,y data where x = datetime objects from the datetime module. y are just floats. It is bundled in a numpy array. So the only import statements are: import datetime as dt import numpy as np I pass the array X, where X is a numpy array of shape [n,2] where n is the number of points in the data. As for your comment regarding the invariant... would it be: while hr q: NOT while hr not q: The latter makes more sense to me, but I'm not familiar with this approach... Thanks, john Bob Gailer wrote: > > John [H2O] wrote: >> Here's a function I wrote to calculate hourly averages: >> >> It seems a bit slow, however... any thoughts on how to improve it? >> >> def calc_hravg(X): >> """Calculates hourly average from input data""" >> >> X_hr = [] >> minX = X[:,0].min() >> hr = dt.datetime(*minX.timetuple()[0:4]) >> >> while hr <= dt.datetime(*X[-1,0].timetuple()[0:4]): >> nhr = hr + dt.timedelta(hours=1) >> ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) >> vals = X[ind,1][0].T >> try: >> #hr_avg = np.sum(vals) / len(vals) >> hr_avg = np.average(vals) >> >> except: >> hr_avg = np.nan >> X_hr.append([hr,hr_avg]) >> hr = hr + dt.timedelta(hours=1) >> >> return np.array(X_hr) >> >> >> > Someone else may know exactly what data you are working with and what > you have imported, but I, for one?, don't. > > Please show us more of the program, including the import statement(s), > and some sample input data. What leads you to think is is slow? > > One opportunity for improvement - take the invariant out of the while > statement. > > q = dt.datetime(*X[-1,0].timetuple()[0:4]) > > while hr q: > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/using-datetime-and-calculating-hourly-average-tp24370537p24375619.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Tue Jul 7 18:13:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Jul 2009 17:13:27 +0100 Subject: [Tutor] using datetime and calculating hourly average References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com> <24375619.post@talk.nabble.com> Message-ID: "John [H2O]" wrote > The data is just x,y data where x = datetime objects from the datetime > module. y are just floats. It is bundled in a numpy array. > > So the only import statements are: > > import datetime as dt > import numpy as np > > I pass the array X, where X is a numpy array of shape [n,2] where n is > the > number of points in the data. I assume there is a good reason to use a numpy array instead of a regular list? ie You need a numpy array elsewhere in the code? I've never used numpy bt there is a possibility that array access is slower than list access, but I have no idea. It just adds an extra level of complexity thats all. > As for your comment regarding the invariant... would it be: > while hr q: > I think he meant while hr <= q as per your original code >>> def calc_hravg(X): >>> """Calculates hourly average from input data""" >>> >>> X_hr = [] >>> minX = X[:,0].min() >>> hr = dt.datetime(*minX.timetuple()[0:4]) >>> >>> while hr <= dt.datetime(*X[-1,0].timetuple()[0:4]): >>> nhr = hr + dt.timedelta(hours=1) >>> ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) I have no idea what this is doing but do you really mean a bitwise and here? You are effectively bitwise anding two boolean values which seems odd to put it mildly... >>> vals = X[ind,1][0].T >>> try: >>> hr_avg = np.average(vals) >>> except: >>> hr_avg = np.nan >>> X_hr.append([hr,hr_avg]) >>> hr = hr + dt.timedelta(hours=1) >>> >>> return np.array(X_hr) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jsseabold at gmail.com Tue Jul 7 18:29:56 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Tue, 7 Jul 2009 12:29:56 -0400 Subject: [Tutor] using datetime and calculating hourly average In-Reply-To: <24370537.post@talk.nabble.com> References: <24370537.post@talk.nabble.com> Message-ID: On Tue, Jul 7, 2009 at 6:16 AM, John [H2O] wrote: > > Here's a function I wrote to calculate hourly averages: > > It seems a bit slow, however... any thoughts on how to improve it? > > def calc_hravg(X): > ? ?"""Calculates hourly average from input data""" > > ? ?X_hr = [] > ? ?minX = X[:,0].min() > ? ?hr = dt.datetime(*minX.timetuple()[0:4]) > > ? ?while hr <= dt.datetime(*X[-1,0].timetuple()[0:4]): > ? ? ? ?nhr = hr + dt.timedelta(hours=1) > ? ? ? ?ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) > ? ? ? ?vals = X[ind,1][0].T > ? ? ? ?try: > ? ? ? ? ? ?#hr_avg = np.sum(vals) / len(vals) > ? ? ? ? ? ?hr_avg = np.average(vals) > > ? ? ? ?except: > ? ? ? ? ? ?hr_avg = np.nan > ? ? ? ?X_hr.append([hr,hr_avg]) > ? ? ? ?hr = hr + dt.timedelta(hours=1) > > ? ?return np.array(X_hr) > > > -- One quick thought, as I haven't read your code very carefully, but using reduce is faster than sum or average (though you sacrifice readability) if the ndarray is big enough to matter ie., instead of np.average(vals) you could have np.add.reduce(vals)/len(vals). You might have some better luck on the numpy mailing list . It's very active and there are people that are much more knowledgeable than me. You might want to include an example of your X in the example to help them help you to optimize. Cheers, Skipper From froslie at gmail.com Tue Jul 7 18:51:14 2009 From: froslie at gmail.com (Pete Froslie) Date: Tue, 7 Jul 2009 12:51:14 -0400 Subject: [Tutor] mac os x executable Message-ID: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> Hi, I'm having trouble finding good tutorials on creating standalone executable files for mac os x.. I've been looking at 'py2app', but can't seem get a solid grasp. Any help would be greatly appreciated! cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Tue Jul 7 19:16:47 2009 From: washakie at gmail.com (John [H2O]) Date: Tue, 7 Jul 2009 10:16:47 -0700 (PDT) Subject: [Tutor] using datetime and calculating hourly average In-Reply-To: References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com> <24375619.post@talk.nabble.com> Message-ID: <24377741.post@talk.nabble.com> Alan Gauld wrote: > > > I assume there is a good reason to use a numpy array instead of > a regular list? ie You need a numpy array elsewhere in the code? > I've never used numpy bt there is a possibility that array access > is slower than list access, but I have no idea. It just adds an extra > level of complexity thats all. > Yes, I use numpy a lot, my understanding is that is is quite a bit faster than lists... but perhaps not in a case like this. >> As for your comment regarding the invariant... would it be: >> while hr q: >> > > I think he meant > > while hr <= q > > as per your original code > Okay, thanks! > >>>> ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) > > I have no idea what this is doing but do you really mean a bitwise > and here? You are effectively bitwise anding two boolean values > which seems odd to put it mildly... > Well, effectively I am searching the array for values matching the criteria, but maybe I don't understand the bitwise details. What I am trying to say is: " index = X where hr < X[:,0] < nhr " I had problems though when I tried to code it as such: ind = np.where((hr < X[:,0] < nhr)) this doesn't work, though you think it would... > HTH, > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > Yes, thank you. -- View this message in context: http://www.nabble.com/using-datetime-and-calculating-hourly-average-tp24370537p24377741.html Sent from the Python - tutor mailing list archive at Nabble.com. From sander.sweers at gmail.com Tue Jul 7 19:20:12 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 7 Jul 2009 19:20:12 +0200 Subject: [Tutor] using datetime and calculating hourly average In-Reply-To: <24375619.post@talk.nabble.com> References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com> <24375619.post@talk.nabble.com> Message-ID: 2009/7/7 John [H2O] : > > The data is just x,y data where x = datetime objects from the datetime > module. y are just floats. It is bundled in a numpy array. I might be totally off but, did know that you can compare datetime objects? >>> from datetime import datetime >>> d1 = datetime.now() >>> d2 = datetime.now() >>> d1 datetime.datetime(2009, 7, 7, 18, 43, 15, 952000) >>> d2 datetime.datetime(2009, 7, 7, 18, 43, 23, 252000) >>> d1 < d2 True You can also add and subtract creating a timedelta object. >>> diff = d2 - d1 >>> diff datetime.timedelta(0, 7, 300000) >>> diff.seconds 7 > import datetime as dt > import numpy as np > > I pass the array X, where X is a numpy array of shape [n,2] where n is the > number of points in the data. > >>> It seems a bit slow, however... any thoughts on how to improve it? >>> >>> def calc_hravg(X): >>> ? ? """Calculates hourly average from input data""" >>> >>> ? ? X_hr = [] >>> ? ? minX = X[:,0].min() Why do you need minX? You only use it to create hr which can be done differently, see below. >>> ? ? hr = dt.datetime(*minX.timetuple()[0:4]) If i read his correctly you create a date timeobject from a datetime object via a sliced timetuple? If you just want the date not the hours and seconds use "X[:,0].date()" assuming X[:,0] is a datetime object. You should create a timedelta here which makes more sense as it does not change. delta = dt.timedelta(hours=1) # Added by me >>> ? ? while hr <= dt.datetime(*X[-1,0].timetuple()[0:4]): Again you could use X[-1,0].date(). >>> ? ? ? ? nhr = hr + dt.timedelta(hours=1) If you create the delta one level up the above changes to "nhr += delta". >>> ? ? ? ? ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) >>> ? ? ? ? vals = X[ind,1][0].T >>> ? ? ? ? try: >>> ? ? ? ? ? ? #hr_avg = np.sum(vals) / len(vals) >>> ? ? ? ? ? ? hr_avg = np.average(vals) >>> >>> ? ? ? ? except: >>> ? ? ? ? ? ? hr_avg = np.nan >>> ? ? ? ? X_hr.append([hr,hr_avg]) >>> ? ? ? ? hr = hr + dt.timedelta(hours=1) >>> >>> ? ? return np.array(X_hr) How should X_hr look like, example? To me it looks like it is overly complicated (but that might be me). Greets Sander From bill at celestial.net Tue Jul 7 18:54:14 2009 From: bill at celestial.net (Bill Campbell) Date: Tue, 7 Jul 2009 09:54:14 -0700 Subject: [Tutor] mac os x executable In-Reply-To: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> Message-ID: <20090707165414.GA21890@ayn.mi.celestial.com> On Tue, Jul 07, 2009, Pete Froslie wrote: >Hi, > >I'm having trouble finding good tutorials on creating standalone executable >files for mac os x.. I've been looking at 'py2app', but can't seem get a >solid grasp. Any help would be greatly appreciated! For a python script, say mypython.py, it should start with something like this: #!/usr/bin/env python # do stuff here Then ``chmod +x mypython.py'' and it's ready to go. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 There has been no greater threat to life, liberty, and property throughout the ages than government. Even the most violent and brutal private individuals have been able to inflict only a mere fraction of the harm and destruction that have been caused by the use of power by political authorities. -- Richard Ebeling From froslie at gmail.com Tue Jul 7 19:40:23 2009 From: froslie at gmail.com (Pete Froslie) Date: Tue, 7 Jul 2009 13:40:23 -0400 Subject: [Tutor] mac os x executable In-Reply-To: <20090707165414.GA21890@ayn.mi.celestial.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <20090707165414.GA21890@ayn.mi.celestial.com> Message-ID: <41fcacc90907071040g770c3e8fn70f79e33bacf16b8@mail.gmail.com> Thanks Bill, Terminal tells me, 'chmod: app_test.py: No such file or directory' I assume that's what you meant to do? Drop this at the start of the script: #!/usr/bin/env python Then go into terminal and type: `chmod +x mypython.py'' --pretty new to some of this stuff. cheers On Tue, Jul 7, 2009 at 12:54 PM, Bill Campbell wrote: > On Tue, Jul 07, 2009, Pete Froslie wrote: > >Hi, > > > >I'm having trouble finding good tutorials on creating standalone > executable > >files for mac os x.. I've been looking at 'py2app', but can't seem get a > >solid grasp. Any help would be greatly appreciated! > > For a python script, say mypython.py, it should start with > something like this: > > #!/usr/bin/env python > # do stuff here > > Then ``chmod +x mypython.py'' and it's ready to go. > > Bill > -- > INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC > URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way > Voice: (206) 236-1676 Mercer Island, WA 98040-0820 > Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 > > There has been no greater threat to life, liberty, and property > throughout the ages than government. Even the most violent and brutal > private individuals have been able to inflict only a mere fraction of > the harm and destruction that have been caused by the use of power by > political authorities. -- Richard Ebeling > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidkim05 at gmail.com Tue Jul 7 19:20:25 2009 From: davidkim05 at gmail.com (David Kim) Date: Tue, 7 Jul 2009 13:20:25 -0400 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! In-Reply-To: <1c2a2c590907070426m40f74bbdm5bb65a38634293a1@mail.gmail.com> References: <1c2a2c590907070426m40f74bbdm5bb65a38634293a1@mail.gmail.com> Message-ID: On Tue, Jul 7, 2009 at 7:26 AM, Kent Johnson wrote: > > curl works because it ignores the redirect to the ToS page, and the > site is (astoundingly) dumb enough to serve the content with the > redirect. You could make urllib2 behave the same way by defining a 302 > handler that does nothing. Many thanks for the redirect pointer! I also found http://diveintopython.org/http_web_services/redirects.html. Is the handler class on this page what you mean by a handler that does nothing? (It looks like it exposes the error code but still follows the redirect). I guess i'm still a little confused since, if the handler does nothing, won't I still go to the ToS page? For example, I ran the following code (found at http://stackoverflow.com/questions/554446/how-do-i-prevent-pythons-urllib2-from-following-a-redirect) and ended-up pulling the same ToS page anyway. #### import urllib2 redirect_handler = urllib2.HTTPRedirectHandler() class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_302(self, req, fp, code, msg, headers): return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers) http_error_301 = http_error_303 = http_error_307 = http_error_302 cookieprocessor = urllib2.HTTPCookieProcessor() opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor) urllib2.install_opener(opener) response = urllib2.urlopen("http://www.dtcc.com/products/derivserv/data_table_i.php?id=table1") print response.read() #### I suspect I am not understanding something basic about how urllib2 deals with this redirect issue since it seems everything I try gives me the same ToS page. > Generally you have to post to the same url as the form, giving the > same data the form does. You can inspect the source of the form to > figure this out. In this case the form is > >
> name="urltarget"/> > > > > >
> > You generally need to enable cookie support in urllib2 as well, > because the site will use a cookie to flag that you saw the consent > form. This tutorial shows how to enable cookies and submit form data: > http://personalpages.tds.net/~kent37/kk/00010.html I have seen the login examples where one provides values for the fields username and password (thanks Kent). Given the form above, however, it's unclear to me how one POSTs the form data when you aren't actually passing any parameters. Perhaps this is less of a Python question and more an http question (which unfortunately I know nothing about either). Thanks so much again for the help! DK -- morenotestoself.wordpress.com From sander.sweers at gmail.com Tue Jul 7 19:51:01 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 7 Jul 2009 19:51:01 +0200 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! In-Reply-To: References: <1c2a2c590907070426m40f74bbdm5bb65a38634293a1@mail.gmail.com> Message-ID: 2009/7/7 David Kim : > opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor) > urllib2.install_opener(opener) > > response = urllib2.urlopen("http://www.dtcc.com/products/derivserv/data_table_i.php?id=table1") > print response.read() > #### > > I suspect I am not understanding something basic about how urllib2 > deals with this redirect issue since it seems everything I try gives > me the same ToS page. Indeed, you create the opener but then you do not use it. Try the below and it should work. response = opener.open("http://www.dtcc.com/products/derivserv/data_table_i.php?id=table1") data = response.read() Greets Sander From kent37 at tds.net Tue Jul 7 19:56:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 7 Jul 2009 13:56:45 -0400 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! In-Reply-To: References: <1c2a2c590907070426m40f74bbdm5bb65a38634293a1@mail.gmail.com> Message-ID: <1c2a2c590907071056g12224aa4l3929c9dd645caa52@mail.gmail.com> On Tue, Jul 7, 2009 at 1:20 PM, David Kim wrote: > On Tue, Jul 7, 2009 at 7:26 AM, Kent Johnson wrote: >> >> curl works because it ignores the redirect to the ToS page, and the >> site is (astoundingly) dumb enough to serve the content with the >> redirect. You could make urllib2 behave the same way by defining a 302 >> handler that does nothing. > > Many thanks for the redirect pointer! I also found > http://diveintopython.org/http_web_services/redirects.html. Is the > handler class on this page what you mean by a handler that does > nothing? (It looks like it exposes the error code but still follows > the redirect). No, all of those examples are handling the redirect. The SmartRedirectHandler just captures additional status. I think you need something like this: class IgnoreRedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): return None def http_error_302(self, req, fp, code, msg, headers): return None > I guess i'm still a little confused since, if the > handler does nothing, won't I still go to the ToS page? No, it is the action of the handler, responding to the redirect request, that causes the ToS page to be fetched. > For example, I ran the following code (found at > http://stackoverflow.com/questions/554446/how-do-i-prevent-pythons-urllib2-from-following-a-redirect) That is pretty similar to the DiP code... > I suspect I am not understanding something basic about how urllib2 > deals with this redirect issue since it seems everything I try gives > me the same ToS page. Maybe you don't understand how redirect works in general... >> Generally you have to post to the same url as the form, giving the >> same data the form does. You can inspect the source of the form to >> figure this out. In this case the form is >> >>
>> > name="urltarget"/> >> >> >> >> >>
>> >> You generally need to enable cookie support in urllib2 as well, >> because the site will use a cookie to flag that you saw the consent >> form. This tutorial shows how to enable cookies and submit form data: >> http://personalpages.tds.net/~kent37/kk/00010.html > > I have seen the login examples where one provides values for the > fields username and password (thanks Kent). Given the form above, > however, it's unclear to me how one POSTs the form data when you > aren't actually passing any parameters. Perhaps this is less of a > Python question and more an http question (which unfortunately I know > nothing about either). Yes, the parameters are listed in the form. If you don't have at least a basic understanding of HTTP and HTML you are going to have trouble with this project... Kent From davidkim05 at gmail.com Tue Jul 7 20:03:07 2009 From: davidkim05 at gmail.com (David Kim) Date: Tue, 7 Jul 2009 14:03:07 -0400 Subject: [Tutor] Urllib, mechanize, beautifulsoup, lxml do not compute (for me)! In-Reply-To: <1c2a2c590907071056g12224aa4l3929c9dd645caa52@mail.gmail.com> References: <1c2a2c590907070426m40f74bbdm5bb65a38634293a1@mail.gmail.com> <1c2a2c590907071056g12224aa4l3929c9dd645caa52@mail.gmail.com> Message-ID: Thanks Kent, perhaps I'll cool the Python jets and move on to HTTP and HTML. I was hoping it would be something I could just pick up along the way, looks like I was wrong. dk On Tue, Jul 7, 2009 at 1:56 PM, Kent Johnson wrote: > On Tue, Jul 7, 2009 at 1:20 PM, David Kim wrote: >> On Tue, Jul 7, 2009 at 7:26 AM, Kent Johnson wrote: >>> >>> curl works because it ignores the redirect to the ToS page, and the >>> site is (astoundingly) dumb enough to serve the content with the >>> redirect. You could make urllib2 behave the same way by defining a 302 >>> handler that does nothing. >> >> Many thanks for the redirect pointer! I also found >> http://diveintopython.org/http_web_services/redirects.html. Is the >> handler class on this page what you mean by a handler that does >> nothing? (It looks like it exposes the error code but still follows >> the redirect). > > No, all of those examples are handling the redirect. The > SmartRedirectHandler just captures additional status. I think you need > something like this: > class IgnoreRedirectHandler(urllib2.HTTPRedirectHandler): > ? ?def http_error_301(self, req, fp, code, msg, headers): > ? ? ? ?return None > > ? ?def http_error_302(self, req, fp, code, msg, headers): > ? ? ? ?return None > >> I guess i'm still a little confused since, if the >> handler does nothing, won't I still go to the ToS page? > > No, it is the action of the handler, responding to the redirect > request, that causes the ToS page to be fetched. > >> For example, I ran the following code (found at >> http://stackoverflow.com/questions/554446/how-do-i-prevent-pythons-urllib2-from-following-a-redirect) > > That is pretty similar to the DiP code... > >> I suspect I am not understanding something basic about how urllib2 >> deals with this redirect issue since it seems everything I try gives >> me the same ToS page. > > Maybe you don't understand how redirect works in general... > >>> Generally you have to post to the same url as the form, giving the >>> same data the form does. You can inspect the source of the form to >>> figure this out. In this case the form is >>> >>>
>>> >> name="urltarget"/> >>> >>> >>> >>> >>>
>>> >>> You generally need to enable cookie support in urllib2 as well, >>> because the site will use a cookie to flag that you saw the consent >>> form. This tutorial shows how to enable cookies and submit form data: >>> http://personalpages.tds.net/~kent37/kk/00010.html >> >> I have seen the login examples where one provides values for the >> fields username and password (thanks Kent). Given the form above, >> however, it's unclear to me how one POSTs the form data when you >> aren't actually passing any parameters. Perhaps this is less of a >> Python question and more an http question (which unfortunately I know >> nothing about either). > > Yes, the parameters are listed in the form. > > If you don't have at least a basic understanding of HTTP and HTML you > are going to have trouble with this project... > > Kent > -- morenotestoself.wordpress.com From wescpy at gmail.com Tue Jul 7 20:35:42 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 7 Jul 2009 11:35:42 -0700 Subject: [Tutor] mac os x executable In-Reply-To: <41fcacc90907071040g770c3e8fn70f79e33bacf16b8@mail.gmail.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <20090707165414.GA21890@ayn.mi.celestial.com> <41fcacc90907071040g770c3e8fn70f79e33bacf16b8@mail.gmail.com> Message-ID: <78b3a9580907071135h12c5948ei6f2fef32a8a97a76@mail.gmail.com> >> >I'm having trouble finding good tutorials on creating standalone >> > executable >> >files for mac os x.. I've been looking at 'py2app', [...] pete, welcome to Python! in order for all to answer your question more appropriately, you'll have to describe the problem in slightly more detail. what do you mean when you say "standalone executable?" the reason why i ask is because a tool like py2app -- the equivalent to py2exe on PCs -- is meant to be used in situations where you're installing the application on a Mac which you're not sure whether Python is installed on it and/or to bundle up your code in a way that's harder to reverse engineer than a plain text .py file. bill's suggestion comes from the fact that pretty much all Macs these days come with Python installed and all you would need to do is to just make your .py file executable, hence the "chmod +x YOUR_MODULE.py" so that you can run YOUR_MODULE.py directly from the shell instead of having to prepend it, i.e, "python YOUR_MODULE.py". in your example above, you have both mypython.py and app_test.py -- you need to make sure that you: 1) use the same name (which is why i changed them to YOUR_MODULE.py meaning substitute in the actual filename in place of "YOUR_MODULE" and 2) that the directory that your script is in is also in your PATH environment variable -- otherwise you would need to do ./YOUR_MODULE.py if your shell is in the same directory as your file. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From froslie at gmail.com Tue Jul 7 20:50:45 2009 From: froslie at gmail.com (Pete Froslie) Date: Tue, 7 Jul 2009 14:50:45 -0400 Subject: [Tutor] mac os x executable In-Reply-To: <78b3a9580907071135h12c5948ei6f2fef32a8a97a76@mail.gmail.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <20090707165414.GA21890@ayn.mi.celestial.com> <41fcacc90907071040g770c3e8fn70f79e33bacf16b8@mail.gmail.com> <78b3a9580907071135h12c5948ei6f2fef32a8a97a76@mail.gmail.com> Message-ID: <41fcacc90907071150p12d59377w58d461809766f63f@mail.gmail.com> Wesley, What I meant is that I would like a file that can be double clicked in order to run the python script.. so that I can drop it on another mac where someone can execute it without worrying about Terminal. Essentially, I need everything to be clean in the end.. My projects are artworks and function better without the tech confusion when viewers interact with them.. I hope this helps clarify my trouble Thanks for the explanation -- it is helpful.. On Tue, Jul 7, 2009 at 2:35 PM, wesley chun wrote: > >> >I'm having trouble finding good tutorials on creating standalone > >> > executable > >> >files for mac os x.. I've been looking at 'py2app', [...] > > > pete, > > welcome to Python! in order for all to answer your question more > appropriately, you'll have to describe the problem in slightly more > detail. > > what do you mean when you say "standalone executable?" the reason why > i ask is because a tool like py2app -- the equivalent to py2exe on PCs > -- is meant to be used in situations where you're installing the > application on a Mac which you're not sure whether Python is installed > on it and/or to bundle up your code in a way that's harder to reverse > engineer than a plain text .py file. > > bill's suggestion comes from the fact that pretty much all Macs these > days come with Python installed and all you would need to do is to > just make your .py file executable, hence the "chmod +x > YOUR_MODULE.py" so that you can run YOUR_MODULE.py directly from the > shell instead of having to prepend it, i.e, "python YOUR_MODULE.py". > > in your example above, you have both mypython.py and app_test.py -- > you need to make sure that you: 1) use the same name (which is why i > changed them to YOUR_MODULE.py meaning substitute in the actual > filename in place of "YOUR_MODULE" and 2) that the directory that your > script is in is also in your PATH environment variable -- otherwise > you would need to do ./YOUR_MODULE.py if your shell is in the same > directory as your file. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -- Pete Froslie http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill at celestial.net Tue Jul 7 21:15:12 2009 From: bill at celestial.net (Bill Campbell) Date: Tue, 7 Jul 2009 12:15:12 -0700 Subject: [Tutor] mac os x executable In-Reply-To: <41fcacc90907071150p12d59377w58d461809766f63f@mail.gmail.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <20090707165414.GA21890@ayn.mi.celestial.com> <41fcacc90907071040g770c3e8fn70f79e33bacf16b8@mail.gmail.com> <78b3a9580907071135h12c5948ei6f2fef32a8a97a76@mail.gmail.com> <41fcacc90907071150p12d59377w58d461809766f63f@mail.gmail.com> Message-ID: <20090707191512.GA19142@ayn.mi.celestial.com> On Tue, Jul 07, 2009, Pete Froslie wrote: > > Wesley, > What I meant is that I would like a file that can be double clicked in > order to run the python script.. so that I can drop it on another mac > where someone can execute it without worrying about Terminal. > Essentially, I need everything to be clean in the end.. My projects > are artworks and function better without the tech confusion when > viewers interact with them.. I hope this helps clarify my trouble > Thanks for the explanation -- it is helpful.. You might want to look at XDroplets, a program that generates wrappers for X11 applications that one can click on or drop files on to execute them. For instance, I have one I call Gvim.app that executes the vim editor in an xterm (I don't like the GUI versions of vim, but prefer working in a simple xterm). Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 It's time to feed the hogs -- Unintended Consequences From alan.gauld at btinternet.com Tue Jul 7 23:13:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Jul 2009 22:13:06 +0100 Subject: [Tutor] using datetime and calculating hourly average References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com><24375619.post@talk.nabble.com> <24377741.post@talk.nabble.com> Message-ID: "John [H2O]" wrote >>>>> ind = np.where( (X[:,0] > hr) & (X[:,0] < nhr) ) >> >> I have no idea what this is doing but do you really mean a bitwise >> and here? You are effectively bitwise anding two boolean values >> which seems odd to put it mildly... > > Well, effectively I am searching the array for values matching the > criteria, > but maybe I don't understand the bitwise details. What I am trying to say > is: > " index = X where hr < X[:,0] < nhr " In Python you can do that comparison directly: ind = np.where( hr < X[:,0] < nhr) What you were doping was evaluating the comparisons as boolean expressions then doing a bitwise and of the results, you should have used a logical and: ind = np.where( (X[:,0] > hr) and (X[:,0] < nhr) ) Which would do what you want, but the direct approach is prettier IMHO. > I had problems though when I tried to code it as such: > > ind = np.where((hr < X[:,0] < nhr)) > this doesn't work, though you think it would... Yes I wpuld... You shouldn't need the inner parens but they shouldn't stop it working either. What does happen? Do you get an error message? What is the argument to np.where()? And of course it could all be irrelevant since as Sander pointed out you can compare datetime objects directly... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jul 7 23:14:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Jul 2009 22:14:41 +0100 Subject: [Tutor] mac os x executable References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> Message-ID: "Pete Froslie" wrote > I'm having trouble finding good tutorials on creating standalone > executable > files for mac os x.. I've been looking at 'py2app', but can't seem get a > solid grasp. Any help would be greatly appreciated! My first question would be do you need to? After all with Python 2.3 pre installed on MacOS X can't you just distribute the python files? Just a thought., Alan G From froslie at gmail.com Tue Jul 7 23:33:10 2009 From: froslie at gmail.com (Pete Froslie) Date: Tue, 7 Jul 2009 17:33:10 -0400 Subject: [Tutor] mac os x executable In-Reply-To: References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> Message-ID: <41fcacc90907071433l49b08057nbc335d4b66ef7619@mail.gmail.com> Yes, this makes sense to me.. but when treating a project as an artwork I can't ask people to go through an effort beyond a simple start of the app. For instance, I'm in Boston and the work is being show on a computer in gallery in SF-- if it crashes, curators often will be unenthusiastic when being told over the phone how to re-launch the artwork-- it would be much easier to say, 'just double click the icon labeled artwork'. Same goes for an artwork I would like to distribute online to 'non-tech' viewers... Does this make sense? thank, Pete F On Tue, Jul 7, 2009 at 5:14 PM, Alan Gauld wrote: > > "Pete Froslie" wrote > > I'm having trouble finding good tutorials on creating standalone >> executable >> files for mac os x.. I've been looking at 'py2app', but can't seem get a >> solid grasp. Any help would be greatly appreciated! >> > > My first question would be do you need to? After all with Python 2.3 pre > installed on MacOS X can't you just distribute the python files? > > Just a thought., > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Tue Jul 7 23:51:26 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 07 Jul 2009 17:51:26 -0400 Subject: [Tutor] mac os x executable In-Reply-To: References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> Message-ID: <1247003486.9099.1323969703@webmail.messagingengine.com> Alan, > After all with Python 2.3 pre installed on MacOS X Is Python 2.3 really the most recent version of Python distributed with new Macs? So if I wanted to distribute a Python 2.6 script to a Mac user, I would need to instruct the Mac user how to download and install a separate version of Python (2.6), being careful not to overwrite the system default version of Python (2.3). Or I could use py2app to build in single standalone distributable (with an embedded Python 2.6 interpreter and library files) and distribute that. Does that sound right? Thank you, Malcolm From alan.gauld at btinternet.com Wed Jul 8 01:12:11 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 7 Jul 2009 23:12:11 +0000 (GMT) Subject: [Tutor] mac os x executable In-Reply-To: <41fcacc90907071433l49b08057nbc335d4b66ef7619@mail.gmail.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <41fcacc90907071433l49b08057nbc335d4b66ef7619@mail.gmail.com> Message-ID: <616851.94008.qm@web86703.mail.ird.yahoo.com> > Yes, this makes sense to me.. but when treating a project as an artwork > I can't ask people to go through an effort beyond a simple start of the > app. For instance, I'm in Boston and the work is being show on a > computer in gallery in SF-- if it crashes, curators often will be > unenthusiastic when being told over the phone how to re-launch the > artwork-- it would be much easier to say, 'just double click the icon > labeled artwork'. Sure, But you can do that without creating an executable. All you need is to drop a shortcut to the file on the desktop and have the shebang line and chmod settings set up correctly as per the previous posting. You don't even need to have it end in .py just use the name of your applicatrion. But it would be worth while spending a little time learning about how Mac OS X works wioth the underlying Unix shell and the interaction between icons on the desktop and the underlying files. A book like The Missing Manual for Mac OS X or almost any other in depth Moc OS X manual should explain what you need to know. But if you are taking the trouble to learn Python you really should learn the OS fundamentals too Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Pete Froslie To: Alan Gauld Cc: tutor at python.org Sent: Tuesday, 7 July, 2009 10:33:10 PM Subject: Re: [Tutor] mac os x executable Does this make sense? thank, Pete F On Tue, Jul 7, 2009 at 5:14 PM, Alan Gauld wrote: "Pete Froslie" wrote I'm having trouble finding good tutorials on creating standalone executable files for mac os x.. I've been looking at 'py2app', but can't seem get a solid grasp. Any help would be greatly appreciated! My first question would be do you need to? After all with Python 2.3 pre installed on MacOS X can't you just distribute the python files? Just a thought., Alan G _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jul 8 02:04:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 7 Jul 2009 20:04:32 -0400 Subject: [Tutor] mac os x executable In-Reply-To: <1247003486.9099.1323969703@webmail.messagingengine.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <1247003486.9099.1323969703@webmail.messagingengine.com> Message-ID: <1c2a2c590907071704r5443e65at999da8266c8dfd33@mail.gmail.com> On Tue, Jul 7, 2009 at 5:51 PM, wrote: > Alan, > >> After all with Python 2.3 pre installed on MacOS X > > Is Python 2.3 really the most recent version of Python distributed with > new Macs? I think *new* Macs come with 2.5. My 2-year-old MacBook Pro has 2.3. > So if I wanted to distribute a Python 2.6 script to a Mac user, I would > need to instruct the Mac user how to download and install a separate > version of Python (2.6), being careful not to overwrite the system > default version of Python (2.3). No care is needed. The Mac installers don't disturb the official Apple version. Kent From froslie at gmail.com Wed Jul 8 02:12:34 2009 From: froslie at gmail.com (Pete Froslie) Date: Tue, 7 Jul 2009 20:12:34 -0400 Subject: [Tutor] mac os x executable In-Reply-To: <616851.94008.qm@web86703.mail.ird.yahoo.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <41fcacc90907071433l49b08057nbc335d4b66ef7619@mail.gmail.com> <616851.94008.qm@web86703.mail.ird.yahoo.com> Message-ID: <41fcacc90907071712n67a756f5waf444d45fa905a68@mail.gmail.com> That's great Alan.. I see what you mean with the shortcut-- going to try it. Thanks for the suggestion on the Mac OS x manual.. I will certainly start looking more into OS fundamentals. I will say that I've been having a really good time with Python and am excited to see it start working further with the OS (as well as utilizing it in artworks) Cheers, Pete On Tue, Jul 7, 2009 at 7:12 PM, ALAN GAULD wrote: > > Yes, this makes sense to me.. but when treating a project as an artwork > > I can't ask people to go through an effort beyond a simple start of the > > app. For instance, I'm in Boston and the work is being show on a > > computer in gallery in SF-- if it crashes, curators often will be > > unenthusiastic when being told over the phone how to re-launch the > > artwork-- it would be much easier to say, 'just double click the icon > > labeled artwork'. > Sure, But you can do that without creating an executable.All you need is > to drop a shortcut to the file on the desktop > and have the shebang line and chmod settings set up > correctly as per the previous posting. You don't even > need to have it end in .py just use the name of your > applicatrion. > > But it would be worth while spending a little time learning > about how Mac OS X works wioth the underlying Unix > shell and the interaction between icons on the desktop > and the underlying files. A book like The Missing Manual > for Mac OS X or almost any other in depth Moc OS X > manual should explain what you need to know. > > But if you are taking the trouble to learn Python you > really should learn the OS fundamentals too > > Alan Gauld > Author of the Learn To Program website > http://www.alan-g.me.uk/ > > > ------------------------------ > *From:* Pete Froslie > *To:* Alan Gauld > *Cc:* tutor at python.org > *Sent:* Tuesday, 7 July, 2009 10:33:10 PM > *Subject:* Re: [Tutor] mac os x executable > > > > Does this make sense? > > thank, > Pete F > > On Tue, Jul 7, 2009 at 5:14 PM, Alan Gauld wrote: > >> >> "Pete Froslie" wrote >> >> I'm having trouble finding good tutorials on creating standalone >>> executable >>> files for mac os x.. I've been looking at 'py2app', but can't seem get a >>> solid grasp. Any help would be greatly appreciated! >>> >> >> My first question would be do you need to? After all with Python 2.3 pre >> installed on MacOS X can't you just distribute the python files? >> >> Just a thought., >> >> Alan G >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Pete Froslie > 617.314.0957 > http://www.froslie.net > > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Wed Jul 8 02:20:09 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 7 Jul 2009 17:20:09 -0700 Subject: [Tutor] mac os x executable In-Reply-To: <1c2a2c590907071704r5443e65at999da8266c8dfd33@mail.gmail.com> References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <1247003486.9099.1323969703@webmail.messagingengine.com> <1c2a2c590907071704r5443e65at999da8266c8dfd33@mail.gmail.com> Message-ID: <78b3a9580907071720hd726269oe1372b6b35cbe826@mail.gmail.com> >>> After all with Python 2.3 pre installed on MacOS X >> Is Python 2.3 really the most recent version of Python distributed with >> new Macs? > I think *new* Macs come with 2.5. My 2-year-old MacBook Pro has 2.3. i got a new MBP from work about half a year ago with leopard 10.5.6 installed, and it came with 2.5.1. (i've been able to build and install 2.6 and 3.0 without conflicts with apple's version as long as i modified my setup.py with the correct lib and inc locations, and ran "make altinstall".) -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at pythontoo.com Wed Jul 8 03:36:55 2009 From: david at pythontoo.com (David) Date: Tue, 07 Jul 2009 21:36:55 -0400 Subject: [Tutor] if: else: can not get else to work Message-ID: <4A53F837.9060209@pythontoo.com> Hi Tutors, I have a web cam that saves files in /var/log/motion and it can get quite large so I clean it every few days. I came up with this; #!/usr/bin/python import commands import os from sys import exit def clean_motion(): folder = '/var/log/motion' if os.path.exists(folder): fobj = os.listdir(folder) fobj.sort() for file in fobj: pathname = os.path.join(folder, file) if os.path.exists(pathname): print 'removing... ', file os.remove(pathname) print folder, 'is clean.' else: print folder, 'does not exist!' if __name__ == "__main__": if commands.getoutput( "whoami" ) != "root": exit("\tYou must be root! Try again please.") clean_motion() My question is I tried to get it to print out when the directory was empty like this; for file in fobj: pathname = os.path.join(folder, file) if os.path.exists(pathname): print 'removing... ', file os.remove(pathname) else: print 'No files to clean' But if there are no files in the directory it never gets to the else. -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From rabidpoobear at gmail.com Wed Jul 8 03:47:23 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 7 Jul 2009 20:47:23 -0500 Subject: [Tutor] if: else: can not get else to work In-Reply-To: <4A53F837.9060209@pythontoo.com> References: <4A53F837.9060209@pythontoo.com> Message-ID: On Tue, Jul 7, 2009 at 8:36 PM, David wrote: > Hi Tutors, Hiya david. Cool e-mail address :) > My question is I tried to get it to print out when the directory was empty > like this; > > for file in fobj: > pathname = os.path.join(folder, file) > if os.path.exists(pathname): > print 'removing... ', file > os.remove(pathname) > else: > print 'No files to clean' > > But if there are no files in the directory it never gets to the else. > > Right, if there are no files in the directory, then fobj will contain 0 items, so when the outer "for file in obj" loop iterates over it, there will be no values for "file" to take. One note - "file" is a builtin (probably deprecated in 3.0 but it's still a builtin in 2.4) so you might not want to use it as filenames. Maybe use "fname"? I think in later versions of Python file() is just aliased to open(), or at least it has fewer features, so probably it should be deprecated by now anyway. Just a thought. Do you need help with adding this "no files" statement or would you like to solve it yourself? I feel like your question was just to confirm that there was nothing wrong with your code, and there isn't, you just need to find the correct way to display this prompt. hint: if the "for" loop isn't iterating over the items, you won't get to print this message, but you also know that the length of the fobj file must be 0 items, right? Think of how you can use this to your advantage. :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Jul 8 03:48:36 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 7 Jul 2009 18:48:36 -0700 Subject: [Tutor] if: else: can not get else to work In-Reply-To: <4A53F837.9060209@pythontoo.com> References: <4A53F837.9060209@pythontoo.com> Message-ID: <40af687b0907071848v6cee3cfy19704ad34a44e514@mail.gmail.com> On Tue, Jul 7, 2009 at 6:36 PM, David wrote: > My question is I tried to get it to print out when the directory was empty > like this; > > for file in fobj: > pathname = os.path.join(folder, file) > if os.path.exists(pathname): > print 'removing... ', file > os.remove(pathname) > else: > print 'No files to clean' > > But if there are no files in the directory it never gets to the else. > It shouldn't, the way you've got it set up... As I read your program, the only way it would get to the "else" would be if some other process deleted one of the files in the directory AFTER your script got a directory listing, but before your script gets around to deleting it. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Wed Jul 8 04:05:13 2009 From: david at pythontoo.com (David) Date: Tue, 07 Jul 2009 22:05:13 -0400 Subject: [Tutor] if: else: can not get else to work In-Reply-To: References: <4A53F837.9060209@pythontoo.com> Message-ID: <4A53FED9.4070400@pythontoo.com> Luke Paireepinart wrote: > > > On Tue, Jul 7, 2009 at 8:36 PM, David > wrote: > > Hi Tutors, > > Hiya david. Cool e-mail address :) Thanks, want luke at pythontoo.com I have a few to spare :) > > But if there are no files in the directory it never gets to the else. > > Right, if there are no files in the directory, then fobj will contain 0 > items, so when the outer "for file in obj" loop iterates over it, there > will be no values for "file" to take. > > One note - "file" is a builtin (probably deprecated in 3.0 but it's > still a builtin in 2.4) so you might not want to use it as filenames. > Maybe use "fname"? I think in later versions of Python file() is just > aliased to open(), or at least it has fewer features, so probably it > should be deprecated by now anyway. Just a thought. > > Do you need help with adding this "no files" statement or would you like > to solve it yourself? I feel like your question was just to confirm > that there was nothing wrong with your code, and there isn't, you just > need to find the correct way to display this prompt. hint: if the "for" > loop isn't iterating over the items, you won't get to print this > message, but you also know that the length of the fobj file must be 0 > items, right? Think of how you can use this to your advantage. :) > > Ok, here is what I came up with; #!/usr/bin/python import commands import os from sys import exit def clean_motion(): folder = '/var/log/motion' if os.path.exists(folder): fobj = os.listdir(folder) if len(fobj) == 0: print 'No files to clean.' else: fobj.sort() for fname in fobj: pathname = os.path.join(folder, fname) if os.path.exists(pathname): print 'removing... ', fname os.remove(pathname) if __name__ == "__main__": if commands.getoutput( "whoami" ) != "root": exit("\tYou must be root! Try again please.") clean_motion() -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From rabidpoobear at gmail.com Wed Jul 8 04:29:59 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 7 Jul 2009 21:29:59 -0500 Subject: [Tutor] if: else: can not get else to work In-Reply-To: <4A53FED9.4070400@pythontoo.com> References: <4A53F837.9060209@pythontoo.com> <4A53FED9.4070400@pythontoo.com> Message-ID: I typically abuse the fact that "return" will get you out of a function to make my code indented less.perhaps others would frown upon this but it makes sense to me. With various other changes, I'd make your function like so: from os import path, listdir, remove def clean(folder): if not path.exists(folder): print "Folder does not exist!" return False files = listdir(folder) if not len(files): print "Folder is empty!" return False files.sort() for f in files: target = path.join(folder, f) if not path.isfile(target): print "skipping directory", f continue print "removing file", f remove(target) clean("/var/log/motion") Also, about the address - yes please! can you make it forward to my gmail? On Tue, Jul 7, 2009 at 9:05 PM, David wrote: > Luke Paireepinart wrote: > >> >> >> On Tue, Jul 7, 2009 at 8:36 PM, David > david at pythontoo.com>> wrote: >> >> Hi Tutors, >> >> Hiya david. Cool e-mail address :) >> > > Thanks, want luke at pythontoo.com I have a few to spare :) > > >> But if there are no files in the directory it never gets to the else. >> >> Right, if there are no files in the directory, then fobj will contain 0 >> items, so when the outer "for file in obj" loop iterates over it, there will >> be no values for "file" to take. >> >> One note - "file" is a builtin (probably deprecated in 3.0 but it's still >> a builtin in 2.4) so you might not want to use it as filenames. Maybe use >> "fname"? I think in later versions of Python file() is just aliased to >> open(), or at least it has fewer features, so probably it should be >> deprecated by now anyway. Just a thought. >> >> Do you need help with adding this "no files" statement or would you like >> to solve it yourself? I feel like your question was just to confirm that >> there was nothing wrong with your code, and there isn't, you just need to >> find the correct way to display this prompt. hint: if the "for" loop isn't >> iterating over the items, you won't get to print this message, but you also >> know that the length of the fobj file must be 0 items, right? Think of how >> you can use this to your advantage. :) >> >> >> > Ok, here is what I came up with; > > #!/usr/bin/python > import commands > import os > from sys import exit > > def clean_motion(): > folder = '/var/log/motion' > if os.path.exists(folder): > fobj = os.listdir(folder) > if len(fobj) == 0: > print 'No files to clean.' > else: > fobj.sort() > for fname in fobj: > pathname = os.path.join(folder, fname) > if os.path.exists(pathname): > print 'removing... ', fname > os.remove(pathname) > > if __name__ == "__main__": > if commands.getoutput( "whoami" ) != "root": > exit("\tYou must be root! Try again please.") > clean_motion() > > > -- > Powered by Gentoo GNU/Linux > http://linuxcrazy.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Wed Jul 8 04:31:01 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 7 Jul 2009 21:31:01 -0500 Subject: [Tutor] if: else: can not get else to work In-Reply-To: References: <4A53F837.9060209@pythontoo.com> <4A53FED9.4070400@pythontoo.com> Message-ID: Oops, you should probably have a "return True" at the end of the function so the return value is meaningful. On Tue, Jul 7, 2009 at 9:29 PM, Luke Paireepinart wrote: > I typically abuse the fact that "return" will get you out of a function to > make my code indented less.perhaps others would frown upon this but it > makes sense to me. > With various other changes, I'd make your function like so: > from os import path, listdir, remove > > def clean(folder): > if not path.exists(folder): > print "Folder does not exist!" > return False > files = listdir(folder) > > if not len(files): > print "Folder is empty!" > return False > > files.sort() > for f in files: > target = path.join(folder, f) > if not path.isfile(target): > print "skipping directory", f > continue > print "removing file", f > remove(target) > > clean("/var/log/motion") > > Also, about the address - yes please! can you make it forward to my gmail? > > > On Tue, Jul 7, 2009 at 9:05 PM, David wrote: > >> Luke Paireepinart wrote: >> >>> >>> >>> On Tue, Jul 7, 2009 at 8:36 PM, David >> david at pythontoo.com>> wrote: >>> >>> Hi Tutors, >>> >>> Hiya david. Cool e-mail address :) >>> >> >> Thanks, want luke at pythontoo.com I have a few to spare :) >> >> >>> But if there are no files in the directory it never gets to the else. >>> >>> Right, if there are no files in the directory, then fobj will contain 0 >>> items, so when the outer "for file in obj" loop iterates over it, there will >>> be no values for "file" to take. >>> >>> One note - "file" is a builtin (probably deprecated in 3.0 but it's still >>> a builtin in 2.4) so you might not want to use it as filenames. Maybe use >>> "fname"? I think in later versions of Python file() is just aliased to >>> open(), or at least it has fewer features, so probably it should be >>> deprecated by now anyway. Just a thought. >>> >>> Do you need help with adding this "no files" statement or would you like >>> to solve it yourself? I feel like your question was just to confirm that >>> there was nothing wrong with your code, and there isn't, you just need to >>> find the correct way to display this prompt. hint: if the "for" loop isn't >>> iterating over the items, you won't get to print this message, but you also >>> know that the length of the fobj file must be 0 items, right? Think of how >>> you can use this to your advantage. :) >>> >>> >>> >> Ok, here is what I came up with; >> >> #!/usr/bin/python >> import commands >> import os >> from sys import exit >> >> def clean_motion(): >> folder = '/var/log/motion' >> if os.path.exists(folder): >> fobj = os.listdir(folder) >> if len(fobj) == 0: >> print 'No files to clean.' >> else: >> fobj.sort() >> for fname in fobj: >> pathname = os.path.join(folder, fname) >> if os.path.exists(pathname): >> print 'removing... ', fname >> os.remove(pathname) >> >> if __name__ == "__main__": >> if commands.getoutput( "whoami" ) != "root": >> exit("\tYou must be root! Try again please.") >> clean_motion() >> >> >> -- >> Powered by Gentoo GNU/Linux >> http://linuxcrazy.com >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Wed Jul 8 12:05:13 2009 From: washakie at gmail.com (John [H2O]) Date: Wed, 8 Jul 2009 03:05:13 -0700 (PDT) Subject: [Tutor] using datetime and calculating hourly average In-Reply-To: References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com> <24375619.post@talk.nabble.com> Message-ID: <24388708.post@talk.nabble.com> Sanders, The problem is I don't want date, I want the date AND hour, just not minutes. As for the comparison, in numpy here's what happens when I change the way I construct the where statements: --> 196 ind = np.where( (t1 < Y[:,0] < t2) ) #same result with/without inner parens 197 screen_vals = Y[ind,1][0] 198 #print 'X time: %s' % t1 TypeError: can't compare datetime.datetime to numpy.ndarray OR trying the 'and' method: --> 196 ind = np.where( (Y[:,0]>t1) and (Y[:,0] Hi, I've been programming for over 20 yrs, but only the last few in python and then only in dribs and drabs. I'm having a difficult time parsing a delimited string. e.g. 100657641~GBP~ACTIVE~0~1~~true~5.0~1247065352508~: 3818854~0~24104.08~4.5~~22.1~false|4.4~241.67~L~1~4.3~936.0~L~2~4.2~210.54~L~3~|4.5~19.16~B~1~4.6~214.27~B~2~4.7~802.13~B~3~: 3991404~1~19974.18~4.7~~21.7~false|4.6~133.01~L~1~4.5~124.83~L~2~4.4~319.33~L~3~|4.7~86.61~B~1~4.8~247.9~B~2~4.9~142.0~B~3~: 4031423~2~15503.56~6.6~~15.1~false|6.6~53.21~L~1~6.4~19.23~L~2~6.2~53.28~L~3~|6.8~41.23~B~1~7.0~145.04~B~2~7.2~37.23~B~3~ That is just a selection of the full string - and I've broken it up for this email. It's delimited by : and then by ~ and finally, in some cases, | (a pipe). If the string is called m, I thought I could create a list with m.split(":"). I would like to then first of all find in this list the entry beginning with e.g. 3991404. I thought I could pop each item in the list and compare that seems pretty long winded. When the ItemFound is now = '3991404~1~19974.18~4.7~~21.7~false|4.6~133.01~L~1~4.5~124.83~L~2~4.4~319.33~L~3~|4.7~86.61~B~1~4.8~247.9~B~2~4.9~142.0~B~3~:' I would like to return the 3rd item delimited with ~, which in this case, is 4.7 Can anyone help? Many thanks! Cheers, Garry From roadierich at googlemail.com Wed Jul 8 19:22:02 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 8 Jul 2009 18:22:02 +0100 Subject: [Tutor] Quick question regarding Parsing a Delimited string In-Reply-To: References: Message-ID: <696BD046-A9A1-4443-9A40-B867A6D85A75@googlemail.com> On 8 Jul 2009, at 17:13, Garry Bettle wrote: > Hi, > > I've been programming for over 20 yrs, but only the last few in python > and then only in dribs and drabs. > > I'm having a difficult time parsing a delimited string. > > e.g. > > 100657641~GBP~ACTIVE~0~1~~true~5.0~1247065352508~: > 3818854~0~24104.08~4.5~~22.1~false| > 4.4~241.67~L~1~4.3~936.0~L~2~4.2~210.54~L~3~| > 4.5~19.16~B~1~4.6~214.27~B~2~4.7~802.13~B~3~: > 3991404~1~19974.18~4.7~~21.7~false| > 4.6~133.01~L~1~4.5~124.83~L~2~4.4~319.33~L~3~| > 4.7~86.61~B~1~4.8~247.9~B~2~4.9~142.0~B~3~: > 4031423~2~15503.56~6.6~~15.1~false| > 6.6~53.21~L~1~6.4~19.23~L~2~6.2~53.28~L~3~| > 6.8~41.23~B~1~7.0~145.04~B~2~7.2~37.23~B~3~ > > That is just a selection of the full string - and I've broken it up > for this email. It's delimited by : and then by ~ and finally, in > some cases, | (a pipe). > > If the string is called m, I thought I could create a list with > m.split(":"). I would like to then first of all find in this list the > entry beginning with e.g. 3991404. > > I thought I could pop each item in the list and compare that seems > pretty long winded. > > When the ItemFound is now = > '3991404~1~19974.18~4.7~~21.7~false| > 4.6~133.01~L~1~4.5~124.83~L~2~4.4~319.33~L~3~| > 4.7~86.61~B~1~4.8~247.9~B~2~4.9~142.0~B~3~:' > > I would like to return the 3rd item delimited with ~, which in this > case, is 4.7 > > Can anyone help? > > Many thanks! > > Cheers, > > Garry > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I've been dealing with a similar problem myself, parsing input for project Euler. The way I did it was to map a split function onto the first list: lst = map(lambda s: s.split("~"), m.split(":")) You can get the same effect with a comprehension: lst = [s.split("~") for s in m.split(":")] You can then use a function like the following: def find(term): for i in lst: if i[0] == term: return i[3] Of course, this assumes that you only want the first match, but it would be trivial to modify it to return all matches. Does that help? If it doesn't solve the problem, I hope it will at least point you towards how to solve it. If you really want to speed up the search, you could turn the list of lists into a dict, using the first value in each sublist as a key: dct = dict((i[0], i[1:]) for i in lst) Then you can access it using the normal dictionary interface. dct["3991404"][3] This will only return the last of any repeated values (previous ones will get overwritten during construction), so it really depends on the behaviour you want. --- Richard "Roadie Rich" Lovely Part of the JNP|UK Famille www.theJNP.com (Sent from my iPod - please allow me a few typos: it's a very small keyboard) From sbuck at are.berkeley.edu Wed Jul 8 18:13:31 2009 From: sbuck at are.berkeley.edu (Steven Buck) Date: Wed, 8 Jul 2009 09:13:31 -0700 Subject: [Tutor] error message Message-ID: I'm running a for loop which returns an error message after the third iteration (see out[4] at the bottom as evidence). I don't understand the error message. Although I'll continue to do my own digging to debug, I thought I'd give you all a shot. Thanks, -steve Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.9.1 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: import psid In [2]: age = {} In [3]: for i in range(len(psid.psid)): ...: age[(i)] = psid.psid[i][20] ...: ...: --------------------------------------------------------------------------- error Traceback (most recent call last) C:\Documents and Settings\Steve\ in () C:\Python26\lib\site-packages\StataTools.pyc in __getitem__(self, k) 85 if self._file.tell() != loc: 86 self._file.seek(loc) ---> 87 return self._next() 88 89 ### PyDTA private methods C:\Python26\lib\site-packages\StataTools.pyc in _next(self) 167 else: 168 data[i] = self._unpack(typlist[i], self._file.read(s elf._col_size(i))) 169 return data 170 else: --> 171 return map(lambda i: self._unpack(typlist[i], self._file.rea d(self._col_size(i))), range(self._header['nvar'])) C:\Python26\lib\site-packages\StataTools.pyc in (i) 167 else: 168 data[i] = self._unpack(typlist[i], self._file.read(s elf._col_size(i))) 169 return data 170 else: --> 171 return map(lambda i: self._unpack(typlist[i], self._file.rea d(self._col_size(i))), range(self._header['nvar'])) C:\Python26\lib\site-packages\StataTools.pyc in _unpack(self, fmt, byt) 148 149 def _unpack(self, fmt, byt): --> 150 d = unpack(self._header['byteorder']+fmt, byt)[0] 151 if fmt[-1] in self.MISSING_VALUES: 152 nmin, nmax = self.MISSING_VALUES[fmt[-1]] error: unpack requires a string argument of length 1 In [4]: age Out[4]: {0: 22, 1: 51, 2: 42} In [5]: -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jul 8 19:49:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 8 Jul 2009 13:49:11 -0400 Subject: [Tutor] Quick question regarding Parsing a Delimited string In-Reply-To: References: Message-ID: <1c2a2c590907081049s11692fb2uc27c25eeec43a28a@mail.gmail.com> On Wed, Jul 8, 2009 at 12:13 PM, Garry Bettle wrote: > Hi, > > I've been programming for over 20 yrs, but only the last few in python > and then only in dribs and drabs. > > I'm having a difficult time parsing a delimited string. > > e.g. > > 100657641~GBP~ACTIVE~0~1~~true~5.0~1247065352508~: > 3818854~0~24104.08~4.5~~22.1~false|4.4~241.67~L~1~4.3~936.0~L~2~4.2~210.54~L~3~|4.5~19.16~B~1~4.6~214.27~B~2~4.7~802.13~B~3~: > 3991404~1~19974.18~4.7~~21.7~false|4.6~133.01~L~1~4.5~124.83~L~2~4.4~319.33~L~3~|4.7~86.61~B~1~4.8~247.9~B~2~4.9~142.0~B~3~: > 4031423~2~15503.56~6.6~~15.1~false|6.6~53.21~L~1~6.4~19.23~L~2~6.2~53.28~L~3~|6.8~41.23~B~1~7.0~145.04~B~2~7.2~37.23~B~3~ > > That is just a selection of the full string - and I've broken it up > for this email. ?It's delimited by : and then by ~ and finally, in > some cases, | (a pipe). > > If the string is called m, I thought I could create a list with > m.split(":"). ?I would like to then first of all find in this list the > entry beginning with e.g. 3991404. A couple of splits and a search will do it: In [1]: data = """100657641~GBP~ACTIVE~0~1~~true~5.0~1247065352508~: ...: 3818854~0~24104.08~4.5~~22.1~false|4.4~241.67~L~1~4.3~936.0~L~2~4.2~210.54~L~3~|4.5~19.16~B~1~4.6~214.27~B~2~4.7~802.1 3~B~3~: ...: 3991404~1~19974.18~4.7~~21.7~false|4.6~133.01~L~1~4.5~124.83~L~2~4.4~319.33~L~3~|4.7~86.61~B~1~4.8~247.9~B~2~4.9~1 42.0~B~3~: ...: 4031423~2~15503.56~6.6~~15.1~false|6.6~53.21~L~1~6.4~19.23~L~2~6.2~53.28~L~3~|6.8~41.23~B~1~7.0~145.04~B~2~7.2 ~37.23~B~3~""" In [6]: items = [ item.strip().split('~') for item in data.split(':') ] The strip() is only needed because when I pasted your string the interpreter introduced white space. In [7]: for item in items: ...: print item[0] 100657641 3818854 3991404 4031423 In [9]: for item in items: ...: if item[0] == '3991404': ...: print item[3] 4.7 Kent From emile at fenx.com Wed Jul 8 20:13:15 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 08 Jul 2009 11:13:15 -0700 Subject: [Tutor] error message In-Reply-To: References: Message-ID: On 7/8/2009 9:13 AM Steven Buck said... > I'm running a for loop which returns an error message after the third > iteration (see out[4] at the bottom as evidence). I don't understand > the error message. Although I'll continue to do my own digging to > debug, I thought I'd give you all a shot. Thanks, -steve > age[(i)] = psid.psid[i][20] Here you're getting the 20th field from the 4th record. So, assuming the tools you're using are OK... > --> 150 d = unpack(self._header['byteorder']+fmt, byt)[0] > error: unpack requires a string argument of length 1 ... you get an unpack error. So my money's on a source data problem. you might try... for ii in range(40): print psid.psid[3][ii] ...and see what you get. It's likely a bad record of some sort. You might need to allow for those... HTH, Emile From kent37 at tds.net Wed Jul 8 21:37:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 8 Jul 2009 15:37:45 -0400 Subject: [Tutor] Quick question regarding Parsing a Delimited string In-Reply-To: <696BD046-A9A1-4443-9A40-B867A6D85A75@googlemail.com> References: <696BD046-A9A1-4443-9A40-B867A6D85A75@googlemail.com> Message-ID: <1c2a2c590907081237i2fe8e033vf98891e88c65d2cb@mail.gmail.com> On Wed, Jul 8, 2009 at 1:22 PM, Rich Lovely wrote: > If you really want to speed up the search, you could turn the list of lists > into a dict, using the first value in each sublist as a key: > > dct = dict((i[0], i[1:]) for i in lst) > > Then you can access it using the normal dictionary interface. > dct["3991404"][3] I'm suspicious of this claim if there is only one lookup needed. You iterate the whole list and incur the overhead of constructing a dict. If there will be multiple lookups it may well be a win but as always there is no substitute for measurement if you want to know what is faster. Kent From garry.bettle at gmail.com Wed Jul 8 21:43:38 2009 From: garry.bettle at gmail.com (Garry Bettle) Date: Wed, 8 Jul 2009 21:43:38 +0200 Subject: [Tutor] Quick question regarding Parsing a Delimited string In-Reply-To: <1c2a2c590907081237i2fe8e033vf98891e88c65d2cb@mail.gmail.com> References: <696BD046-A9A1-4443-9A40-B867A6D85A75@googlemail.com> <1c2a2c590907081237i2fe8e033vf98891e88c65d2cb@mail.gmail.com> Message-ID: On Wed, Jul 8, 2009 at 21:37, Kent Johnson wrote: > On Wed, Jul 8, 2009 at 1:22 PM, Rich Lovely wrote: > >> If you really want to speed up the search, you could turn the list of lists >> into a dict, using the first value in each sublist as a key: >> >> dct = dict((i[0], i[1:]) for i in lst) >> >> Then you can access it using the normal dictionary interface. >> dct["3991404"][3] > > I'm suspicious of this claim if there is only one lookup needed. You > iterate the whole list and incur the overhead of constructing a dict. > If there will be multiple lookups it may well be a win but as always > there is no substitute for measurement if you want to know what is > faster. > > Kent > Hi Kent, No, I think the dict will be fine: I have to find every one that is in my original list. Many thanks to both you and Rich for all the help. I'll let you know how I get on. Cheers, Garry From bgailer at gmail.com Wed Jul 8 22:12:21 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 08 Jul 2009 16:12:21 -0400 Subject: [Tutor] error message In-Reply-To: References: Message-ID: <4A54FDA5.2020205@gmail.com> An HTML attachment was scrubbed... URL: From buckstec at gmail.com Wed Jul 8 22:35:34 2009 From: buckstec at gmail.com (Steven Buck) Date: Wed, 8 Jul 2009 13:35:34 -0700 Subject: [Tutor] error message In-Reply-To: <4A54FDA5.2020205@gmail.com> References: <4A54FDA5.2020205@gmail.com> Message-ID: As Bob prescribed, I added (and made sure to indent): print self._header['byteorder'], fmt, byt The fourth printed line appears to be the same: Out[4]: {0: 22, 1: 51, 2: 42} This is consistent with what I observe as the first three age observations in the Stata data editor. I include the rest of the error message I received (& could capture) below. Any more thoughts? Thanks Steve < b ? < b ? < b ? < b ? < b ? < b ? < b ? < f PCF < b ? < f ?Q?@ < b ? < f `A < b ? < b ? < f < f < b < b < b ? < h ? < f ?C < b e < b ? < b < b < b < b ? < b ? < b ? < b ? < h ? < h < f 5??D < b ? < b < b < b < b < b < b ? < b ? < h ?? < b ? < b ? < f ?B < f ???B < f ???B < f ?B < f ???B < f ???B < f ???B < f ffzB < f ???B < f ff?B < f ffrB < f 33?B < f ?Q8? < f ???@ < f ?1?? < f b?2A < f ?o at A < f ??OA < f ??QA < f ?? < h ?? < b < h ? < h in () C:\Python26\lib\site-packages\StataTools.py in __getitem__(self, k) 85 if self._file.tell() != loc: 86 self._file.seek(loc) ---> 87 return self._next() 88 89 ### PyDTA private methods C:\Python26\lib\site-packages\StataTools.py in _next(self) 168 else: 169 data[i] = self._unpack(typlist[i], self._file.read(s elf._col_size(i))) 170 return data 171 else: --> 172 return map(lambda i: self._unpack(typlist[i], self._file.rea d(self._col_size(i))), range(self._header['nvar'])) C:\Python26\lib\site-packages\StataTools.py in (i) 168 else: 169 data[i] = self._unpack(typlist[i], self._file.read(s elf._col_size(i))) 170 return data 171 else: --> 172 return map(lambda i: self._unpack(typlist[i], self._file.rea d(self._col_size(i))), range(self._header['nvar'])) C:\Python26\lib\site-packages\StataTools.py in _unpack(self, fmt, byt) 149 def _unpack(self, fmt, byt): 150 print self._header['byteorder'], fmt, byt --> 151 d = unpack(self._header['byteorder']+fmt, byt)[0] 152 if fmt[-1] in self.MISSING_VALUES: 153 nmin, nmax = self.MISSING_VALUES[fmt[-1]] error: unpack requires a string argument of length 1 In [4]: age Out[4]: {0: 22, 1: 51, 2: 42} In [5]: On Wed, Jul 8, 2009 at 1:12 PM, bob gailer wrote: > Steven Buck wrote: > > I'm running a for loop which returns an error message after the third > iteration (see out[4] at the bottom as evidence). I don't understand the > error message. Although I'll continue to do my own digging to debug, I > thought I'd give you all a shot. Thanks, -steve > > Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit > (Intel)] > Type "copyright", "credits" or "license" for more information. > IPython 0.9.1 -- An enhanced Interactive Python. > ? -> Introduction and overview of IPython's features. > %quickref -> Quick reference. > help -> Python's own help system. > object? -> Details about 'object'. ?object also works, ?? prints more. > In [1]: import psid > In [2]: age = {} > In [3]: for i in range(len(psid.psid)): > ...: age[(i)] = psid.psid[i][20] > ...: > ...: > --------------------------------------------------------------------------- > error Traceback (most recent call last) > C:\Documents and Settings\Steve\ in () > C:\Python26\lib\site-packages\StataTools.pyc in __getitem__(self, k) > 85 if self._file.tell() != loc: > 86 self._file.seek(loc) > ---> 87 return self._next() > 88 > 89 ### PyDTA private methods > > C:\Python26\lib\site-packages\StataTools.pyc in _next(self) > 167 else: > 168 data[i] = self._unpack(typlist[i], > self._file.read(s > elf._col_size(i))) > 169 return data > 170 else: > --> 171 return map(lambda i: self._unpack(typlist[i], > self._file.rea > d(self._col_size(i))), range(self._header['nvar'])) > C:\Python26\lib\site-packages\StataTools.pyc in (i) > 167 else: > 168 data[i] = self._unpack(typlist[i], > self._file.read(s > elf._col_size(i))) > 169 return data > 170 else: > --> 171 return map(lambda i: self._unpack(typlist[i], > self._file.rea > d(self._col_size(i))), range(self._header['nvar'])) > C:\Python26\lib\site-packages\StataTools.pyc in _unpack(self, fmt, byt) > 148 > 149 def _unpack(self, fmt, byt): > > > Add here (temporarily) print self._header['byteorder'], fmt, byt > make sure it is indented the same as 150. > Let's examine the 4th printed line. > > --> 150 d = unpack(self._header['byteorder']+fmt, byt)[0] > 151 if fmt[-1] in self.MISSING_VALUES: > 152 nmin, nmax = self.MISSING_VALUES[fmt[-1]] > error: unpack requires a string argument of length 1 > In [4]: age > Out[4]: {0: 22, 1: 51, 2: 42} > In [5]: > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From froslie at gmail.com Thu Jul 9 00:28:08 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 8 Jul 2009 18:28:08 -0400 Subject: [Tutor] thesaurus Message-ID: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> okay.. I'm getting the hang of python a little more. I'd like to try something a bit more complicated (for me). I would like to convert each word in a series of paragraphs to its first matching synonym in a thesaurus. I'm a bit stuck as how to start.. I think I understand how to split and parse the original paragraphs, but the thesaurus is throwing me. I'm thinking maybe find a CSV thesaurus -or- a thesaurus online with an API.. I'm wondering if anyone has done something similar that may point me in the correct direction? thanks, -- Pete F -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jul 9 01:10:35 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 8 Jul 2009 16:10:35 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> Message-ID: <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> On Sun, Jul 5, 2009 at 11:48 PM, Luis Galvan wrote: > Hello all, this is my first time using a mailing list, so I'm not sure if > I'm doing this right!? Anyway, I have a wee bit of a problem.? I've recently > completed watching a Youtube video series on Python 2.6 by thenewboston > which helped me a TON with learning Python's syntax and how to use some of > the various builtin modules.? I am very thankful for his tutorials, but the > only thing that I need is something to help me really grasp onto the world > of programming. (I'm new to programming)? What I'm looking for is a tutorial > series that walks you through the steps of writing a useful program in > Python. luis, no sales pitch here (or at least none intended), but if you ever come across a copy of "Core Python Programming," i've put lots of exercises at the end of every chapter. not all of them are full-scale applications, but it is good practice writing snippets of code that at some point may be plugged *into* an application at some point. best regards, and welcome to Python! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From python at bdurham.com Thu Jul 9 01:37:42 2009 From: python at bdurham.com (python at bdurham.com) Date: Wed, 08 Jul 2009 19:37:42 -0400 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> Message-ID: <1247096262.11978.1324168009@webmail.messagingengine.com> > but if you ever come across a copy of "Core Python Programming," i've put lots of exercises at the end of every chapter. +1 from a reader/customer (vs. the author) "Core Python Programming" is an excellent resource for learning Python. I enjoyed the exercises - they force you to master the content vs. thinking you know what's going on via a fast skim of the content. Highly recommended! Regards, Malcolm From emile at fenx.com Thu Jul 9 01:59:47 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 08 Jul 2009 16:59:47 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <1247096262.11978.1324168009@webmail.messagingengine.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> <1247096262.11978.1324168009@webmail.messagingengine.com> Message-ID: >> but if you ever come across a copy of "Core Python Programming," i've put lots of exercises at the end of every chapter. > > +1 from a reader/customer (vs. the author) +1 from a reviewer (vs. a reader/customer (vs. the author)) :) From bermanrl at cfl.rr.com Thu Jul 9 02:25:28 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 08 Jul 2009 20:25:28 -0400 Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> Message-ID: <1247099128.3915.3.camel@bermanrl-desktop> http://pywordnet.sourceforge.net/ This will get you started. This is a tad easier to play with than its newer implementation. Read and experiment. it may meet most of your needs in this arena. Good Luck, Robert On Wed, 2009-07-08 at 18:28 -0400, Pete Froslie wrote: > okay.. I'm getting the hang of python a little more. I'd like to try > something a bit more complicated (for me). I would like to convert > each word in a series of paragraphs to its first matching synonym in a > thesaurus. I'm a bit stuck as how to start.. I think I understand how > to split and parse the original paragraphs, but the thesaurus is > throwing me. I'm thinking maybe find a CSV thesaurus -or- a thesaurus > online with an API.. I'm wondering if anyone has done something > similar that may point me in the correct direction? > > > thanks, > > -- > Pete F > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Thu Jul 9 02:33:16 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 08 Jul 2009 20:33:16 -0400 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> Message-ID: <1247099596.3915.10.camel@bermanrl-desktop> While it is not a sales pitch, the book is excellent. It and the Python Cookbook sit on top of my desk. Both are fantastic and pragmatic reference sources. Robert On Wed, 2009-07-08 at 16:10 -0700, wesley chun wrote: > On Sun, Jul 5, 2009 at 11:48 PM, Luis Galvan wrote: > > Hello all, this is my first time using a mailing list, so I'm not sure if > > I'm doing this right! Anyway, I have a wee bit of a problem. I've recently > > completed watching a Youtube video series on Python 2.6 by thenewboston > > which helped me a TON with learning Python's syntax and how to use some of > > the various builtin modules. I am very thankful for his tutorials, but the > > only thing that I need is something to help me really grasp onto the world > > of programming. (I'm new to programming) What I'm looking for is a tutorial > > series that walks you through the steps of writing a useful program in > > Python. > > > luis, > > no sales pitch here (or at least none intended), but if you ever come > across a copy of "Core Python Programming," i've put lots of exercises > at the end of every chapter. not all of them are full-scale > applications, but it is good practice writing snippets of code that at > some point may be plugged *into* an application at some point. > > best regards, and welcome to Python! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Jul 9 02:40:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 9 Jul 2009 01:40:05 +0100 Subject: [Tutor] using datetime and calculating hourly average References: <24370537.post@talk.nabble.com> <4A536545.7060705@gmail.com><24375619.post@talk.nabble.com> <24388708.post@talk.nabble.com> Message-ID: "John [H2O]" wrote > --> 196 ind = np.where( (t1 < Y[:,0] < t2) ) #same result > > TypeError: can't compare datetime.datetime to numpy.ndarray Have you checked what you are comparing? Try printing Y[:,0] It looks like an invalid test and no amolunt of parenthesising or 'and'ing will make it work. > --> 196 ind = np.where( (Y[:,0]>t1) and (Y[:,0] > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() Looks like the Y[:,0] value is not compatible with the time t1 or t2. What does print Y[:,0] produce? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From froslie at gmail.com Thu Jul 9 02:54:01 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 8 Jul 2009 20:54:01 -0400 Subject: [Tutor] Fwd: thesaurus In-Reply-To: <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> Message-ID: <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> ---------- Forwarded message ---------- From: Pete Froslie Date: Wed, Jul 8, 2009 at 8:53 PM Subject: Re: [Tutor] thesaurus To: Robert Berman Thanks Robert, I will try this out.. at the moment I'm playing with an API from ' http://words.bighugelabs.com/'. It works and pulls the synonyms into python. It cost money if you want to process more than 10,000 in a day though. I do have another pretty noob question that I'm figuring out -- once I have a list of synonyms returned, is there a simple way to replace the words I looked up inside of the 'txt' file? For instance, I open and read the 'txt' file, grab the first word, search it with the thesaurus, get the result, write the result back to the file, and then grab the next word to repeat the process. It seems like there is probably a quick shortcut for this.. thanks so much On Wed, Jul 8, 2009 at 8:25 PM, Robert Berman wrote: > http://pywordnet.sourceforge.net/ > > This will get you started. This is a tad easier to play with than its > newer implementation. Read and experiment. it may meet most of your > needs in this arena. > > Good Luck, > > Robert > > > > On Wed, 2009-07-08 at 18:28 -0400, Pete Froslie wrote: > > okay.. I'm getting the hang of python a little more. I'd like to try > > something a bit more complicated (for me). I would like to convert > > each word in a series of paragraphs to its first matching synonym in a > > thesaurus. I'm a bit stuck as how to start.. I think I understand how > > to split and parse the original paragraphs, but the thesaurus is > > throwing me. I'm thinking maybe find a CSV thesaurus -or- a thesaurus > > online with an API.. I'm wondering if anyone has done something > > similar that may point me in the correct direction? > > > > > > thanks, > > > > -- > > Pete F > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- Pete Froslie 617.314.0957 http://www.froslie.net -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Jul 9 03:41:28 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 9 Jul 2009 02:41:28 +0100 Subject: [Tutor] Fwd: thesaurus In-Reply-To: <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> Message-ID: 2009/7/9 Pete Froslie : > > > ---------- Forwarded message ---------- > From: Pete Froslie > Date: Wed, Jul 8, 2009 at 8:53 PM > Subject: Re: [Tutor] thesaurus > To: Robert Berman > > > Thanks Robert, > > I will try this out.. at the moment I'm playing with an API from > 'http://words.bighugelabs.com/'. It works and pulls the synonyms into > python. It cost money if you want to process more than 10,000 in a day > though. > > I do have another pretty noob question that I'm figuring out -- once I have > a list of synonyms returned, is there a simple way to replace the words I > looked up inside of the 'txt' file? > > For instance, I open and read the 'txt' file, grab the first word, search it > with the thesaurus, get the result, write the result back to the file, and > then grab the next word to repeat the process. It seems like there is > probably a quick shortcut for this.. > > thanks so much > > > Assuming lookup() handles punctuation and capitalisation... import sys if sys.version_info < (2,5): print "This script needs a more recent version of python" sys.exit(1) elif sys.version_info < (2,6): from __future__ import with_statement buff = [] with open("path_to_input_file", "r") as fin: for line in fin: buff.append(" ".join(lookup(word) for word in line.split())) with open("path_to_output_file", "w") as fout: fout.write("\n".join(buff)) This is also a good intro to the with statement, which cleans everything up for you. Unfortunatly, it was only introduced in 2.5 as a __future__ feature, and 2.6 as a final feature. If you've got a version prior to that, you'll need to rework it a little, or upgrade. But I think this gives the general idea. I don't think there's any more concise way of doing it than that in python. You also might want to use print instead of writing straight to a file, and use the terminal's stream redirection to put the output into a file. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From froslie at gmail.com Thu Jul 9 03:57:29 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 8 Jul 2009 21:57:29 -0400 Subject: [Tutor] Fwd: thesaurus In-Reply-To: References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> Message-ID: <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> Great Richard, thanks.. I'm getting an error as follows: from __future__ import with_statement SyntaxError: from __future__ imports must occur at the beginning of the file I don't think this is the issue in need of rework and have tried a few quick reworks.. I'll read up a bit on 'with' cheers On Wed, Jul 8, 2009 at 9:41 PM, Rich Lovely wrote: > 2009/7/9 Pete Froslie : > > > > > > ---------- Forwarded message ---------- > > From: Pete Froslie > > Date: Wed, Jul 8, 2009 at 8:53 PM > > Subject: Re: [Tutor] thesaurus > > To: Robert Berman > > > > > > Thanks Robert, > > > > I will try this out.. at the moment I'm playing with an API from > > 'http://words.bighugelabs.com/'. It works and pulls the synonyms into > > python. It cost money if you want to process more than 10,000 in a day > > though. > > > > I do have another pretty noob question that I'm figuring out -- once I > have > > a list of synonyms returned, is there a simple way to replace the words I > > looked up inside of the 'txt' file? > > > > For instance, I open and read the 'txt' file, grab the first word, search > it > > with the thesaurus, get the result, write the result back to the file, > and > > then grab the next word to repeat the process. It seems like there is > > probably a quick shortcut for this.. > > > > thanks so much > > > > > > > > Assuming lookup() handles punctuation and capitalisation... > > import sys > > if sys.version_info < (2,5): > print "This script needs a more recent version of python" > sys.exit(1) > elif sys.version_info < (2,6): > from __future__ import with_statement > > buff = [] > with open("path_to_input_file", "r") as fin: > for line in fin: > buff.append(" ".join(lookup(word) for word in line.split())) > > with open("path_to_output_file", "w") as fout: > fout.write("\n".join(buff)) > > This is also a good intro to the with statement, which cleans > everything up for you. Unfortunatly, it was only introduced in 2.5 as > a __future__ feature, and 2.6 as a final feature. If you've got a > version prior to that, you'll need to rework it a little, or upgrade. > > But I think this gives the general idea. I don't think there's any > more concise way of doing it than that in python. > > You also might want to use print instead of writing straight to a > file, and use the terminal's stream redirection to put the output into > a file. > > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Jul 9 04:10:10 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 9 Jul 2009 03:10:10 +0100 Subject: [Tutor] Fwd: thesaurus In-Reply-To: <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> Message-ID: 2009/7/9 Pete Froslie : > Great Richard, thanks.. > > I'm getting an error as follows: > > from __future__ import with_statement > SyntaxError: from __future__ imports must occur at the beginning of the file > > I don't think this is the issue in need of rework and have tried a few quick > reworks.. I'll read up a bit on 'with' > > cheers > > (Appologies for my inital, incomplete email...) Oops... forgot it wasn't a standard import... Just move it to the first line of the program, and delete the relevant elif branch. It won't hurt code on more recent versions. from __future__ import with_statement import sys buff = [] with open("path_to_input_file", "r") as fin: for line in fin: buff.append(" ".join(lookup(word) for word in line.split())) with open("path_to_output_file", "w") as fout: fout.write("\n".join(buff)) -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From froslie at gmail.com Thu Jul 9 04:27:00 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 8 Jul 2009 22:27:00 -0400 Subject: [Tutor] Fwd: thesaurus In-Reply-To: References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> Message-ID: <41fcacc90907081927p39eb884n634a70461838fe19@mail.gmail.com> No problem, thanks for taking the time. I'm actually trying to resolve this error now: buff.append(" ".join(lookup(Word) for Word in line.split())) NameError: global name 'lookup' is not defined ..also assume I need to change 'Word' to something that checks the next word in the text file and then replaces it with the one that is looked up.. working on that now. Pete F On Wed, Jul 8, 2009 at 10:10 PM, Rich Lovely wrote: > 2009/7/9 Pete Froslie : > > Great Richard, thanks.. > > > > I'm getting an error as follows: > > > > from __future__ import with_statement > > SyntaxError: from __future__ imports must occur at the beginning of the > file > > > > I don't think this is the issue in need of rework and have tried a few > quick > > reworks.. I'll read up a bit on 'with' > > > > cheers > > > > > > (Appologies for my inital, incomplete email...) > Oops... forgot it wasn't a standard import... > > Just move it to the first line of the program, and delete the relevant > elif branch. > > It won't hurt code on more recent versions. > > from __future__ import with_statement > import sys > > buff = [] > with open("path_to_input_file", "r") as fin: > for line in fin: > buff.append(" ".join(lookup(word) for word in line.split())) > > with open("path_to_output_file", "w") as fout: > fout.write("\n".join(buff)) > > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Jul 9 04:29:55 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 9 Jul 2009 03:29:55 +0100 Subject: [Tutor] Fwd: thesaurus In-Reply-To: <41fcacc90907081927p39eb884n634a70461838fe19@mail.gmail.com> References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> <41fcacc90907081927p39eb884n634a70461838fe19@mail.gmail.com> Message-ID: 2009/7/9 Pete Froslie : > No problem, thanks for taking the time. > > I'm actually trying to resolve this error now: > > ?? buff.append(" ".join(lookup(Word) for Word in line.split())) > NameError: global name 'lookup' is not defined > > ..also assume I need to change 'Word' to something that checks the next word > in the text file and then replaces it with the one that is looked up.. > working on that now. > > Pete F lookup() is the function that looks up the word in the thesaurus. I left implementing that as an exercise for you, as I don't know the format of the reference you're using. -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From froslie at gmail.com Thu Jul 9 04:41:56 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 8 Jul 2009 22:41:56 -0400 Subject: [Tutor] Fwd: thesaurus In-Reply-To: References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> <41fcacc90907081927p39eb884n634a70461838fe19@mail.gmail.com> Message-ID: <41fcacc90907081941qaecf218q962b93705b597e6a@mail.gmail.com> I see.. that makes sense. Kind of new with python -- sorry for that. after printing using this: print urllib.urlopen(' http://words.bighugelabs.com/api/2/e413f24801aa30b8d441ca43a64317be/moving/').read( ) I'm getting a format like this returned: adjective|sim|streaming adjective|sim|swirling adjective|sim|tossing adjective|sim|touching adjective|sim|touring adjective|sim|traveling adjective|sim|tumbling I assume I need to clean this up by reading past 'Adjective|sim|' to 'streaming' and then returning it from lookup().. this will be happening in the following: urllib.urlopen(' http://words.bighugelabs.com/api/2/e413f24801aa30b8d441ca43a64317be/moving/').read(SOMETHINGHERE) On Wed, Jul 8, 2009 at 10:29 PM, Rich Lovely wrote: > 2009/7/9 Pete Froslie : > > No problem, thanks for taking the time. > > > > I'm actually trying to resolve this error now: > > > > buff.append(" ".join(lookup(Word) for Word in line.split())) > > NameError: global name 'lookup' is not defined > > > > ..also assume I need to change 'Word' to something that checks the next > word > > in the text file and then replaces it with the one that is looked up.. > > working on that now. > > > > Pete F > > lookup() is the function that looks up the word in the thesaurus. I > left implementing that as an exercise for you, as I don't know the > format of the reference you're using. > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Thu Jul 9 05:12:55 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 9 Jul 2009 04:12:55 +0100 Subject: [Tutor] Fwd: thesaurus In-Reply-To: <41fcacc90907081941qaecf218q962b93705b597e6a@mail.gmail.com> References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <1247099128.3915.3.camel@bermanrl-desktop> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> <41fcacc90907081927p39eb884n634a70461838fe19@mail.gmail.com> <41fcacc90907081941qaecf218q962b93705b597e6a@mail.gmail.com> Message-ID: 2009/7/9 Pete Froslie : > I see.. that makes sense. Kind of new with python -- sorry for that. > > after printing using this: > > print > urllib.urlopen('http://words.bighugelabs.com/api/2/e413f24801aa30b8d441ca43a64317be/moving/').read() > > I'm getting a format like this returned: > > adjective|sim|streaming > adjective|sim|swirling > adjective|sim|tossing > adjective|sim|touching > adjective|sim|touring > adjective|sim|traveling > adjective|sim|tumbling > > I assume I need to clean this up by reading past? 'Adjective|sim|' to > 'streaming' and then returning it from lookup().. > this will be happening in the following: > > urllib.urlopen('http://words.bighugelabs.com/api/2/e413f24801aa30b8d441ca43a64317be/moving/').read(SOMETHING > HERE) > > > I don't think there is any easy way of doing that. You would be better off using the split method of the strings, and ignoring the first parts for now. Have you considered what happens with the word set in the following sentance, about testing TV receivers: We've set the code number of each set to a reasonable value for this set of experiments. I can't get the api to work for me, but the way you're doing it at the moment, you'd end up with something like We've fixed the code number of each fixed to a reasonable value for this fixed of experiments. A contrived example, I know, but it makes the point. Unless, of course, this sort of gibberish is what you're after. Natural language parsers are one of the hardest things to create. Just look up the word "set" in a dictionary to see why. Even if you did work out that the second "set" was a noun, is it "a radio or television receiver" or "a group or collection of things that belong together, resemble one another, or are usually found together" -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From froslie at gmail.com Thu Jul 9 05:25:28 2009 From: froslie at gmail.com (Pete Froslie) Date: Wed, 8 Jul 2009 23:25:28 -0400 Subject: [Tutor] Fwd: thesaurus In-Reply-To: References: <41fcacc90907081528o75acb930pc4cbadd4d2898885@mail.gmail.com> <41fcacc90907081753r60276ebdl7367cf73ab0fcbf8@mail.gmail.com> <41fcacc90907081754h670e2550ne8663a673c5397b7@mail.gmail.com> <41fcacc90907081857p1dc553d9k8cad00b4af209c42@mail.gmail.com> <41fcacc90907081927p39eb884n634a70461838fe19@mail.gmail.com> <41fcacc90907081941qaecf218q962b93705b597e6a@mail.gmail.com> Message-ID: <41fcacc90907082025h46b22f0cgfc4085474dfc0d35@mail.gmail.com> oops.. I just realized I attached the wrong example for the API-- it was off by number, this one works: print urllib.urlopen(' http://words.bighugelabs.com/api/2/e413f24701aa30b8d441ca43a64317be/moving/').read( ) The example makes sense to me and I can see how it is difficult to figure out a natural language parser.. as it turns out, I don't mind it for this project--gibberish is fine. Though I am now pretty curious about NL parsers-- thanks for the example.. I will look at using the split method of strings.. On Wed, Jul 8, 2009 at 11:12 PM, Rich Lovely wrote: > 2009/7/9 Pete Froslie : > > I see.. that makes sense. Kind of new with python -- sorry for that. > > > > after printing using this: > > > > print > > urllib.urlopen(' > http://words.bighugelabs.com/api/2/e413f24801aa30b8d441ca43a64317be/moving/').read( > ) > > > > I'm getting a format like this returned: > > > > adjective|sim|streaming > > adjective|sim|swirling > > adjective|sim|tossing > > adjective|sim|touching > > adjective|sim|touring > > adjective|sim|traveling > > adjective|sim|tumbling > > > > I assume I need to clean this up by reading past 'Adjective|sim|' to > > 'streaming' and then returning it from lookup().. > > this will be happening in the following: > > > > urllib.urlopen(' > http://words.bighugelabs.com/api/2/e413f24801aa30b8d441ca43a64317be/moving/').read(SOMETHING > > HERE) > > > > > > > I don't think there is any easy way of doing that. > > You would be better off using the split method of the strings, and > ignoring the first parts for now. > > Have you considered what happens with the word set in the following > sentance, about testing TV receivers: > > We've set the code number of each set to a reasonable value for this > set of experiments. > > I can't get the api to work for me, but the way you're doing it at the > moment, you'd end up with something like > > We've fixed the code number of each fixed to a reasonable value for > this fixed of experiments. > > A contrived example, I know, but it makes the point. > > Unless, of course, this sort of gibberish is what you're after. > > Natural language parsers are one of the hardest things to create. > Just look up the word "set" in a dictionary to see why. Even if you > did work out that the second "set" was a noun, is it "a radio or > television receiver" or "a group or collection of things that belong > together, resemble one another, or are usually found together" > > -- > Richard "Roadie Rich" Lovely, part of the JNP|UK Famile > www.theJNP.com > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jul 9 09:54:28 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 9 Jul 2009 00:54:28 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <1247099596.3915.10.camel@bermanrl-desktop> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> <1247099596.3915.10.camel@bermanrl-desktop> Message-ID: <78b3a9580907090054x30f97ff2r963d1af3fa9a596f@mail.gmail.com> Robert, Emile, Malcolm, wow, you guys are making me blush while hijacking this thread! people are gonna start thinking i paid you off somehow LOL! :-) seriously, thanks for the kudos. since i'm a technical instructor, i wrote it not only from the software engineer's perspective, but also a teacher's, and i know that nothing can substitute for the experience gained when writing code in a language new to you. the OP hit it right on the head -- he watched videos and studied the syntax, but then what are you going to do with your newfound knowledge? gotta put it to use. writing a full-scale hardcore ap- plication, while effective, may get too large for your britches and may be easily abandoned, making you less likely to pick it up again later. the point of the short exercises is to get you going and to get comfortable in order to adequately *prepare* you for your first large project in your new favorite programming language! anyway, off the soapbox with me. if anyone wants to read all the good (and bad) reviews of the book on a single page, just go to the book's website at http://corepython.com and click on the reviews link on the left-hand side. best regards! -wesley ps. for those of you who already have the book, be sure to download the errata if you have an older printing... i had a long laundry list of things that the publisher didn't get to until recently. the latest printing of the book will have most of not all the cor- rections already made, plus i've just added brand new appendices on 2.6 and 3.x to keep it current -- the book was developed during the 2.5 timeframe. i'm working with the publisher to make these 2 appen- dices available to everyone who purchased earlier copies of the book. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com On Wed, Jul 8, 2009 at 5:33 PM, Robert Berman wrote: > While it is not a sales pitch, the book is excellent. It and the Python > Cookbook sit on top of my desk. Both are fantastic and pragmatic > reference sources. On Wed, Jul 8, 2009 at 4:59 PM, Emile van Sebille wrote: > > +1 from a reviewer (vs. a reader/customer (vs. the author)) > :) On Wed, Jul 8, 2009 at 4:37 PM, wrote: > > +1 from a reader/customer (vs. the author) > > "Core Python Programming" is an excellent resource for learning Python. > I enjoyed the exercises - they force you to master the content vs. > thinking you know what's going on via a fast skim of the content. > > Highly recommended! From m.van.brummelen at antoniusziekenhuis.nl Wed Jul 8 16:26:47 2009 From: m.van.brummelen at antoniusziekenhuis.nl (Brummelen, M. van (ICT)) Date: Wed, 8 Jul 2009 16:26:47 +0200 Subject: [Tutor] setup.py to Makefile Message-ID: <64E1B95F8C29894D8D5403E7B237BF4A0218BACD@AZN-SVMA002-AMG.amg.local> Hi, What would be the best way to convert a setup.py file to a Makefile? Regards, Martijn From angusr at bigfoot.com Thu Jul 9 11:56:51 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Thu, 09 Jul 2009 10:56:51 +0100 Subject: [Tutor] Python Tutorials: How to create useful programs In-Reply-To: References: Message-ID: On Thu, 09 Jul 2009 02:40:19 +0200, you wrote: >Date: Wed, 08 Jul 2009 16:59:47 -0700 >From: Emile van Sebille >Message-ID: > >>> but if you ever come across a copy of "Core Python Programming," >>>i've put lots of exercises at the end of every chapter. >> >> +1 from a reader/customer (vs. the author) > >+1 from a reviewer (vs. a reader/customer (vs. the author)) > >:) > >------------------------------ > >Date: Wed, 08 Jul 2009 20:33:16 -0400 >From: Robert Berman >Message-ID: <1247099596.3915.10.camel at bermanrl-desktop> > >While it is not a sales pitch, the book is excellent. It and the Python >Cookbook sit on top of my desk. Both are fantastic and pragmatic >reference sources. >>> happy.append(me) >>> len(happy) 5 -- Angus Rodgers From angusr at bigfoot.com Thu Jul 9 12:17:48 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Thu, 09 Jul 2009 11:17:48 +0100 Subject: [Tutor] Fwd: thesaurus In-Reply-To: References: Message-ID: >Date: Thu, 9 Jul 2009 04:12:55 +0100 >From: Rich Lovely >Message-ID: > > >Natural language parsers are one of the hardest things to create. I think the most famous illustration of this is the problem of parsing these two sentences: Time flies like an arrow. Fruit flies like a banana. -- Angus Rodgers From a.t.hofkamp at tue.nl Thu Jul 9 12:26:08 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 09 Jul 2009 12:26:08 +0200 Subject: [Tutor] setup.py to Makefile In-Reply-To: <64E1B95F8C29894D8D5403E7B237BF4A0218BACD@AZN-SVMA002-AMG.amg.local> References: <64E1B95F8C29894D8D5403E7B237BF4A0218BACD@AZN-SVMA002-AMG.amg.local> Message-ID: <4A55C5C0.4030200@tue.nl> Brummelen, M. van (ICT) wrote: > Hi, > > What would be the best way to convert a setup.py file to a Makefile? Don't convert, simply run the setup.py from the Makefile Albert From alan.gauld at btinternet.com Thu Jul 9 13:19:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 9 Jul 2009 12:19:24 +0100 Subject: [Tutor] Fwd: thesaurus References: Message-ID: "Angus Rodgers" wrote > parsing these two sentences: > > Time flies like an arrow. > Fruit flies like a banana. Or the translation program that translated the expression Out of sight, out of mind from English to Russian and back with the result: Invisible, lunatic Alan G. From python at bdurham.com Thu Jul 9 14:53:26 2009 From: python at bdurham.com (python at bdurham.com) Date: Thu, 09 Jul 2009 08:53:26 -0400 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <78b3a9580907090054x30f97ff2r963d1af3fa9a596f@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> <1247099596.3915.10.camel@bermanrl-desktop> <78b3a9580907090054x30f97ff2r963d1af3fa9a596f@mail.gmail.com> Message-ID: <1247144006.9367.1324253579@webmail.messagingengine.com> Wesley, You mean my check is not in the mail? Damn! Well, no more positive reviews for you :) Since you've stepped off your soapbox, I'll also mention your free hour long video hosted by Safari Books (you may have to signup for a free account to see the video). What is Python by CPP (Core Python Programming) by author Wesley Chun http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcasts.php QUOTE: This one-hour webcast is ideal for technical professionals, programmers, engineers or students already literate in another high-level language that want to pick up Python as quickly as possible. No computer science background is necessary. In this webcast, leading Python developer and trainer, Wesley Chun, will help you learn Python quickly and comprehensively so you can immediately succeed with any Python project. Instead of focusing on creating applications, he will address the fundamentals of the language itself. I'm happy to hear about the errata - do you have a link? Malcolm From wescpy at gmail.com Thu Jul 9 22:53:22 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 9 Jul 2009 13:53:22 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <1247144006.9367.1324253579@webmail.messagingengine.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> <1247099596.3915.10.camel@bermanrl-desktop> <78b3a9580907090054x30f97ff2r963d1af3fa9a596f@mail.gmail.com> <1247144006.9367.1324253579@webmail.messagingengine.com> Message-ID: <78b3a9580907091353q58182ffbode6d8949b4c903f6@mail.gmail.com> On Thu, Jul 9, 2009 at 5:53 AM, wrote: > > You mean my check is not in the mail? Damn! Well, no more positive > reviews for you :) oh great, i'm in trouble now! ;) > Since you've stepped off your soapbox, I'll also mention your free hour > long video hosted by Safari Books (you may have to signup for a free > account to see the video). > > What is Python by CPP (Core Python Programming) by author Wesley Chun > http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcasts.php ah, i wasn't aware that they finished editing it and put it online. thx for the pointer! > I'm happy to hear about the errata - do you have a link? http://corepython.com (click "Errrata" link on left-hand side) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From davea at ieee.org Fri Jul 10 13:08:12 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 10 Jul 2009 07:08:12 -0400 Subject: [Tutor] thesaurus In-Reply-To: References: Message-ID: <4A57211C.6030902@ieee.org> Alan Gauld wrote: >
> "Angus Rodgers" wrote >> parsing these two sentences: >> >> Time flies like an arrow. >> Fruit flies like a banana. > > Or the translation program that translated the expression > > Out of sight, out of mind > > from English to Russian and back with the result: > > Invisible, lunatic > > Alan G. > > >
> Or the expression: "The spirit is willing, but the flesh is weak" to: "The wine is good, but the meat is rotten" DaveA From kent37 at tds.net Fri Jul 10 16:11:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Jul 2009 10:11:00 -0400 Subject: [Tutor] thesaurus In-Reply-To: <4A57211C.6030902@ieee.org> References: <4A57211C.6030902@ieee.org> Message-ID: <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> On Fri, Jul 10, 2009 at 7:08 AM, Dave Angel wrote: > Alan Gauld wrote: >> Or the translation program that translated the expression >> >> Out of sight, out of mind >> >> from English to Russian and back with the result: >> >> Invisible, lunatic > Or the expression: > "The spirit is willing, but the flesh is weak" > to: > "The wine is good, but the meat is rotten" These are fun but, according to snopes.com, they are probably urban legend rather than fact: http://www.snopes.com/language/misxlate/machine.asp FWIW translate.google.com correctly translates both of the above from English to Russian and back. I wonder if they have optimized for those phrases? Kent From davea at ieee.org Fri Jul 10 16:43:22 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 10 Jul 2009 10:43:22 -0400 Subject: [Tutor] thesaurus In-Reply-To: <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> Message-ID: <4A57538A.3050708@ieee.org> Kent Johnson wrote: > On Fri, Jul 10, 2009 at 7:08 AM, Dave Angel wrote: > >> Alan Gauld wrote: >> > > >>> Or the translation program that translated the expression >>> >>> Out of sight, out of mind >>> >>> from English to Russian and back with the result: >>> >>> Invisible, lunatic >>> > > >> Or the expression: >> "The spirit is willing, but the flesh is weak" >> to: >> "The wine is good, but the meat is rotten" >> > > These are fun but, according to snopes.com, they are probably urban > legend rather than fact: > http://www.snopes.com/language/misxlate/machine.asp > > FWIW translate.google.com correctly translates both of the above from > English to Russian and back. I wonder if they have optimized for those > phrases? > > Kent > > I first heard the "spirit is willing" one about 30 years ago, from my father when he was studying Russian (written Russian, with the interest in reading technical materials), so I concur with Snopes evaluation. But I don't really care if it was true then or not. It got some people to realize just how complex language automated translation might be. As for present-day Google doing better on those, it's also possible that those idioms have been imported into Russian by now, so that there is a better translation possible. My point is that in some languages, some concepts can't be literally translated, so some idiomatic usage may be needed. I can only think of a lousy example right now, but Chinese apparently has no distinct verb forms for past, present, future. So they rely on other words to indicate which they might mean. And those clues might be far displaced from the verb in question. And I frequently have talked to recent Chinese-American folk, who get the English for this wrong. Until they learn to "think in English" some things are tricky. And meatware is so much more powerful than software in these kinds of things, I'm amazed at how good computer translations have gotten. I remember a computer translation of a camera review, where the English version kept referring to guns. It took a few paragraphs to figure out they were talking about Canon. From amit.pureenergy at gmail.com Fri Jul 10 17:29:50 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Fri, 10 Jul 2009 20:59:50 +0530 Subject: [Tutor] getting image from url Message-ID: Hi , I am trying to get images from url Their is a mail relating to it here : "http://mail.python.org/pipermail/python-list/2001-October/108548.html" but when i followed similar procedure : >>> import urllib >>>fp = urllib.urlopen("http://en.wikipedia.org/wiki/File:Portrait_john_calvin.jpg") >>>img = cStringIO.StringIO(fp.read()) >>> Image.open(img) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1917, in open raise IOError("cannot identify image file") IOError: cannot identify image file what is wrong?? how can I rectify... -- A-M-I-T S|S From angusr at bigfoot.com Fri Jul 10 17:24:22 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Fri, 10 Jul 2009 16:24:22 +0100 Subject: [Tutor] Searching backwards from end of string Message-ID: I'm probably having a bit of an off-day, so please forgive me if this is a really silly question (even for a beginner in Python)! I'm working through the exercises for Chapter 6 of Wesley Chun's book [incidentally, I tried to append another endorsement to the list, but my use of Python rather than "+1" may have looked like a typo or the work of a lunatic, or perhaps my post is just late in appearing - anyway, another happy reader here!], and running again into a difficulty which I "cheated" my way through earlier. On the earlier occasion: "6-6 Strings. Create the equivalent of string.strip(): Take a string and remove all leading and trailing whitespace. (Use of string.*strip() defeats the purpose of this exercise.)" I wrote: from string import whitespace def lstrip(s): if s: for i, c in enumerate(s): if c not in whitespace: break return s[i:] else: return s def rstrip(s): return lstrip(s[::-1])[::-1] # Note: far from maximally efficient (two unnecessary copies!) def strip(s): return lstrip(rstrip(s)) On the present occasion: "6-12 Strings. ... (b) Create another function called rfindchr() that will find the last occurrence of a character in a string. Naturally this works similarly to findchr(), but it starts its search from the end of the input string. ..." I thought I had better err in the opposite direction, so I wrote: def findchr(strng, ch): for i, c in enumerate(strng): if c == ch: return i return -1 def rfindchr(strng, ch): # Surely there's a neater (but still efficient) way? n = len(strng) for i in range(n - 1, -1, -1): if strng[i] == ch: return i return -1 def subchr(strng, origchar, newchar): chars = list(strng) for i, c in enumerate(chars): if c == origchar: chars[i] = newchar return ''.join(chars) I've quoted all my code, in case it's all bad, but it's rfindchr() that I'm particularly worried about. -- Angus Rodgers From emile at fenx.com Fri Jul 10 17:49:04 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 10 Jul 2009 08:49:04 -0700 Subject: [Tutor] getting image from url In-Reply-To: References: Message-ID: On 7/10/2009 8:29 AM Amit Sethi said... > Hi , I am trying to get images from url > > Their is a mail relating to it here : > "http://mail.python.org/pipermail/python-list/2001-October/108548.html" > > but when i followed similar procedure : > >>>> import urllib >>>> fp = urllib.urlopen("http://en.wikipedia.org/wiki/File:Portrait_john_calvin.jpg") >>>> img = cStringIO.StringIO(fp.read()) Right here, try... img.read()[:50] ... and it should become clear what the problem is... HTH, Emile From bermanrl at cfl.rr.com Fri Jul 10 17:57:21 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 10 Jul 2009 11:57:21 -0400 Subject: [Tutor] Searching backwards from end of string In-Reply-To: References: Message-ID: <1247241441.3915.39.camel@bermanrl-desktop> I think you are looking for a complex solution. How about the following example: In [31]: s1='abcdeefghijkl' #find last 'e' In [32]: s2=s1[::-1] #reverses s1 In [33]: j=s2.find('e') #finds first 'e' in reversed string In [36]: ind=len(s1)-j-1 #index into s1 where last occurrence of 'e' is In [37]: ind Out[37]: 5 In [38]: s1[ind] Out[38]: 'e' In [39]: s1 Out[39]: 'abcdeefghijkl' BINGO. Done. Is that not a bit simpler Robert On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote: > I'm probably having a bit of an off-day, so please forgive me if > this is a really silly question (even for a beginner in Python)! > > I'm working through the exercises for Chapter 6 of Wesley Chun's > book [incidentally, I tried to append another endorsement to the > list, but my use of Python rather than "+1" may have looked like > a typo or the work of a lunatic, or perhaps my post is just late > in appearing - anyway, another happy reader here!], and running > again into a difficulty which I "cheated" my way through earlier. > > On the earlier occasion: > > "6-6 Strings. Create the equivalent of string.strip(): Take a > string and remove all leading and trailing whitespace. (Use of > string.*strip() defeats the purpose of this exercise.)" > > I wrote: > > from string import whitespace > > def lstrip(s): > if s: > for i, c in enumerate(s): > if c not in whitespace: > break > return s[i:] > else: > return s > > def rstrip(s): > return lstrip(s[::-1])[::-1] > # Note: far from maximally efficient (two unnecessary copies!) > > def strip(s): > return lstrip(rstrip(s)) > > On the present occasion: > > "6-12 Strings. ... > (b) Create another function called rfindchr() that will find the > last occurrence of a character in a string. Naturally this works > similarly to findchr(), but it starts its search from the end of > the input string. > ..." > > I thought I had better err in the opposite direction, so I wrote: > > def findchr(strng, ch): > for i, c in enumerate(strng): > if c == ch: > return i > return -1 > > def rfindchr(strng, ch): > # Surely there's a neater (but still efficient) way? > n = len(strng) > for i in range(n - 1, -1, -1): > if strng[i] == ch: > return i > return -1 > > def subchr(strng, origchar, newchar): > chars = list(strng) > for i, c in enumerate(chars): > if c == origchar: > chars[i] = newchar > return ''.join(chars) > > I've quoted all my code, in case it's all bad, but it's rfindchr() > that I'm particularly worried about. From amit.pureenergy at gmail.com Fri Jul 10 18:28:26 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Fri, 10 Jul 2009 21:58:26 +0530 Subject: [Tutor] getting image from url In-Reply-To: References: Message-ID: I am sorry, I did not realize the problem was in the location .Ignore the message On Fri, Jul 10, 2009 at 9:19 PM, Emile van Sebille wrote: > On 7/10/2009 8:29 AM Amit Sethi said... >> >> Hi , I am trying to get ?images from url >> >> Their is ?a ?mail relating to it here : >> "http://mail.python.org/pipermail/python-list/2001-October/108548.html" >> >> but when i followed similar procedure : >> >>>>> import urllib >>>>> fp = >>>>> urllib.urlopen("http://en.wikipedia.org/wiki/File:Portrait_john_calvin.jpg") >>>>> img = cStringIO.StringIO(fp.read()) > > Right here, try... > > ? ?img.read()[:50] > > ... and it should become clear what the problem is... > > HTH, > > Emile > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- A-M-I-T S|S From daychilde at gmail.com Fri Jul 10 19:00:11 2009 From: daychilde at gmail.com (daychilde at gmail.com) Date: Fri, 10 Jul 2009 12:00:11 -0500 Subject: [Tutor] os.system and/or subprocess.call problem... Message-ID: <02b001ca017f$e3df3150$ab9d93f0$@com> I'm working on a program that calls another program recursively - this other program reads in ini file and processes it; my program creates a number of slightly different ini files and calls the other program for each one. I can successfully generate the ini file. The problem is that the other program doesn't seem to execute it correctly; or is unable to read its contents. I'm not sure what's going on from the error it's giving me - basically, it says there's nothing to do in the ini, so that's why I think it's either not reading the ini, or perhaps it's being executed as the wrong user or something. (Linux environment) What's really gotten me is that if I take the command that I generate and execute it manually, either on the shell command line, or even in the Python interactive shell, it works. It's only when I call it programmatically that it fails. I've tried a number of different methods, and at this point, I'm a little confused as to which did precisely what. For a while, I was getting a "file is busy" error, which wasn't solved by putting a few seconds' delay . So basically what I'm trying to do is: - Create a subdirectory (./timestamp/indexnumber - e.g. ./2009.07.08-11.55.24.12/1 - this works) - Write a file "bsf.ini" into that directory (this works) - Execute a program called "bluesky" from its directory, passing the ini file along using the appropriate parameter (I'm definitely generating the correct command to do this) An example of the command that works, slightly changed to protect the guilty, would be: /home/isaac/bluesky/bluesky -inifile=/home/isaac/loopy/2009.07.08-11.55.24.12/1/bsf.ini ('loopy' is my program. Not my choice, but it does 'loop' bluesky, so. hey. Heh. I'm *going* loopy, but that's a different problem entirely!) So when I execute the above on the command-line, it works perfectly. But when I do it via an os.system or subproces.call, bluesky basically says "hey, I found nothing to do here". What do you think? Can it be executing bluesky in such a way that it can't open the ini, or perhaps it's executing blueksy as a different user on the system or something? Sincerely, -Isaac Eiland-Hall -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Fri Jul 10 18:46:03 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 10 Jul 2009 11:46:03 -0500 Subject: [Tutor] thesaurus - translation, actually In-Reply-To: References: Message-ID: My favorite rendition of this is in the related field of text-to-speech. In early Object Management Group days, OMG conference proceedings were available as transcripts, but there was substantial delay in getting these out. An attempt to automate this with TTS software of the time was discarded quickly - the first conference had a session track on configuration management, and every mention of "version control" was transcribed as "virgin control" - a dubious prospect in any event. -- Paul From steve at alchemy.com Fri Jul 10 19:04:47 2009 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 10 Jul 2009 10:04:47 -0700 Subject: [Tutor] os.system and/or subprocess.call problem... In-Reply-To: <02b001ca017f$e3df3150$ab9d93f0$@com> References: <02b001ca017f$e3df3150$ab9d93f0$@com> Message-ID: <20090710170447.GA62060@dragon.alchemy.com> On Fri, Jul 10, 2009 at 12:00:11PM -0500, daychilde at gmail.com wrote: > I'm working on a program that calls another program recursively - this other Actually it sounds like you're calling it iteratively, not recursively. > I can successfully generate the ini file. The problem is that the other > program doesn't seem to execute it correctly; or is unable to read its > contents. I'm not sure what's going on from the error it's giving me - >From what you write in here, my first thought is that the ini file isn't being flushed out to disk before the subprocess starts up and tries to read it. Are you either calling .flush() or .close() or something equivalent BEFORE starting the subprocess? When you start the subprocess, is it being started in the directory you think it is? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From bill at celestial.net Fri Jul 10 19:08:45 2009 From: bill at celestial.net (Bill Campbell) Date: Fri, 10 Jul 2009 10:08:45 -0700 Subject: [Tutor] os.system and/or subprocess.call problem... In-Reply-To: <02b001ca017f$e3df3150$ab9d93f0$@com> References: <02b001ca017f$e3df3150$ab9d93f0$@com> Message-ID: <20090710170845.GA11326@ayn.mi.celestial.com> On Fri, Jul 10, 2009, daychilde at gmail.com wrote: >I'm working on a program that calls another program recursively - this other >program reads in ini file and processes it; my program creates a number of >slightly different ini files and calls the other program for each one. > >I can successfully generate the ini file. The problem is that the other >program doesn't seem to execute it correctly; or is unable to read its >contents. I'm not sure what's going on from the error it's giving me - >basically, it says there's nothing to do in the ini, so that's why I think >it's either not reading the ini, or perhaps it's being executed as the wrong >user or something. (Linux environment) Are you closing or flushing the output file before starting the subprocess? Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 Thou shalt not steal, except by majority vote. From daychilde at gmail.com Fri Jul 10 19:24:11 2009 From: daychilde at gmail.com (daychilde at gmail.com) Date: Fri, 10 Jul 2009 12:24:11 -0500 Subject: [Tutor] os.system and/or subprocess.call problem... In-Reply-To: <20090710170447.GA62060@dragon.alchemy.com> References: <02b001ca017f$e3df3150$ab9d93f0$@com> <20090710170447.GA62060@dragon.alchemy.com> Message-ID: <02de01ca0183$3ddda580$b998f080$@com> : Actually it sounds like you're calling it iteratively, not recursively. :blush: Indeed. : From what you write in here, my first thought is that the ini file : isn't being flushed out to disk before the subprocess starts up and : tries to read it. : : Are you either calling .flush() or .close() or something : equivalent BEFORE starting the subprocess? self.filename = 'bsf.ini' self.fullpath = self.thispath + self.filename self.fh = open(self.fullpath, 'w') self.fh.write(self.bsf_ini) self.fh.close Which doesn't show where the vars come from, but I am closing the file first. : When you start the subprocess, is it being started in the directory : you think it is? Well... I know that when I use os.system to create a directory, it starts in cwd, which in this case is /home/isaac/loopy/ -- I create a directory with the timestamp as the name, and successfully write out the bsf.ini files into subfolders underneath it... so I think I'm confident that, at least when I use os.system, it executes in cwd -- but I specific the path to the command, so I think that doesn't matter anyway, e.g.: /home/isaac/bluesky/bluesky --inifile=/home/isaac/loopy/[timestamp]/12/bsf.ini And I know the above is valid otherwise, as I have put in a print statement and copied the actual line I generated and it executed fine... :) Thank you for your reply; I appreciate all help I get on this. :) -Isaac From steve at alchemy.com Fri Jul 10 19:22:17 2009 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 10 Jul 2009 10:22:17 -0700 Subject: [Tutor] os.system and/or subprocess.call problem... In-Reply-To: <02dc01ca0182$fe786600$fb693200$@com> References: <02b001ca017f$e3df3150$ab9d93f0$@com> <20090710170447.GA62060@dragon.alchemy.com> <02dc01ca0182$fe786600$fb693200$@com> Message-ID: <20090710172217.GB62060@dragon.alchemy.com> On Fri, Jul 10, 2009 at 12:22:24PM -0500, daychilde at gmail.com wrote: > self.filename = 'bsf.ini' > self.fullpath = self.thispath + self.filename > self.fh = open(self.fullpath, 'w') > self.fh.write(self.bsf_ini) > self.fh.close > > Which doesn't show where the vars come from, but I am closing the file > first. Actually, no, it doesn't. You forgot the () which are needed to actually _call_ the close method on the last line. self.fh.close is an expression which evaluates to the close method object belonging to the file object self.fh belonging to the object instance in play here. self.fh.close() on the other hand, takes that method and calls it, and evaluates to whatever that method call returns. > : When you start the subprocess, is it being started in the directory > : you think it is? > > Well... I know that when I use os.system to create a directory, it starts in > cwd, which in this case is /home/isaac/loopy/ -- I create a directory with > the timestamp as the name, and successfully write out the bsf.ini files into > subfolders underneath it... so I think I'm confident that, at least when I > use os.system, it executes in cwd -- but I specific the path to the command, > so I think that doesn't matter anyway, e.g.: Ok, that sounds good. > > /home/isaac/bluesky/bluesky > --inifile=/home/isaac/loopy/[timestamp]/12/bsf.ini > > And I know the above is valid otherwise, as I have put in a print statement > and copied the actual line I generated and it executed fine... :) > > Thank you for your reply; I appreciate all help I get on this. :) > -Isaac > -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From emile at fenx.com Fri Jul 10 19:31:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 10 Jul 2009 10:31:27 -0700 Subject: [Tutor] os.system and/or subprocess.call problem... In-Reply-To: <02de01ca0183$3ddda580$b998f080$@com> References: <02b001ca017f$e3df3150$ab9d93f0$@com> <20090710170447.GA62060@dragon.alchemy.com> <02de01ca0183$3ddda580$b998f080$@com> Message-ID: On 7/10/2009 10:24 AM daychilde at gmail.com said... > : Actually it sounds like you're calling it iteratively, not recursively. > > :blush: Indeed. > > : From what you write in here, my first thought is that the ini file > : isn't being flushed out to disk before the subprocess starts up and > : tries to read it. > : > : Are you either calling .flush() or .close() or something > : equivalent BEFORE starting the subprocess? > > self.filename = 'bsf.ini' > self.fullpath = self.thispath + self.filename > self.fh = open(self.fullpath, 'w') > self.fh.write(self.bsf_ini) > self.fh.close > > Which doesn't show where the vars come from, but I am closing the file > first. Are you? If it reads as you've pasted it doesn't. I think you'll want self.fh.close() Emile From daychilde at gmail.com Fri Jul 10 19:42:09 2009 From: daychilde at gmail.com (daychilde at gmail.com) Date: Fri, 10 Jul 2009 12:42:09 -0500 Subject: [Tutor] os.system and/or subprocess.call problem... In-Reply-To: <20090710172217.GB62060@dragon.alchemy.com> References: <02b001ca017f$e3df3150$ab9d93f0$@com> <20090710170447.GA62060@dragon.alchemy.com> <02dc01ca0182$fe786600$fb693200$@com> <20090710172217.GB62060@dragon.alchemy.com> Message-ID: <02f401ca0185$c0df2c90$429d85b0$@com> : > self.fh.close : > : > Which doesn't show where the vars come from, but I am closing the : file : > first. : : Actually, no, it doesn't. You forgot the () which are needed to : actually _call_ the close method on the last line. : : self.fh.close : : is an expression which evaluates to the close method object : belonging to the file object self.fh belonging to the object : instance in play here. : : self.fh.close() : : on the other hand, takes that method and calls it, and evaluates : to whatever that method call returns. I don't know whether to be happy it's a stoopid-newbie mistake or not... :) I am extremely grateful, however, for the help - and I already see one more reply pointing this out, so to Emile as well, and anyone else -- my hearty thanks. Think I'll go curl up in a ball in the corner for a while now. ;-) -Isaac From eduardo.susan at gmail.com Fri Jul 10 20:29:52 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 10 Jul 2009 12:29:52 -0600 Subject: [Tutor] My code to update database Message-ID: <9356b9f30907101129o28bcdef7hccd22526aec7633b@mail.gmail.com> Hello! I have the code below to update a database from a csv file. I have tested one time and it has worked fine, but I'm a bit fearful that it should work right as I am updating a database and don't want to cause troubles into the system. Is this code safe for my personal use? the update code is in a function, but the rest of the code to connect and disconnect is outside the function. I thought this was a good idea because for each line iterated in the csv file, there is a call to the function to update the database with the data from the csv file. So, using the 'global' inside the function is ok, or maybe not? # --- Code starts here --- import csv import dbi import odbc myconn = odbc.odbc('DSN=MKPT01') mycursor = myconn.cursor() def inventory_update(partnumber, quantity, warehouse='00'): """Updates a given part number with the corrected quantity""" global mycursor mycursor.execute("""UPDATE INVENTORY SET ONHAND = ? WHERE CODE = ? AND WHSE = ? """, [quantity, partnumber, warehouse]) if __name__ == "__main__": csvreader = csv.reader(open('Inventory_tracker.csv', 'rb'), dialect = 'excel') for pnumber, qty in csvreader: print "%s has now %s items in stock" % (pnumber, qty) inventory_update(pnumber, qty) mycursor.close() myconn.commit() myconn.close() # --- End --- I'd appreciate your feedback. Eduardo www.expresssignproducts.com From emile at fenx.com Fri Jul 10 20:51:35 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 10 Jul 2009 11:51:35 -0700 Subject: [Tutor] My code to update database In-Reply-To: <9356b9f30907101129o28bcdef7hccd22526aec7633b@mail.gmail.com> References: <9356b9f30907101129o28bcdef7hccd22526aec7633b@mail.gmail.com> Message-ID: On 7/10/2009 11:29 AM Eduardo Vieira said... > Hello! I have the code below to update a database from a csv file. I > have tested one time and it has worked fine, but I'm a bit fearful > that it should work right as I am updating a database and don't want > to cause troubles into the system. > Is this code safe for my personal use? Looks OK to me -- note one small change I'd make (move myconn and mycursor to after __main__ test) , but even that's not critical. > the update code is in a function, but the rest of the code to connect > and disconnect is outside the function. I thought this was a good idea > because for each line iterated in the csv file, there is a call to the > function to update the database with the data from the csv file. So, > using the 'global' inside the function is ok, or maybe not? Looks like you don't need the global at all. Have you tried without it? Emile From angusr at bigfoot.com Fri Jul 10 21:55:09 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Fri, 10 Jul 2009 20:55:09 +0100 Subject: [Tutor] Searching backwards from end of string In-Reply-To: <1247241441.3915.39.camel@bermanrl-desktop> References: <1247241441.3915.39.camel@bermanrl-desktop> Message-ID: On Fri, 10 Jul 2009 11:57:21 -0400, Robert Berman wrote: >I think you are looking for a complex solution. Hardly. >How about the following example: > > >In [31]: s1='abcdeefghijkl' #find last 'e' > >In [32]: s2=s1[::-1] #reverses s1 > >In [33]: j=s2.find('e') #finds first 'e' in reversed string > >In [36]: ind=len(s1)-j-1 #index into s1 where last occurrence of 'e' is > >In [37]: ind >Out[37]: 5 > >In [38]: s1[ind] >Out[38]: 'e' > >In [39]: s1 >Out[39]: 'abcdeefghijkl' BINGO. Done. > >Is that not a bit simpler I did explain (perhaps at too great a length, or with too many irrelevancies): >On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote: >> [...] >> On the earlier occasion: >> [...] >> I wrote: >> [...] >> def rstrip(s): >> return lstrip(s[::-1])[::-1] >> # Note: far from maximally efficient (two unnecessary copies!) >> [...] >> On the present occasion: >> [...] >> I thought I had better err in the opposite direction, so I wrote: >> [...] >> def rfindchr(strng, ch): >> # Surely there's a neater (but still efficient) way? >> n = len(strng) >> for i in range(n - 1, -1, -1): >> if strng[i] == ch: >> return i >> return -1 I don't even think that's "complicated" (just ugly and clumsy). I just wondered if there were some simplifying feature of Python that I had either forgotten or not learned about yet. Python code (even mine!) is usually neater than this. I know efficiency is not always a major concern (and it certainly isn't of any practical importance in a toy example like this), but it seems downright profligate to make a reversed copy of a string just in order to avoid searching it backwards, and to make use of a nifty notation like "[::-1]" - even though my own first instinct is to do exactly that, to save "development time", and to make use of a previous solution. -- Angus Rodgers From eduardo.susan at gmail.com Fri Jul 10 22:03:05 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 10 Jul 2009 14:03:05 -0600 Subject: [Tutor] My code to update database In-Reply-To: References: <9356b9f30907101129o28bcdef7hccd22526aec7633b@mail.gmail.com> Message-ID: <9356b9f30907101303t414c9e28qd67df3155d1ec1f3@mail.gmail.com> On Fri, Jul 10, 2009 at 12:51 PM, Emile van Sebille wrote: > On 7/10/2009 11:29 AM Eduardo Vieira said... >> >> Hello! I have the code below to update a database from a csv file. I >> have tested one time and it has worked fine, but I'm a bit fearful >> that it should work right as I am updating a database and don't want >> to cause troubles into the system. >> Is this code safe for my personal use? > > Looks OK to me -- note one small change I'd make (move myconn and mycursor > to after __main__ test) , but even that's not critical. Well, I thought in the case I needed to import this module then I'd have to put it there, right? > >> the update code is in a function, but the rest of the code to connect >> and disconnect is outside the function. I thought this was a good idea >> because for each line iterated in the csv file, there is a call to the >> function to update the database with the data from the csv file. So, >> using the 'global' inside the function is ok, or maybe not? > > Looks like you don't need the global at all. ?Have you tried without it? > > Oh, yeah, I was getting confuse on that... probably because a another case where I did need to use the 'global' declaration From emile at fenx.com Fri Jul 10 22:36:12 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 10 Jul 2009 13:36:12 -0700 Subject: [Tutor] My code to update database In-Reply-To: <9356b9f30907101303t414c9e28qd67df3155d1ec1f3@mail.gmail.com> References: <9356b9f30907101129o28bcdef7hccd22526aec7633b@mail.gmail.com> <9356b9f30907101303t414c9e28qd67df3155d1ec1f3@mail.gmail.com> Message-ID: On 7/10/2009 1:03 PM Eduardo Vieira said... > On Fri, Jul 10, 2009 at 12:51 PM, Emile van Sebille wrote: >> On 7/10/2009 11:29 AM Eduardo Vieira said... >>> Hello! I have the code below to update a database from a csv file. I >>> have tested one time and it has worked fine, but I'm a bit fearful >>> that it should work right as I am updating a database and don't want >>> to cause troubles into the system. >>> Is this code safe for my personal use? >> Looks OK to me -- note one small change I'd make (move myconn and mycursor >> to after __main__ test) , but even that's not critical. > Well, I thought in the case I needed to import this module then I'd > have to put it there, right? Yes -- but that's the place you're shutting things down at, so it made sense to me to do the setup in the same spot. Certainly if you import the module, you'd not expect the shutdown code to be implemented external to your module, so some restructuring would be needed to convert this to utility status. Emile From bermanrl at cfl.rr.com Fri Jul 10 22:55:12 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Fri, 10 Jul 2009 16:55:12 -0400 Subject: [Tutor] Searching backwards from end of string In-Reply-To: References: <1247241441.3915.39.camel@bermanrl-desktop> Message-ID: <1247259312.3915.56.camel@bermanrl-desktop> On Fri, 2009-07-10 at 20:55 +0100, Angus Rodgers wrote: > On Fri, 10 Jul 2009 11:57:21 -0400, Robert Berman > wrote: > > >I think you are looking for a complex solution. > > Hardly. In my opinion your code w was overly complex for what you were attempting to do. I would not be so presumptuous to tell you that you should change it. I do think you asked for a simple method to solve a specific problem. That is what I offered; nothing else. > >How about the following example: > > > > > >In [31]: s1='abcdeefghijkl' #find last 'e' > > > >In [32]: s2=s1[::-1] #reverses s1 > > > >In [33]: j=s2.find('e') #finds first 'e' in reversed string > > > >In [36]: ind=len(s1)-j-1 #index into s1 where last occurrence of 'e' is > > > >In [37]: ind > >Out[37]: 5 > > > >In [38]: s1[ind] > >Out[38]: 'e' > > > >In [39]: s1 > >Out[39]: 'abcdeefghijkl' BINGO. Done. > > > >Is that not a bit simpler > > I did explain (perhaps at too great a length, or with too many > irrelevancies): > > >On Fri, 2009-07-10 at 16:24 +0100, Angus Rodgers wrote: > >> [...] > >> On the earlier occasion: > >> [...] > >> I wrote: > >> [...] > >> def rstrip(s): > >> return lstrip(s[::-1])[::-1] > >> # Note: far from maximally efficient (two unnecessary copies!) > >> [...] > >> On the present occasion: > >> [...] > >> I thought I had better err in the opposite direction, so I wrote: > >> [...] > >> def rfindchr(strng, ch): > >> # Surely there's a neater (but still efficient) way? > >> n = len(strng) > >> for i in range(n - 1, -1, -1): > >> if strng[i] == ch: > >> return i > >> return -1 > > I don't even think that's "complicated" (just ugly and clumsy). I disagree. For the question asked, the solution is complicated. A nifty 'notation like "[::-1]"' is an example of something called slicing which you will find very well explained in 6.1 of CORE PYTHON PROGRAMMING. I thought that you had reviewed this since it precedes the questions in Chapter 6. It is a very handy tool for not only strings, but lists and dictionaries as well. > > I just wondered if there were some simplifying feature of Python > that I had either forgotten or not learned about yet. Python code > (even mine!) is usually neater than this. > > I know efficiency is not always a major concern (and it certainly > isn't of any practical importance in a toy example like this), > but it seems downright profligate to make a reversed copy of a > string just in order to avoid searching it backwards, and to make > use of a nifty notation like "[::-1]" - even though my own first > instinct is to do exactly that, to save "development time", and > to make use of a previous solution. In any case, whether you choose to incorporate my suggestion or not, I hope you will take some time and experiment with it if only because it's a fun type of solution. Robert From alan.gauld at btinternet.com Sat Jul 11 01:26:20 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 10 Jul 2009 23:26:20 +0000 (GMT) Subject: [Tutor] thesaurus In-Reply-To: <4A57538A.3050708@ieee.org> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> Message-ID: <425199.99164.qm@web86709.mail.ird.yahoo.com> > right now, but Chinese apparently has no distinct verb forms for past, present, > future. So they rely on other words to indicate which they might mean. Chinese also has the problem of relying on intonation to distinguish between identically spelled words. We have the same in English - bow(on stage) v bow (as in arrows), but there are lots of these things in Chinese making translation of written language almost wholly context dependant, and therefore very difficult for a machine. Alan G From angusr at bigfoot.com Sat Jul 11 04:15:46 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sat, 11 Jul 2009 03:15:46 +0100 Subject: [Tutor] Trickier exercise: convert string to complex number Message-ID: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> Wesley Chun, /Core Python Programming/, Ex. 6-13: "[...] An atoc() was never implemented in the string module, so that is your task here. atoc() takes a single string as input, a string representation of a complex number [...] and returns the equivalent complex number object with the given value [...]" (retention: 1 day) (retention: 1 day) (helper functions for user input) The main functions are short enough to post here, I think, but there are many explanatory and apologetic comments in the first file above; also, I would welcome (with a grimace!) any comments as to whether I am developing a cranky or baroque style (as I'm working very much on my own, apart from whatever feedback I can get here), and such misdemeanours are more likely to be noticed in the second (and longer) of the two files above. from string import whitespace def no_spaces(str): return ''.join([ch for ch in str if ch not in whitespace]) def atoc(num): """Convert string representation to complex number.""" num = no_spaces(num) n = len(num) if not n: raise ValueError # Ignore first character for i, ch in enumerate(num[1:]): if ch == 'j': # Must be end of string, else invalid if i != n - 2: raise ValueError return complex(0.0, float(num[:-1])) if ch in '+-' and num[i] not in 'eE': return complex(float(num[:i + 1]), float(num[i + 1:-1])) return complex(float(num), 0.0) -- Angus Rodgers From roadierich at googlemail.com Sat Jul 11 06:19:33 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 11 Jul 2009 05:19:33 +0100 Subject: [Tutor] Trickier exercise: convert string to complex number In-Reply-To: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> References: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> Message-ID: <02A82AC5-85D7-429C-BBDA-0BFEDCBB8724@googlemail.com> On 11 Jul 2009, at 03:15, Angus Rodgers wrote: > Wesley Chun, /Core Python Programming/, Ex. 6-13: > > "[...] An atoc() was never implemented in the string module, so > that is your task here. atoc() takes a single string as input, > a string representation of a complex number [...] and returns > the equivalent complex number object with the given value [...]" > > (retention: 1 day) > (retention: 1 day) > (helper functions for user input) > > The main functions are short enough to post here, I think, but > there are many explanatory and apologetic comments in the first > file above; also, I would welcome (with a grimace!) any comments > as to whether I am developing a cranky or baroque style (as I'm > working very much on my own, apart from whatever feedback I can > get here), and such misdemeanours are more likely to be noticed > in the second (and longer) of the two files above. > > from string import whitespace > > def no_spaces(str): > return ''.join([ch for ch in str if ch not in whitespace]) > > def atoc(num): > """Convert string representation to complex number.""" > num = no_spaces(num) > n = len(num) > if not n: > raise ValueError > # Ignore first character > for i, ch in enumerate(num[1:]): > if ch == 'j': > # Must be end of string, else invalid > if i != n - 2: > raise ValueError > return complex(0.0, float(num[:-1])) > if ch in '+-' and num[i] not in 'eE': > return complex(float(num[:i + 1]), > float(num[i + 1:-1])) > return complex(float(num), 0.0) > > -- > Angus Rodgers > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor This would probably be considered cheating, but there _is_ actually a atoc() (of sorts) in the 2.6 stdlib. It's called ast.literal_eval(). It will take a string representing ANY python literal, and SAFELY return it's value. Why has no one here spoted this before? --- Rich "RoadieRich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. (Sent from my iPod - please allow me a few typos: it's a very small keyboard) -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Sat Jul 11 06:33:58 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 11 Jul 2009 14:33:58 +1000 Subject: [Tutor] Trickier exercise: convert string to complex number In-Reply-To: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> References: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> Message-ID: Angus Rodgers wrote: > Wesley Chun, /Core Python Programming/, Ex. 6-13: > > "[...] An atoc() was never implemented in the string module, so > that is your task here. atoc() takes a single string as input, > a string representation of a complex number [...] and returns > the equivalent complex number object with the given value [...]" It's true that atoc() was never implemented in the string module, but the builtin complex() does the same thing (and more). > (retention: 1 day) > (retention: 1 day) > (helper functions for user input) > > The main functions are short enough to post here, I think, but > there are many explanatory and apologetic comments in the first > file above; also, I would welcome (with a grimace!) any comments > as to whether I am developing a cranky or baroque style (as I'm > working very much on my own, apart from whatever feedback I can > get here), and such misdemeanours are more likely to be noticed > in the second (and longer) of the two files above. > > from string import whitespace > > def no_spaces(str): > return ''.join([ch for ch in str if ch not in whitespace]) > > def atoc(num): > """Convert string representation to complex number.""" > num = no_spaces(num) > n = len(num) > if not n: > raise ValueError > # Ignore first character > for i, ch in enumerate(num[1:]): > if ch == 'j': > # Must be end of string, else invalid > if i != n - 2: > raise ValueError > return complex(0.0, float(num[:-1])) > if ch in '+-' and num[i] not in 'eE': > return complex(float(num[:i + 1]), > float(num[i + 1:-1])) > return complex(float(num), 0.0) > Err... what's the question? Are you asking for style checking or the mentioned "bugs" in the comments? === _const_func = lambda c : (lambda x : c) ... def get_val(typ, prompt=None, valid=_const_func(True)): ... I think that is an over-generalisation. It is much simpler to read def get_val(typ, prompt=None, valid=lambda x: True): because other people reading your code might not know what _const_func do (whether it is simply returning a lambda or it does something more complex). === > # A bug in this program is that, by indiscriminately removing all > # > # whitespace before processing, it fails to catch certain errors, > # > # e.g. " - 1 2 " will be passed to float("-12"). Correcting this > # > # bug is likely to make the program considerably more ... complex. You can avoid that bug by not stripping whitespaces. Ignore them inside the loop (put if ch == '': break) and before passing the number to float, compare the number's length before and after the whitespace is stripped. Not really considerably more complex... === > # (It would seem to be more sensible to learn about the regular > # > # expressions module than to complicate this simplistic program.) With regex, you'll just "simply" need something like: >>> import re >>> pat = r'({s})??(?:({f})({s})?)??({f}j)?$' >>> pat = pat.format(f=r'(?:\d*\.?\d*)', s=r'[+-]') >>> >>> print pat ([+-])??(?:((?:\d*\.?\d*))([+-])?)??((?:\d*\.?\d*)j)?$ >>> >>> tests = ['', '10', '+10', '-10', '10.', '+10.', '-10.', '.4', '+.4', '-.4', '10.4', '+10.4', '-10.4', '10j', '+10j', '-10j', '10.j', '+10.j', '-10.j', '.4j', '+.4j', '-.4j', '10.4j', '+10.4j', '-10.4j', '10+10j', '+10+10j', '-10+10j', '10.+10j', '+10.+10j', '-10.+10j', '10.4+10j', '+10.4+10j', '-10.4+10j', '.4+10j', '+.4+10j', '-.4+10j', '10+10.4j', '10.4+10.4j', '+10.4+10.4j', '+10.4-10.4j'] >>> for t in tests: ... print t, re.match(pat, t).groups() ... (None, None, None, None) 10 (None, '10', None, None) +10 ('+', '10', None, None) -10 ('-', '10', None, None) 10. (None, '10.', None, None) +10. ('+', '10.', None, None) -10. ('-', '10.', None, None) .4 (None, '.4', None, None) +.4 ('+', '.4', None, None) -.4 ('-', '.4', None, None) 10.4 (None, '10.4', None, None) +10.4 ('+', '10.4', None, None) -10.4 ('-', '10.4', None, None) 10j (None, None, None, '10j') +10j (None, '', '+', '10j') -10j (None, '', '-', '10j') 10.j (None, None, None, '10.j') +10.j (None, '', '+', '10.j') -10.j (None, '', '-', '10.j') .4j (None, None, None, '.4j') +.4j (None, '', '+', '.4j') -.4j (None, '', '-', '.4j') 10.4j (None, None, None, '10.4j') +10.4j (None, '', '+', '10.4j') -10.4j (None, '', '-', '10.4j') 10+10j (None, '10', '+', '10j') +10+10j ('+', '10', '+', '10j') -10+10j ('-', '10', '+', '10j') 10.+10j (None, '10.', '+', '10j') +10.+10j ('+', '10.', '+', '10j') -10.+10j ('-', '10.', '+', '10j') 10.4+10j (None, '10.4', '+', '10j') +10.4+10j ('+', '10.4', '+', '10j') -10.4+10j ('-', '10.4', '+', '10j') .4+10j (None, '.4', '+', '10j') +.4+10j ('+', '.4', '+', '10j') -.4+10j ('-', '.4', '+', '10j') 10+10.4j (None, '10', '+', '10.4j') 10.4+10.4j (None, '10.4', '+', '10.4j') +10.4+10.4j ('+', '10.4', '+', '10.4j') +10.4-10.4j ('+', '10.4', '-', '10.4j') >>> >>> # might have just used complex() === From cynicalairrick at gmail.com Sat Jul 11 09:49:21 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Sat, 11 Jul 2009 00:49:21 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <78b3a9580907091353q58182ffbode6d8949b4c903f6@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> <1247099596.3915.10.camel@bermanrl-desktop> <78b3a9580907090054x30f97ff2r963d1af3fa9a596f@mail.gmail.com> <1247144006.9367.1324253579@webmail.messagingengine.com> <78b3a9580907091353q58182ffbode6d8949b4c903f6@mail.gmail.com> Message-ID: <5cd723fd0907110049r92d08abkc69924bb9236fa9f@mail.gmail.com> Mr. Chun, thank you so much for your plug! I had no idea such a prestiged author as yourself would respond to my question, but I'm glad you did! I checked out a copy of your book from my public library (I'll need to purchase a copy eventually though) and the exercises are definitely helping a TON with getting my mind "thinking like a programmer". I'm barely in the excercises section in Part I Chapter 2 and I'm already amazed at your ability to encourage the mind to think! Personally, I'm loving your exercises so much, that they really are motivating me to "expand" on what you asked for. Take the small script where you challenge us to create a "negative, postive, and zero number detecter". I'm enjoying playing around with it by adding exceptions and elif statements here and there. Thank you Mr. Chun, you really answered my question in its entirety. :) Have you written any other books on programming by any chance, or can we expect any in the future? I really love your work! luis, > > no sales pitch here (or at least none intended), but if you ever come > across a copy of "Core Python Programming," i've put lots of exercises > at the end of every chapter. not all of them are full-scale > applications, but it is good practice writing snippets of code that at > some point may be plugged *into* an application at some point. > > best regards, and welcome to Python! > -- wesley > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sat Jul 11 10:02:27 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 11 Jul 2009 01:02:27 -0700 Subject: [Tutor] Python Tutorials: How to create useful programs after learning the syntax? In-Reply-To: <5cd723fd0907110049r92d08abkc69924bb9236fa9f@mail.gmail.com> References: <5cd723fd0907052348x34d4f1a9ta54c4b8f9886ab8@mail.gmail.com> <78b3a9580907081610l7697df4aq56569667ef57c5b4@mail.gmail.com> <1247099596.3915.10.camel@bermanrl-desktop> <78b3a9580907090054x30f97ff2r963d1af3fa9a596f@mail.gmail.com> <1247144006.9367.1324253579@webmail.messagingengine.com> <78b3a9580907091353q58182ffbode6d8949b4c903f6@mail.gmail.com> <5cd723fd0907110049r92d08abkc69924bb9236fa9f@mail.gmail.com> Message-ID: <78b3a9580907110102i3202028fiaecfd203add599d4@mail.gmail.com> luis, thanks for the kind words... i am glad that i am able to help you with developing your Python programming skills. you are indeed "taking it to the next level" by adding more to the problem without me asking you to. i think that's great! i am a software engineer by profession, which doesn't leave me much time to write, although i do enjoy it whenever i'm *not* coding. :-) the best thing i can do as a writer is to meld together the different perspectives as a programmer, a teacher, and writer, and put it all together in a way that's easily digestable for people. i have 2 other books (at the moment), one of which is a DVD version of "Core Python Programming" which is called "Python Fundamentals." it is a DVD containing a PowerPoint presentation with my narration that covers the core part of the book. you can download a free video from it by going to http://corepython.com and clicking on the "Python Fundamentals" link, then choose the sample video link to the left. the other book is called "Python Web Development with Django," a book on which i helped two excellent gentlemen put together a great tutorial to learning how to create web applications using Django. it is a very user-friendly book but has enough useful examples to make that knowledge very useful. at some point, i may work on other books, but for the near future, the only thing on my writing list is thinking about a 3rd edition of Core Python... possibly within the next couple of years. best regards! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com On Sat, Jul 11, 2009 at 12:49 AM, Luis Galvan wrote: > Mr. Chun, thank you so much for your plug!? I had no idea such a prestiged > author as yourself would respond to my question, but I'm glad you did!? I > checked out a copy of your book from my public library (I'll need to > purchase a copy eventually though)? and the exercises are definitely helping > a TON with getting my mind "thinking like a programmer".? I'm barely in the > excercises section in Part I Chapter 2 and I'm already amazed at your > ability to encourage the mind to think!? Personally, I'm loving your > exercises so much, that they really are motivating me to "expand" on what > you asked for.? Take the small script where you challenge us to create a > "negative, postive, and zero number detecter".? I'm enjoying playing around > with it by adding exceptions and elif statements here and there.? Thank you > Mr. Chun, you really answered my question in its entirety. :)? Have you > written any other books on programming by any chance, or can we expect any > in the future?? I really love your work! From angusr at bigfoot.com Sat Jul 11 11:28:51 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sat, 11 Jul 2009 10:28:51 +0100 Subject: [Tutor] Searching backwards from end of string In-Reply-To: <1247259312.3915.56.camel@bermanrl-desktop> References: <1247241441.3915.39.camel@bermanrl-desktop> <1247259312.3915.56.camel@bermanrl-desktop> Message-ID: <4dmg55h185jjcfo7h9ougolhifhs0kbsf3@4ax.com> Robert Berman wrote: >A nifty 'notation like "[::-1]"' is an example of something called >slicing which you will find very well explained in 6.1 of CORE PYTHON >PROGRAMMING. I thought that you had reviewed this since it precedes the >questions in Chapter 6. It is a very handy tool for not only strings, >but lists and dictionaries as well. I'm baffled as to how you could read both of my messages without seeing the bit in the first message where I explained that I had used [::-1] in a previous exercise (and chosen, for good reasons or bad, not to use it in this one), and then the bit in the second message where I repeated this information, carefully and briefly, because you seemed to have missed it the first time! I hope I'm not being rude, but I just don't know what else to say. I can't see that I'm at fault here. If I am, please explain. -- Angus Rodgers From rabidpoobear at gmail.com Sat Jul 11 12:29:28 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Jul 2009 05:29:28 -0500 Subject: [Tutor] Searching backwards from end of string In-Reply-To: <4dmg55h185jjcfo7h9ougolhifhs0kbsf3@4ax.com> References: <1247241441.3915.39.camel@bermanrl-desktop> <1247259312.3915.56.camel@bermanrl-desktop> <4dmg55h185jjcfo7h9ougolhifhs0kbsf3@4ax.com> Message-ID: Angus,I don't think you're at fault but you must keep in mind that a lot of people that read this list get a lot of the same questions repeatedly, only worded slightly differently. I also didn't notice that you used slicing in your first message, and in your second message I just saw that you quoted the first one and my brain triggered its automatic "you've read this section, skip it!" setting and I skipped over it. I didn't see the slicing until I was writing a reply with an alternate way to solve the problem (using slices) when I went back to refer to your original e-mail and I saw that you used slicing as well, and I discarded my reply. I think it's pretty clear that Robert skimmed your message, but that's not an issue either for him or for you. If anything, this is just additional noise that others now have to acknowledge. So I suggest we drop it and pretend Robert didn't even reply. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Jul 11 14:52:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Jul 2009 08:52:54 -0400 Subject: [Tutor] Free webinars: Scientific computing with Python Message-ID: <1c2a2c590907110552k2cbad0fekfa335c99249135f9@mail.gmail.com> Enthought is conducting a series of free webinars on scientific computing with Python. They seem to be oriented to beginners. The next one is about Chaco, the plotting tool. http://blog.enthought.com/?p=125 Kent From angusr at bigfoot.com Sat Jul 11 15:03:08 2009 From: angusr at bigfoot.com (Angus Rodgers) Date: Sat, 11 Jul 2009 14:03:08 +0100 Subject: [Tutor] Trickier exercise: convert string to complex number In-Reply-To: References: Message-ID: <7v1h55lig6l6sj6g85g52ke74id2lsc6q2@4ax.com> >Date: Sat, 11 Jul 2009 14:33:58 +1000 >From: Lie Ryan >Message-ID: > >Err... what's the question? Are you asking for style checking or the >mentioned "bugs" in the comments? Mainly style checking (but more generally anything silly that I'm doing, that might leap to somebody's eye). Any time my coding (or in this case, mainly my commenting!) gets more elaborate (because, in this case, I had to think harder about this exercise than about any of the previous ones), I feel a need for somebody to look over my shoulder, to make sure that I'm not starting to go haywire. I was fairly pleased with the solution (because it would have been easy to have coded something a lot more complicated and confusing) - but also worried that I might have no good reason to be pleased! I worry that I may be developing a silly and overly fussy style. I tend to get obsessed with trivia, and fail to see the wood for the trees. On the other hand, I'm trying to discipline myself to do even small exercises in a way that will scale up to larger ones. I'm trying to keep my idiosyncrasies in check, but there's no substitute for an external check now and then, to ensure that I'm getting the balance at least roughly right. >_const_func = lambda c : (lambda x : c) >... >def get_val(typ, prompt=None, valid=_const_func(True)): > ... > >I think that is an over-generalisation. It is much simpler to read >def get_val(typ, prompt=None, valid=lambda x: True): > >because other people reading your code might not know what _const_func >do (whether it is simply returning a lambda or it does something more >complex). That's a good point, and I'll change this. (Reverting to how it was before! I imagined adding '_const_func' was an improvement.) >> # A bug in this program is that, by indiscriminately removing all >> # >> # whitespace before processing, it fails to catch certain errors, >> # >> # e.g. " - 1 2 " will be passed to float("-12"). Correcting this >> # >> # bug is likely to make the program considerably more ... complex. > >You can avoid that bug by not stripping whitespaces. Ignore them inside >the loop (put if ch == '': break) and before passing the number to >float, compare the number's length before and after the whitespace is >stripped. Not really considerably more complex... D'oh! How true. I haven't coded this exactly as you suggested (no explicit check for internal whitespace, and no length comparison, either), but it seems to be roughly OK (although my testing hasn't been thorough, and I may have introduced new bugs). float() itself strips initial and final whitespace, so my program doesn't have to worry about that. def atoc(num): """Convert string representation to complex number.""" # The algorithm still assumes there is no initial or final # whitespace num = num.strip() n = len(num) if not n: raise ValueError # Ignore first character (now initial whitespace has been # stripped) for i, ch in enumerate(num[1:]): if ch == 'j': # Must be end of string (now final whitespace has been # stripped) if i != n - 2: raise ValueError # Case (ii) return complex(0.0, float(num[:-1])) if ch in '+-' and num[i] not in 'eE': if num[-1] != 'j' or num[-2].isspace(): raise ValueError if ch == '+': # Case (iii) return complex(float(num[:i + 1]), +float(num[i + 2:-1])) if ch == '-': # Case (iv) return complex(float(num[:i + 1]), -float(num[i + 2:-1])) # Case (i) return complex(float(num), 0.0) (I have manually wrapped a few longish lines, just for this post to the mailing list - the longest was 76 characters long. I've also corrected another bug that was in the original program - it didn't check that the final [non-space] character was actually a 'j'.) -- Angus Rodgers From froslie at gmail.com Sat Jul 11 20:15:28 2009 From: froslie at gmail.com (Pete Froslie) Date: Sat, 11 Jul 2009 14:15:28 -0400 Subject: [Tutor] thesaurus In-Reply-To: <425199.99164.qm@web86709.mail.ird.yahoo.com> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> Message-ID: <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> So, I basically have this working so that it pulls a word from a 'txt' file; searches for the synonym in the thesaurus; returns the result... but then I am having trouble with probably the most simple part: I cannot seem to go back into the 'txt' file and replace the word I just searched with the new word! I tried a few methods. One with re.sub, which I can't seem to get to work and one adapting Rich's suggestion in this thread. Rich's suggestion works to a degree-- it replaces all of the words in the 'txt' with the new word. I'm probably missing something obvious, so thought I'd ask before I get too far down the confused road. here is the code I'm tinkering with now (know its a bit messy and will clean it up for a repost when I'm done): from __future__ import with_statement > import re > from urllib2 import urlopen > > word_number = 2 # when incremented-- steps through each word of the text > file. > API_URL = ' > http://words.bighugelabs.com/api/2/e413f24701aa30b8d441ca43a64317be/' > #thesaurus = API_URL + response[word_number] > > fin = open("journey_test.txt", "r") > #really need to make sure I split at all of the delimiters at this point > response = re.split(r"[/|/,\n, , ,:\"\"\.?,)(\-\<>\[\]\r]", fin.read()) > > thesaurus = API_URL + response[word_number] + '/' > print thesaurus # just to test the thesaurus is working > response2 = urlopen(thesaurus) #set the API to search for the current word > response3 = re.split(r"[/|/,\n]", response2.read()) # strip the result > downd to the needed word > > print response3[2] # shows the result of the stripping down to the needed > word > fin.close() > > > #*****HAVING TROUBLE HERE********************** > # > new_word = response3[2] > old_word = response[word_number] > > > buff = [] > with open("journey_test.txt", "r") as fin: > for line in fin: > buff.append(" ".join(new_word for old_word in line.split())) > > with open("journey_test.txt", "w") as fout: > fout.write("\n".join(buff)) > # > #*****HAVING TROUBLE HERE********************** > > """ > #****Different Attempt: I stopped on******************* > combine = response3[2] > combine2 = response[word_number] > > fout = open("journey_test.txt", "r/w") > #data = open("journey_test.txt").read() > #exchange = re.compile('MAKES') > fout.write( re.sub(combine, combine2) ) #trying to replace > fout.close() > #****THIS IS THE AREA OF DIFFICULTY******************* > """ > On Fri, Jul 10, 2009 at 7:26 PM, ALAN GAULD wrote: > > > > > > right now, but Chinese apparently has no distinct verb forms for past, > present, > > future. So they rely on other words to indicate which they might mean. > > > Chinese also has the problem of relying on intonation to distinguish > between > identically spelled words. We have the same in English - bow(on stage) v > bow > (as in arrows), but there are lots of these things in Chinese making > translation > of written language almost wholly context dependant, and therefore very > difficult for a machine. > > Alan G > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Jul 11 20:42:57 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 11 Jul 2009 11:42:57 -0700 Subject: [Tutor] Trickier exercise: convert string to complex number In-Reply-To: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> References: <7prf55l82d1rted8upkv2m9vqla520ilr0@4ax.com> Message-ID: On 7/10/2009 7:15 PM Angus Rodgers said... > and such misdemeanours > from string import whitespace > > def no_spaces(str): Generally, don't shadow builtins (ie, don't use vars with the same names as builtin functions -- str in this case) Emile From alan.gauld at btinternet.com Sat Jul 11 21:38:54 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 11 Jul 2009 19:38:54 +0000 (GMT) Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> Message-ID: <221443.59063.qm@web86703.mail.ird.yahoo.com> > I am having trouble with probably the most simple part: > I cannot seem to go back into the 'txt' file and replace the word I just > searched with the new word! Its not a good idea to try to read and write to the same file at the same time. The normal approach is to weither ead the file into memory and process it then write it back to the file or to open a second file and write to that then copy the second file over the original. > One with re.sub, which I can't seem to get to work re.sub works on a text string it doesn't affect the file. read the content into a string, close the input file. Use re.sub to make the changes (or even just the replace method of strings) then write the changed string back out to the file. HTH, Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From froslie at gmail.com Sat Jul 11 22:04:46 2009 From: froslie at gmail.com (Pete Froslie) Date: Sat, 11 Jul 2009 16:04:46 -0400 Subject: [Tutor] thesaurus In-Reply-To: <221443.59063.qm@web86703.mail.ird.yahoo.com> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> Message-ID: <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> thanks for the advice Alan.. I am wondering about the following: new_word = response3[2] old_word = response[word_number] #this works but adds carriage returns********* for line in fileinput.FileInput("journey_test.txt",inplace=1): line = line.replace(old_word, new_word) print line It seems that if I put it in at the difficulty location it works, but it also adds carriage returns to the entire text file. Basically it ends up double spacing a single-spaced document. I'm also not sure if this is causing the trouble you suggested against (writing and reading at the same time). cheers On Sat, Jul 11, 2009 at 3:38 PM, ALAN GAULD wrote: > > I am having trouble with probably the most simple part: > > I cannot seem to go back into the 'txt' file and replace the word I just > > searched with the new word! > > Its not a good idea to try to read and write to the same file at the same > time. The normal approach is to weither ead the file into memory and > process it then write it back to the file or to open a second file and > write to that then copy the second file over the original. > > > One with re.sub, which I can't seem to get to work > > re.sub works on a text string it doesn't affect the file. > > read the content into a string, close the input file. > Use re.sub to make the changes (or even just the replace > method of strings) then write the changed string back out > to the file. > > HTH, > > Alan G > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Jul 11 23:38:04 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 11 Jul 2009 17:38:04 -0400 Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> Message-ID: <4A59063C.7020102@ieee.org> Pete Froslie wrote: > thanks for the advice Alan.. I am wondering about the following: > > new_word = response3[2] > old_word = response[word_number] > > #this works but adds carriage returns********* > for line in fileinput.FileInput("journey_test.txt",inplace=1): > line = line.replace(old_word, new_word) > print line > > It seems that if I put it in at the difficulty location it works, but it > also adds carriage returns to the entire text file. Basically it ends up > double spacing a single-spaced document. I'm also not sure if this is > causing the trouble you suggested against (writing and reading at the same > time). > > cheers > > On Sat, Jul 11, 2009 at 3:38 PM, ALAN GAULD wrote: > > >>> I am having trouble with probably the most simple part: >>> I cannot seem to go back into the 'txt' file and replace the word I just >>> searched with the new word! >>> >> Its not a good idea to try to read and write to the same file at the same >> time. The normal approach is to weither ead the file into memory and >> process it then write it back to the file or to open a second file and >> write to that then copy the second file over the original. >> >> >>> One with re.sub, which I can't seem to get to work >>> >> re.sub works on a text string it doesn't affect the file. >> >> read the content into a string, close the input file. >> Use re.sub to make the changes (or even just the replace >> method of strings) then write the changed string back out >> to the file. >> >> HTH, >> >> Alan G >> >> fileinput.FileInput() finesses the problem of updating "in place" very nicely. But it also replaces STDOUT, which can make it harder to debug your code, because if you put other print statements there, they'll go to the file, by default. Anyway, here's your answers to the doublespacing: If you put a trailing comma on the print statement, it won't append an extra newline, so you won't end up doublespacing. Or you could rstrip() the 'line' variable, to remove the newline that's there before print. Or you could write to stdout using write() instead of print. I'd like to know if there's a reason you're putting this code all inline. By breaking it into functions, you'd have a chance to work on the different aspects of it independently. That also might mean that you could change different aspects of it independently, or even parameterize it from a command line to do slightly different things. For example, what if you'd like to substitute more than one word for its synomym? Do you really want to pass through the entire file each time? Or what if you want to get your synomyms from somewhere else, or from multiple places? DaveA From froslie at gmail.com Sun Jul 12 00:16:04 2009 From: froslie at gmail.com (Pete Froslie) Date: Sat, 11 Jul 2009 18:16:04 -0400 Subject: [Tutor] thesaurus In-Reply-To: <4A59063C.7020102@ieee.org> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> Message-ID: <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> the trailing comma is getting me much closer right away! -- will read about the other options you suggest (rstrip(); stdout: write()) I clearly have a few other issues I need to sort out now. i guess I've been assuming that print was a good way to trace what is happening rather than thinking about its results in the external file as well.. As for the inline: simply put, I'm an artist trying to learn how to code for my work, so my decisions are not altogether as informed as they could be. Thanks for taking the time to make that suggestion.. I will try to rework it to make use of functions. Then I will address the next set of issues.. This seems the basic form for a function: *def** hello*(): > *print* "Hello World!" > *return* > > I assume each part that can be separated will be done so in this format at the start of the code; consequently, allowing me to call 'hello' later when I need it. Does this also mean that I will be able to call those functions separately later when I import 'thesaurus.py' into a new code also? Pete F On Sat, Jul 11, 2009 at 5:38 PM, Dave Angel wrote: > Pete Froslie wrote: > >> thanks for the advice Alan.. I am wondering about the following: >> >> new_word = response3[2] >> old_word = response[word_number] >> >> #this works but adds carriage returns********* >> for line in fileinput.FileInput("journey_test.txt",inplace=1): >> line = line.replace(old_word, new_word) >> print line >> >> It seems that if I put it in at the difficulty location it works, but it >> also adds carriage returns to the entire text file. Basically it ends up >> double spacing a single-spaced document. I'm also not sure if this is >> causing the trouble you suggested against (writing and reading at the same >> time). >> >> cheers >> >> On Sat, Jul 11, 2009 at 3:38 PM, ALAN GAULD > >wrote: >> >> >> >>> I am having trouble with probably the most simple part: >>>> I cannot seem to go back into the 'txt' file and replace the word I just >>>> searched with the new word! >>>> >>>> >>> Its not a good idea to try to read and write to the same file at the same >>> time. The normal approach is to weither ead the file into memory and >>> process it then write it back to the file or to open a second file and >>> write to that then copy the second file over the original. >>> >>> >>> >>>> One with re.sub, which I can't seem to get to work >>>> >>>> >>> re.sub works on a text string it doesn't affect the file. >>> >>> read the content into a string, close the input file. >>> Use re.sub to make the changes (or even just the replace >>> method of strings) then write the changed string back out >>> to the file. >>> >>> HTH, >>> >>> Alan G >>> >>> >>> >> fileinput.FileInput() finesses the problem of updating "in place" very > nicely. But it also replaces STDOUT, which can make it harder to debug your > code, because if you put other print statements there, they'll go to the > file, by default. Anyway, here's your answers to the doublespacing: > > If you put a trailing comma on the print statement, it won't append an > extra newline, so you won't end up doublespacing. > Or you could rstrip() the 'line' variable, to remove the newline that's > there before print. > Or you could write to stdout using write() instead of print. > > I'd like to know if there's a reason you're putting this code all inline. > By breaking it into functions, you'd have a chance to work on the different > aspects of it independently. That also might mean that you could change > different aspects of it independently, or even parameterize it from a > command line to do slightly different things. > > For example, what if you'd like to substitute more than one word for its > synomym? Do you really want to pass through the entire file each time? Or > what if you want to get your synomyms from somewhere else, or from multiple > places? > > DaveA > > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Jul 12 02:17:53 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 11 Jul 2009 20:17:53 -0400 Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> References: <4A57211C.6030902@ieee.org> <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> Message-ID: <4A592BB1.7000108@ieee.org> Pete Froslie wrote: > the trailing comma is getting me much closer right away! -- will read about > the other options you suggest (rstrip(); stdout: write()) I clearly have a > few other issues I need to sort out now. i guess I've been assuming that > print was a good way to trace what is happening rather than thinking about > its results in the external file as well.. > > As for the inline: simply put, I'm an artist trying to learn how to code for > my work, so my decisions are not altogether as informed as they could be. > Thanks for taking the time to make that suggestion.. I will try to rework it > to make use of functions. Then I will address the next set of issues.. > > This seems the basic form for a function: > > *def** hello*(): > >> *print* "Hello World!" >> *return* >> >> I assume each part that can be separated will be done so in this format at >> > the start of the code; consequently, allowing me to call 'hello' later when > I need it. Does this also mean that I will be able to call those functions > separately later when I import 'thesaurus.py' into a new code also? > > Pete F > > >> That's exactly right, although you probably want to include arguments and return values to really understand how a function would work. Part of the idea of a function is to isolate one set of functionality. That can be for at least three reasons: 1) there's more than one implementation, and you want to be able to easily switch between them. 2) More than one caller might want to use that functionality. 3) it's easier to write, comment, and test a small piece of code with well-defined interfaces, than a whole program. I'm assuming you do this inside a source file, a script. And yes, you can then import the module and reuse much of it from other scripts. There are lots of built-in functions (and methods, which are similar in concept) that you're already using. There, the main advantage to you is that you can re-use something that was written for generality, with the assumption that it's been adequately tested. So the question becomes how do you factor this program into pieces. There are usually several choices, with tradeoffs, and usually the "correct" one depends on how you expect things to change over time. For the present purposes, I think the biggest change might be how you test it. So try this: 1) a function that given a word, produces a synonym. For testing purposes, you can hard-code it with a simple table. That way you're not hammering on that website, maybe exceeding your daily quota for lookups. Also the table will be faster. So you write two of these functions, with identical interfaces, and similar names, and quickly choose between them. 2) a function that reads a file, modifies parts of it (by calling the first function), and writes the file back. Again, you might have multiple versions. For example, the simplest version of it simply prints the results instead of actually writing the file. Or maybe it deliberately writes to a different file. So you can rerun the program without having to separately copy the original version back on top. 3) a test harness of some sort. def synomym1(word): """ return synonym of the word """ table={"dog":"mammal", "person":"human"} if word in table: return table[word] return word def synonym2(name): --- do some stuff with the web lookup --- return result def processfile(filename, lookup): --- loop through file, looking up each word newword = lookup(word) --- write the translated word out, to stdout, or to a new file, or whatever if __name__ == "__main__": processfile("myfile.txt", synonym1) #typically, the filename will come from sys.argv. You might even use argv to decide which of the synonym functions to use. Now when you want to switch to using the website, you just change the last line in the file to use the other function. Note that this is not the organization you used. I'm assuming here that you really want to translate all the words, not just a single word per pass. But hopefully this gives you enough clues to get you going. DaveA From wcyeee at gmail.com Sun Jul 12 04:42:41 2009 From: wcyeee at gmail.com (wcyee) Date: Sat, 11 Jul 2009 22:42:41 -0400 Subject: [Tutor] Why is there no uninstall option for setup.py? Message-ID: Hi, When I am able to find and install a windows package distributed as an exe file, I can just go to "Add & Remove Programs" in the "Control Panel" and uninstall it. But if I have to run "python setup.py install", this is not possible. I'm trying to understand why uninstall has not been provided. After all, setup.py has been available for many years now, right? Is this because no one has contributed a patch or code? Or is there something inherent to python and packages that makes this a hard problem (on non-windows platforms)? It seems really odd that there is no such thing after such a long time. Thanks! From ataulla at gmail.com Sun Jul 12 06:34:02 2009 From: ataulla at gmail.com (Ataulla S H) Date: Sun, 12 Jul 2009 10:04:02 +0530 Subject: [Tutor] Why is there no uninstall option for setup.py? In-Reply-To: References: Message-ID: its a open source.... u need to delete the installed package or rename the package.... y have full flexibility.... On Sun, Jul 12, 2009 at 8:12 AM, wcyee wrote: > Hi, ?When I am able to find and install a windows package distributed > as an exe file, I can just go to "Add & Remove Programs" in the > "Control Panel" and uninstall it. > > But if I have to run "python setup.py install", this is not possible. > I'm trying to understand why uninstall has not been provided. ?After > all, setup.py has been available for many years now, right? > > Is this because no one has contributed a patch or code? ?Or is there > something inherent to python and packages that makes this a hard > problem (on non-windows platforms)? ?It seems really odd that there is > no such thing after such a long time. > > Thanks! > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Ataulla SH web:www.kring.com personal blog:www.ataulla.objectis.net KRING Technologies India Pvt. Ltd. 1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002 From alan.gauld at btinternet.com Sun Jul 12 10:00:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Jul 2009 09:00:05 +0100 Subject: [Tutor] thesaurus References: <4A57211C.6030902@ieee.org><1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com><4A57538A.3050708@ieee.org><425199.99164.qm@web86709.mail.ird.yahoo.com><41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com><221443.59063.qm@web86703.mail.ird.yahoo.com><41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com><4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> Message-ID: "Pete Froslie" wrote > This seems the basic form for a function: > > *def** hello*(): >> *print* "Hello World!" >> *return* That is a very limited form that encourages bad practice. The more general form is: def aFunction(inputValue1, inputValue2,...): # do some processing here return output_value1, outputValue2.... By adding the input and output values we make the function independant of its immediate surroundings and therefore more easily reusable across different programs. We can then call it like: x,y = aFunction(a,b) >> I assume each part that can be separated will be done so in this format >> at > the start of the code; consequently, allowing me to call 'hello' later > when > I need it. Does this also mean that I will be able to call those > functions > separately later when I import 'thesaurus.py' into a new code also? Exactly. The first benefit of functions is in encapsulating parts of your program and providing structure which makles it easier to read but the real power of functions is in making those blocks of code available to other programs too. Read my tutorial topic on Moduules and Functions more information. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eddie9139 at gmail.com Sun Jul 12 09:56:57 2009 From: eddie9139 at gmail.com (Eddie) Date: Sun, 12 Jul 2009 17:56:57 +1000 Subject: [Tutor] String manipulation: Pig latin translator Message-ID: Hi guys, What I have here is more of a logic problem that I can't get my head around than a programming problem. I am trying to program an English to Pig Latin translator. I've got the English to Pig Latin part down and its working great. The part I am having difficulty with is the Pig Latin to English part. Say I have the word ellohay (hello) which I wish to convert into English. The first thing I am doing is removing the added ay at the end and the new word becomes elloh. This is where I have the problem. I have to somehow identify which letters to remove from the end and add back to the front of the word (i.e. h needs to be removed and added back to the front). However with a word such as string which translates as ingstray, when we remove the ay we are left with ingstr, and need to identify that str needs to be removed and added back on the front. I am lost as to how to identify which characters need to be removed to be re-added to the front and can't find a common rule to program by. There are translators out there already like this, so it works somehow, I just need a push in the right direction i think [image: :)] Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Jul 12 14:43:04 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 12 Jul 2009 08:43:04 -0400 Subject: [Tutor] String manipulation: Pig latin translator In-Reply-To: References: Message-ID: <4A59DA58.10304@ieee.org> Eddie wrote: > Hi guys, > > What I have here is more of a logic problem that I can't get my head around > than a programming problem. I am trying to program an English to Pig Latin > translator. I've got the English to Pig Latin part down and its working > great. > > The part I am having difficulty with is the Pig Latin to English part. > Say I have the word ellohay (hello) which I wish to convert into English. > The first thing I am doing is removing the added ay at the end and the new > word becomes elloh. > > This is where I have the problem. I have to somehow identify which letters > to remove from the end and add back to the front of the word (i.e. h needs > to be removed and added back to the front). However with a word such as > string which translates as ingstray, when we remove the ay we are left with > ingstr, and need to identify that str needs to be removed and added back on > the front. > > I am lost as to how to identify which characters need to be removed to be > re-added to the front and can't find a common rule to program by. There are > translators out there already like this, so it works somehow, I just need a > push in the right direction i think [image: :)] > > Thanks > > You can't find an algorithm, because there isn't one. Pig-latin conversion is a non-reversible transformation. I suspect what existing implementations do is to have a dictionary of legal words. Then the algorithm might become: while word ends with consonant, move consonant to beginning if word is in dictionary, break From eike.welk at gmx.net Sun Jul 12 14:52:17 2009 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 12 Jul 2009 14:52:17 +0200 Subject: [Tutor] String manipulation: Pig latin translator In-Reply-To: References: Message-ID: <200907121452.17532.eike.welk@gmx.net> Hello Eddie! On Sunday 12 July 2009, Eddie wrote: > Hi guys, > > What I have here is more of a logic problem that I can't get my > head around than a programming problem. I am trying to program an > English to Pig Latin translator. I've got the English to Pig Latin > part down and its working great. > > The part I am having difficulty with is the Pig Latin to English > part. Say I have the word ellohay (hello) which I wish to convert > into English. The first thing I am doing is removing the added ay > at the end and the new word becomes elloh. > > This is where I have the problem. I have to somehow identify which > letters to remove from the end and add back to the front of the > word (i.e. h needs to be removed and added back to the front). > However with a word such as string which translates as ingstray, > when we remove the ay we are left with ingstr, and need to identify > that str needs to be removed and added back on the front. > > I am lost as to how to identify which characters need to be removed > to be re-added to the front and can't find a common rule to program > by. There are translators out there already like this, so it works > somehow, I just need a push in the right direction i think [image: > :)] > > Thanks I didn't look up the rules for creating Pig Latin. But from looking at your examples: hello --> ellohay, string --> ingstray, I think that information loss occurs in the conversion English --> Pig Latin. This means that the operation can not be reversed with an algorithm that only sees the word in question. The most easy solution IMHO is to download a big English text from the Internet, and translate it to Pig Latin. During the translation you create a big reverse mapping: Pig Latin --> English, which for use in the reverse translator. This method exploits the fact that not each character combination is a valid English word. But there may be collisions: two different English words that have the same Pig Latin translation. It would be interesting to see if such collisions do really occur with English source text. Kind regards, Eike. From emile at fenx.com Sun Jul 12 18:25:07 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 12 Jul 2009 09:25:07 -0700 Subject: [Tutor] String manipulation: Pig latin translator In-Reply-To: <200907121452.17532.eike.welk@gmx.net> References: <200907121452.17532.eike.welk@gmx.net> Message-ID: <4A5A0E63.7090905@fenx.com> On 7/12/2009 5:52 AM Eike Welk said... > This method exploits the fact that not each character combination is a > valid English word. But there may be collisions: two different > English words that have the same Pig Latin translation. stop -- opstay tops -- opstay Emile From emile at fenx.com Sun Jul 12 18:25:07 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 12 Jul 2009 09:25:07 -0700 Subject: [Tutor] String manipulation: Pig latin translator In-Reply-To: <200907121452.17532.eike.welk@gmx.net> References: <200907121452.17532.eike.welk@gmx.net> Message-ID: <4A5A0E63.7090905@fenx.com> On 7/12/2009 5:52 AM Eike Welk said... > This method exploits the fact that not each character combination is a > valid English word. But there may be collisions: two different > English words that have the same Pig Latin translation. stop -- opstay tops -- opstay Emile From rick at niof.net Sun Jul 12 18:09:18 2009 From: rick at niof.net (Rick Pasotto) Date: Sun, 12 Jul 2009 12:09:18 -0400 Subject: [Tutor] segmentation fault Message-ID: <20090712160918.GA22474@niof.net> I've got a script that I wrote several years ago and have been happily using daily. Suddenly when I try to run it I get a segmentation fault. I'm running debian testing so probably some recent update caused the breakage. How can I find out what's gone wrong? -- "Happiness is having a large, loving, caring, close-knit family in another city." -- George Burns Rick Pasotto rick at niof.net http://www.niof.net From emile at fenx.com Sun Jul 12 18:54:26 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 12 Jul 2009 09:54:26 -0700 Subject: [Tutor] segmentation fault In-Reply-To: <20090712160918.GA22474@niof.net> References: <20090712160918.GA22474@niof.net> Message-ID: On 7/12/2009 9:09 AM Rick Pasotto said... > I've got a script that I wrote several years ago and have been happily > using daily. Suddenly when I try to run it I get a segmentation fault. > > I'm running debian testing so probably some recent update caused the > breakage. How can I find out what's gone wrong? > If you're certain it's not otherwise environmental (out of space, bad memory or disk, packet flooding on network, etc), I'd try rolling back recent changes if that's convenient. Sometimes an strace on the process leads me in the right direction. If neither get you started, I'd try littering print statements through the code the track progress and try to narrow down where in the code it's happening. I've sometimes stumbled over a specific line causing the problem, and can eliminate the problem by refactoring. Be sure to report what you find upstream. There are probably other ways to isolate the problem depending on your focus. Maybe someone will point you in those directions. Of course, this is not entirely unexpected when you're running testing. It could resolve itself on its own. Emile From rick at niof.net Sun Jul 12 19:31:45 2009 From: rick at niof.net (Rick Pasotto) Date: Sun, 12 Jul 2009 13:31:45 -0400 Subject: [Tutor] segmentation fault In-Reply-To: References: <20090712160918.GA22474@niof.net> Message-ID: <20090712173145.GB22474@niof.net> On Sun, Jul 12, 2009 at 09:54:26AM -0700, Emile van Sebille wrote: > On 7/12/2009 9:09 AM Rick Pasotto said... >> I've got a script that I wrote several years ago and have been happily >> using daily. Suddenly when I try to run it I get a segmentation fault. >> >> I'm running debian testing so probably some recent update caused the >> breakage. How can I find out what's gone wrong? >> > > If you're certain it's not otherwise environmental (out of space, bad > memory or disk, packet flooding on network, etc), I'd try rolling back > recent changes if that's convenient. Sometimes an strace on the process > leads me in the right direction. If neither get you started, I'd try > littering print statements through the code the track progress and try > to narrow down where in the code it's happening. I've sometimes > stumbled over a specific line causing the problem, and can eliminate the > problem by refactoring. Be sure to report what you find upstream. > > There are probably other ways to isolate the problem depending on your > focus. Maybe someone will point you in those directions. > > Of course, this is not entirely unexpected when you're running testing. > It could resolve itself on its own. I downgraded 2.5.2-1.1 to 2.5.2-1 and all is well. I've sent a reportbug that includes the last several lines of an strace. Thanks for pointing me in the right direction. -- "Upon common theatres, indeed, the applause of the audience is of more importance to the actors than their own approbation. But upon the stage of life, while conscience claps, let the world hiss! On the contrary if conscience disapproves, the loudest applauses of the world are of little value." -- John Adams Rick Pasotto rick at niof.net http://www.niof.net From cfuller084 at thinkingplanet.net Sun Jul 12 19:21:46 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sun, 12 Jul 2009 12:21:46 -0500 Subject: [Tutor] segmentation fault In-Reply-To: <20090712160918.GA22474@niof.net> References: <20090712160918.GA22474@niof.net> Message-ID: <200907121221.47271.cfuller084@thinkingplanet.net> On Sunday 12 July 2009 11:09, Rick Pasotto wrote: > I've got a script that I wrote several years ago and have been happily > using daily. Suddenly when I try to run it I get a segmentation fault. > > I'm running debian testing so probably some recent update caused the > breakage. How can I find out what's gone wrong? Crashing the Python interpreter isn't easy. The most common ways I've seen are errors in C extensions, unpickling, and the ctypes module. You might have some C extensions that need to be recompiled for the new version of Python, or an update to your C extensions that requires a newer version of Python. The usual troubleshooting advice applies. Strategically placed print statements (I actually prefer using UDP sockets for logging), separate your code into blocks and see if you can narrow down where the error is occurring, use a debugger, etc. Depending on the complexity of your code, you might even be able to find out if there's some input somewhere that isn't validated, although this probably isn't the problem in your case. At each step, verify what you think you've learned. If it isn't repeatable, you can't test the fix. But yeah, check for resource exhaustion too. That one can bite you unexpectedly. Cheers From froslie at gmail.com Sun Jul 12 21:01:17 2009 From: froslie at gmail.com (Pete Froslie) Date: Sun, 12 Jul 2009 15:01:17 -0400 Subject: [Tutor] thesaurus In-Reply-To: References: <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> Message-ID: <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> so, I've been playing with the functions a bit-- took a little time to get the hang of them after I started that other mess. Initially, I've done the opposite suggested here by creating functions without the input values. I do see the where it will pay off in re-usability that route.. Alan, I'll read your tutorial on modules and functions. Things that are arising for me now: (1)the use of global variables- seems it would be easier to communicate between functions with 'I/O' values if I understood where the best location for declaration is.. (2)not sure why this function doesn't work: word_count = 0 #set up variable to increment through text def increment(x): > return x+1 > > increment(word_count) > (3) related to strings: Trying a function that will strip unwanted words off of the url before I bounce it off the website. For instance, I don't need to search for a, was, is... This is working, but with strange results-- often it will find an 'a' in the middle of a word and replace it with text and such. using rstrip, but with varying results: #this is the url as a string > http://words.bighugelabs.com/api/2/e413f24701aa30b7d441ca43a64317be/A/ > > thesaurus = string.rstrip(url(),"/A/") + '/' # stripping the end off and > re-adding the '/' > The url function btw: def url(): > fin = open("journey_test.txt", "r") > response = re.split(r"[/|/,\n, , ,:\"\"\.?,)(\-\<>\[\]'\r']", > fin.read()) > thesaurus = API_URL + response[word_number] + '/' #API_URL is > established at the start of the code > return thesaurus > Pete F On Sun, Jul 12, 2009 at 4:00 AM, Alan Gauld wrote: > > "Pete Froslie" wrote > > This seems the basic form for a function: >> >> *def** hello*(): >> >>> *print* "Hello World!" >>> *return* >>> >> > That is a very limited form that encourages bad practice. The more > general form is: > > def aFunction(inputValue1, inputValue2,...): > # do some processing here > return output_value1, outputValue2.... > > By adding the input and output values we make the function > independant of its immediate surroundings and therefore > more easily reusable across different programs. > > We can then call it like: > > x,y = aFunction(a,b) > > I assume each part that can be separated will be done so in this format at >>> >> the start of the code; consequently, allowing me to call 'hello' later >> when >> I need it. Does this also mean that I will be able to call those functions >> separately later when I import 'thesaurus.py' into a new code also? >> > > Exactly. The first benefit of functions is in encapsulating parts of your > program and providing structure which makles it easier to read but > the real power of functions is in making those blocks of code available > to other programs too. > > Read my tutorial topic on Moduules and Functions more information. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sun Jul 12 21:34:21 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 12 Jul 2009 12:34:21 -0700 Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> References: <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> Message-ID: On 7/12/2009 12:01 PM Pete Froslie said... > (2)not sure why this function doesn't work: > > word_count = 0 #set up variable to increment through text > > def increment(x): > return x+1 > > increment(word_count) You need to capture and assign the result (or possibly restructure to work with a mutable or simply use word_count+=1 ): word_count = increment(word_count) Emile From alan.gauld at btinternet.com Mon Jul 13 01:05:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jul 2009 00:05:16 +0100 Subject: [Tutor] segmentation fault References: <20090712160918.GA22474@niof.net> Message-ID: "Rick Pasotto" wrote > using daily. Suddenly when I try to run it I get a segmentation fault. > > I'm running debian testing so probably some recent update caused the > breakage. How can I find out what's gone wrong? Have you got the core file? If so you should be able to use gdb to examine the stack trace or at least the register dump. It should provide a clue as to which function of which process was at fault, and tell you the input parameters at the time of crash. If you have it, you might find adb useful too. But I don't know if Debian Linux has an adb... Alan G From davea at ieee.org Mon Jul 13 01:40:02 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 12 Jul 2009 19:40:02 -0400 Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> References: <1c2a2c590907100711h1eb00649h4b8b29f3336d23d@mail.gmail.com> <4A57538A.3050708@ieee.org> <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> Message-ID: <4A5A7452.3040103@ieee.org> Pete Froslie wrote: > so, I've been playing with the functions a bit-- took a little time to get > the hang of them after I started that other mess. Initially, I've done the > opposite suggested here by creating functions without the input values. I do > see the where it will pay off in re-usability that route.. Alan, I'll read > your tutorial on modules and functions. > > Things that are arising for me now: > > (1)the use of global variables- seems it would be easier to communicate > between functions with 'I/O' values if I understood where the best location > for declaration is.. > > You don't seem to understand functions. Part of the point is to *avoid* global variables. If everything a function uses is passed in as arguments, and if everything it produces is returned as return value(s), it's much easier to see its effect. And to make sure it doesn't have bugs. > (2)not sure why this function doesn't work: > > word_count = 0 #set up variable to increment through text > > def increment(x): > >> return x+1 >> >> increment(word_count) >> >> This function doesn't have any effect on global variables. It returns a value that's one more than its argument. Period. If you wanted to increment word_count using that function, you'd do something like: word_count = increment(word_count) > (3) related to strings: Trying a function that will strip unwanted words off > of the url before I bounce it off the website. For instance, I don't need to > search for a, was, is... This is working, but with strange results-- often > it will find an 'a' in the middle of a word and replace it with text and > such. > > using rstrip, but with varying results: > > #this is the url as a string > >> http://words.bighugelabs.com/api/2/e413f24701aa30b7d441ca43a64317be/A/ >> >> thesaurus = string.rstrip(url(),"/A/") + '/' # stripping the end off and >> re-adding the '/' >> >> > > The url function btw: > > def url(): > >> fin = open("journey_test.txt", "r") >> response = re.split(r"[/|/,\n, , ,:\"\"\.?,)(\-\<>\[\]'\r']", >> fin.read()) >> thesaurus = API_URL + response[word_number] + '/' #API_URL is >> established at the start of the code >> return thesaurus >> >> > > Pete F > > I have no clue what this url() function is trying to do. Nor how you expect to use it. Are you planning to open this file for each word contained in it? DaveA From froslie at gmail.com Mon Jul 13 05:35:40 2009 From: froslie at gmail.com (Pete Froslie) Date: Sun, 12 Jul 2009 23:35:40 -0400 Subject: [Tutor] thesaurus In-Reply-To: <4A5A7452.3040103@ieee.org> References: <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> <4A5A7452.3040103@ieee.org> Message-ID: <41fcacc90907122035u9be4311nacab6ef7e6536a51@mail.gmail.com> > > You don't seem to understand functions. Part of the point is to *avoid* > global variables. If everything a function uses is passed in as arguments, > and if everything it produces is returned as return value(s), it's much > easier to see its effect. And to make sure it doesn't have bugs. True enough- that's why I seek advice. My trouble was with the bit of code I was writing inline; while adapting to the functions I misunderstood their value regarding global variables. I'm happy to say the code is using functions more appropriately now and that, as I learn, it will get closer to something more respectable. I see the advantages for debugging word_count = 0 #set up variable to increment through text > > def increment(x): > >> return x+1 >> increment(word_count) >> >> >> > This function doesn't have any effect on global variables. It returns a > value that's one more than its argument. Period. If you wanted to > increment word_count using that function, you'd do something like: > Thanks-- that makes complete sense; it appears that I just was wrapping my head around functions right away. Initially, I assumed this function could be something quick for any increments. Rather than writing out: 'word_count = word_count + 1' when needed.. I have no clue what this url() function is trying to do. Nor how you expect > to use it. Are you planning to open this file for each word contained in > it? yes. Essentially, it grabs each word from a text file and combines it with the other stuff to create a url string that I send through an API to an online thesaurus. I was attempting to strip it this way as a weak method for cleaning out the words I don't want searched from the text file. Along with the the other functions the code currently scans a text file and replaces each of its words with one of their synonyms.. slightly legible gibberish, but that's what I'm interested in for now. It is a project to help me start learning pyhton as well being intended to take a different form in an artwork I'm working on. thanks. petef On Sun, Jul 12, 2009 at 7:40 PM, Dave Angel wrote: > Pete Froslie wrote: > >> so, I've been playing with the functions a bit-- took a little time to get >> the hang of them after I started that other mess. Initially, I've done the >> opposite suggested here by creating functions without the input values. I >> do >> see the where it will pay off in re-usability that route.. Alan, I'll read >> your tutorial on modules and functions. >> >> Things that are arising for me now: >> >> (1)the use of global variables- seems it would be easier to communicate >> between functions with 'I/O' values if I understood where the best >> location >> for declaration is.. >> >> >> > You don't seem to understand functions. Part of the point is to *avoid* > global variables. If everything a function uses is passed in as arguments, > and if everything it produces is returned as return value(s), it's much > easier to see its effect. And to make sure it doesn't have bugs. > >> (2)not sure why this function doesn't work: >> >> word_count = 0 #set up variable to increment through text >> >> def increment(x): >> >> >>> return x+1 >>> >>> increment(word_count) >>> >>> >>> >> This function doesn't have any effect on global variables. It returns a > value that's one more than its argument. Period. If you wanted to > increment word_count using that function, you'd do something like: > > word_count = increment(word_count) > > (3) related to strings: Trying a function that will strip unwanted words >> off >> of the url before I bounce it off the website. For instance, I don't need >> to >> search for a, was, is... This is working, but with strange results-- often >> it will find an 'a' in the middle of a word and replace it with text and >> such. >> >> using rstrip, but with varying results: >> >> #this is the url as a string >> >> >>> http://words.bighugelabs.com/api/2/e413f24701aa30b7d441ca43a64317be/A/ >>> >>> thesaurus = string.rstrip(url(),"/A/") + '/' # stripping the end off and >>> re-adding the '/' >>> >>> >>> >> >> The url function btw: >> >> def url(): >> >> >>> fin = open("journey_test.txt", "r") >>> response = re.split(r"[/|/,\n, , ,:\"\"\.?,)(\-\<>\[\]'\r']", >>> fin.read()) >>> thesaurus = API_URL + response[word_number] + '/' #API_URL is >>> established at the start of the code >>> return thesaurus >>> >>> >>> >> >> Pete F >> >> >> > > I have no clue what this url() function is trying to do. Nor how you > expect to use it. Are you planning to open this file for each word > contained in it? > > DaveA > -- Pete Froslie 617.314.0957 http://www.froslie.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From pedrooconnell at gmail.com Mon Jul 13 06:33:25 2009 From: pedrooconnell at gmail.com (pedro) Date: Mon, 13 Jul 2009 00:33:25 -0400 Subject: [Tutor] mac os x executable References: <41fcacc90907070951i535a62c4w86a6d8351e99191c@mail.gmail.com> <1247003486.9099.1323969703@webmail.messagingengine.com> <1c2a2c590907071704r5443e65at999da8266c8dfd33@mail.gmail.com> <78b3a9580907071720hd726269oe1372b6b35cbe826@mail.gmail.com> Message-ID: Hi, the way I do this on mac os x is to use applescript like so. --start of applescript tell application "Terminal" do script "python /Volumes/Seagate750/drive_01/myPythonScript.py" end tell --end of applescript Where you simply point the terminal to the python script using applescript. If you save the applescript as an app, you double click it and it runs the python script. Pete PS this is my first post on this board by the way, so hi everyone. From pedrooconnell at gmail.com Mon Jul 13 07:07:46 2009 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Mon, 13 Jul 2009 01:07:46 -0400 Subject: [Tutor] find and replace relative to an nearby search string in a file Message-ID: <8e423ca70907122207o5936b00dv7af8bea521f48b2c@mail.gmail.com> Hi, I am trying to do a find and replace in a text file (a nuke script). Here are a couple excerpts from the file that demonstrate what I want to do. I am always looking for the line " name Write1" as my starting point. In the first example below, I want to replace the path, which is 2 lines above it. I have made a basic script to do that and it works fine. The problem I am having is when the number of lines between " name Write1" and the path above it is not 1, my script breaks. I'm not sure how to say in python "when you find the line " name Write1", go back line by line until you find a line that begins with " file /Volumes/" and then assign a new variable to the path on that line". At the very bottom of this post I have included what I have so far (The script which works but breaks). Any help would be greatly appreciated. Pete Write { file /Volumes/raid0/Z353_002_comp_v27.%04d.cin file_type cin name Write1 xpos 13762 ypos -364 } Write { file /Volumes/raid0/Z353_002_comp_v04.%04d.exr colorspace linear raw true file_type exr name Write1 selected true xpos -487 ypos -155 } # This is the basic script import re theFile = open('/Volumes/raid0/Z353_001_comp_v05.nk',"r") theNukeScriptText = theFile.read() theFile.close() #p = re.compile('.+_comp_v\d\d.%04d.cin\n file_type cin\n name Write1') p = re.compile(r'.+_comp_v\d\d.%04d.cin\n.+\n name Write1') m = p.finditer(theNukeScriptText) the3Lines = p.findall(theNukeScriptText) the3LinesString = ''.join(the3Lines) theOldSeq = the3LinesString.split('\n')[0] print str(the3LinesString.split('\n')[0]) theNewSeq = 'file /Volumes/raid0/Z353_002_comp_v27.%04d.cin' theFile = open('/Volumes/raid0/Z353_001_comp_v05.nk', "w") theFile.write(theNukeScriptText.replace(theOldSeq,theNewSeq)) theFile.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Mon Jul 13 09:00:22 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 13 Jul 2009 09:00:22 +0200 Subject: [Tutor] find and replace relative to an nearby search string in a file In-Reply-To: <8e423ca70907122207o5936b00dv7af8bea521f48b2c@mail.gmail.com> References: <8e423ca70907122207o5936b00dv7af8bea521f48b2c@mail.gmail.com> Message-ID: <4A5ADB86.7080100@tue.nl> Pete O'Connell wrote: > > Write { > file /Volumes/raid0/Z353_002_comp_v27.%04d.cin > file_type cin > name Write1 > xpos 13762 > ypos -364 > } The simplest approach imho is to parse the input with a proper parser, eg PLY or pyparsing. If you want to do the parsing manually, I'd start by classifying each line manually to be one of "Write" "{" "}" and then collect the lines of each group to eg a dict (if there are no duplicate keys, and order is not relevent). In both cases, you'll end up with a list of collected groups. Once you have that, you can do your processing. Finally, convert the groups back to text. Albert From a.t.hofkamp at tue.nl Mon Jul 13 09:38:56 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 13 Jul 2009 09:38:56 +0200 Subject: [Tutor] Why is there no uninstall option for setup.py? In-Reply-To: References: Message-ID: <4A5AE490.4050205@tue.nl> Hai, Welcome to the complexities of package management :) wcyee wrote: > Hi, When I am able to find and install a windows package distributed > as an exe file, I can just go to "Add & Remove Programs" in the > "Control Panel" and uninstall it. That's what I call an OS package manager. My Linux one also handles dependencies (to install A, you first need to install B and C). Don't know whether your package manager does that too. In general, you want exactly one package manager at your system imho. If you have more captains at the ship, they get confused. This is imho the basic reason why I think extending distutils is not good. > But if I have to run "python setup.py install", this is not possible. > I'm trying to understand why uninstall has not been provided. After > all, setup.py has been available for many years now, right? setup.py is an installer, not a package manager. Its only job is to install new packages. It does not take care of dependencies, it does not uninstall. > Is this because no one has contributed a patch or code? Or is there > something inherent to python and packages that makes this a hard > problem (on non-windows platforms)? It seems really odd that there is > no such thing after such a long time. There are other variants around, some of them do dependency handling, I haven't yet seen one that does uninstall too. I believe that extending the Python installer further brings you into the area of package management, something your system already provides at OS level. It is also better positioned there imho. For the sake of argument, let's assume we have a Python package manager. Now for example, if you install PyGTK (Python bindings to the GTK library) from the Python package manager, wouldn't you want it to install GTK too? The latter however is not a Python package, so how do you do that? Installing it from the Python package manager means you have two captains at your ship. If I later tell the OS package manager to install GTK, you'll have two GTK versions around (assuming it doesn't get confused of the gtk files that have appeared out of the blue without telling it about the new files). Alternatively, you can ask the OS package manager to install GTK from the Python package manager. However, the OS manager is then not aware why it is installed. When I browse through the installed packages, it says "GTK is not needed by any installed package", so I may be tempted to remove it. If I do, a) your PyGTK installation fails, and b) your Python package manager gets confused, since nobody told him that the GTK library was removed. If you think this is not bad, think about how to update the GTK library to a new version, in particular when I also install a package that needs the new GTK version with the OS package manager. Good luck. To get around these problems, you either need (imho) to a) have 1 OS package manager that manages everything, or b) have several package manager that understand each other (but that seems like a complicated version of "a" to me, so it may not be viable). Albert From ali.jan at gmail.com Mon Jul 13 10:01:19 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Mon, 13 Jul 2009 14:01:19 +0600 Subject: [Tutor] Pythonify this code! Message-ID: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> Hi, This is my first attempt at python. I tried my hand at steganography for fun. The code includes separate, combine, encode, decode functions. The separate function takes a number and it's base and returns a list containing each digit of the number in a list, vice versa for combine. The encode function encodes each char's ascii value into each pixel's RGB values at the least significant end. The decode function does the opposite. e.g., a = 97, so if we have at a pixel r, g, b (230, 107, 155) it will become (230, 109, 157) when it's encoded. Since I am new and don't speak the python idiom yet, I would like the experts to pythonify the following code as much as possible for both python 2.6 and 3.0. Any other suggestion to improve the quality would also be highly appreciated Thanks a lot! #The code starts here: def separate(num, base): li = [] while num / base > 0: li.insert(0, num % base) num = num / base li.insert(0,num) return li def combine(tup, base): num = 0 mul = pow(base, len(tup) - 1) for i in tup: num = num + i * mul mul = mul / base return num #Will make changes to the original image and not to a copy! You have been warned! import Image def encode(img, text): x = 0 y = 0 height, width = img.size text = text + "~~" if len(text) > height * width: return false pix = img.load() for c in text: li = separate(ord(c), 10) if(len(li) == 1): li.insert(0, 0) li.insert(0, 0) elif(len(li) == 2): li.insert(0, 0) r, g, b = pix[x, y] r = r - (r % 10) + li[0] if (r > 255): r = r - 10 g = g - (g % 10) + li[1] if (g > 255): g = g - 10 b = b - (b % 10) + li[2] if (b > 255): b = b - 10 pix[x,y] = (r,g,b) if y == width - 1: y = 0 x = x + 1 else: y = y + 1 img.save(img.filename) def decode(img): x = 0 y = 0 text = "" c = "" height, width = img.size pix = img.load() while 1: r, g, b = pix[x, y] if (c == '~') and chr(combine([r % 10, g % 10, b % 10], 10)) == '~': return text[:len(text) - 1] c = chr(combineUnits([r % 10, g % 10, b % 10], 10)) text = text + c if y == width - 1: y = 0 x = x + 1 else: y = y + 1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Jul 13 12:15:38 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 13 Jul 2009 05:15:38 -0500 Subject: [Tutor] find and replace relative to an nearby search string In-Reply-To: References: Message-ID: <8C7AA8BB6604454D8A8C947C5D42D444@AWA2> This is a good little pyparsing exercise. Pyparsing makes it easy to define the structure of a "Write { ( )* }" block, and use the names given to the parsed tokens to easily find the "name" and "file" entries. from pyparsing import (Literal, Word, alphanums, empty, restOfLine, dictOf) # make up grammar for expression of a Write block (tiny bit of # pyparsing magic: define value as "empty + restOfLine" instead # of just plain restOfLine, because empty will advance the # parser past any whitespace before starting the capture of # restOfLine) WRITE = Literal("Write") key = Word(alphanums+"_") value = empty + restOfLine write_block = WRITE + "{" + dictOf(key,value)("data") + "}" # SIMPLE VERSION # if the order of the output key-value pairs is not significant, # just modify the "file" entry of tokens.data, and iterate # over tokens.data.items() to create the output def modify_write1(tokens): if tokens.data["name"] == "Write1": tokens.data["file"] = NEW_FILE_VALUE def tokens_as_string(tokens): return ("Write {\n" + "\n".join(" %s %s" % (k,v) for k,v in tokens.data.items()) + "\n" + "}") # SLIGHTLY MORE COMPLICATED VERSION # if the order of the key-value pairs must be preserved, then # you must enumerate through tokens.data's underlying list, # to replace the value associated with "file" def modify_write1(tokens): if tokens.data["name"] == "Write1": for i,(k,v) in enumerate(tokens.data): if k == "file": tokens.data[i][1] = NEW_FILE_VALUE break def tokens_as_string(tokens): return ("Write {\n" + "\n".join(" %s %s" % (k,v) for k,v in tokens.data) + "\n" + "}") # Assign parse actions: for each write_block found, modify the # file entry if name is "Write1", and then reformat the parsed # tokens into a string of the right form (since the parser will # have turned the tokens into a data structure of keys and # values) write_block.setParseAction(modify_write1, tokens_as_string) # define NEW_FILE_VALUE, and use transformString to parse # through the input text, and process every Write block found NEW_FILE_VALUE = "/Volumes/raid0/Z353_002_comp_v27.%04d.cin" print write_block.transformString(text) If you assign your input test string to the variable 'text', you'll get this output: Write { file /Volumes/raid0/Z353_002_comp_v27.%04d.cin file_type cin name Write1 xpos 13762 ypos -364 } Write { file /Volumes/raid0/Z353_002_comp_v27.%04d.cin colorspace linear raw true file_type exr name Write1 selected true xpos -487 ypos -155 } Find out more about pyparsing at http://pyparsing.wikispaces.com. Cheers, -- Paul From alan.gauld at btinternet.com Mon Jul 13 12:17:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jul 2009 11:17:31 +0100 Subject: [Tutor] find and replace relative to an nearby search string in afile References: <8e423ca70907122207o5936b00dv7af8bea521f48b2c@mail.gmail.com> Message-ID: "Pete O'Connell" wrote > I am always looking for the line " name Write1" as my starting point. In > the > first example below, I want to replace the path, which is 2 lines above > it. > I have made a basic script to do that and it works fine. The problem I am > having is when the number of lines between " name Write1" and the path > above > it is not 1, my script breaks. Why not turn the algorithm around and look for the pasth line, then see if a name Write1 line exists in the same block. for each Write block: find path line and store it find name Write1 if exists: update path That way you have no dependency on the number of lines and the only tricky bit is if the path comes after the name Write1 line Or if there is no path line.... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jul 13 12:30:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jul 2009 11:30:43 +0100 Subject: [Tutor] Pythonify this code! References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> Message-ID: "Muhammad Ali" wrote > I tried my hand at steganography Never heard of it before! > #The code starts here: > > def separate(num, base): > li = [] > while num / base > 0: > li.insert(0, num % base) > num = num / base > > li.insert(0,num) > return li > > def combine(tup, base): > num = 0 > mul = pow(base, len(tup) - 1) > for i in tup: > num = num + i * mul > mul = mul / base A general comment is that you can use the operator shortcuts num /= base mul /= base same for the incrementing below. > return num > import Image > > def encode(img, text): > ... > for c in text: > li = separate(ord(c), 10) > ... > > r, g, b = pix[x, y] > > r = r - (r % 10) + li[0] > if (r > 255): > r = r - 10 > > g = g - (g % 10) + li[1] > if (g > 255): > g = g - 10 > > b = b - (b % 10) + li[2] > if (b > 255): > b = b - 10 The 3 sections above are nearly identical, you could create a helper function to do the work. def f(item, aList, index) r = f(r,li,0) g = f(g,li,1) b = f(b,li,2) Just think of a descriptive name for f()! > pix[x,y] = (r,g,b) > > if y == width - 1: > y = 0 > x = x + 1 > else: > y = y + 1 > > img.save(img.filename) > > def decode(img): > x = 0 > y = 0 > text = "" > c = "" > height, width = img.size > pix = img.load() > while 1: While 1 is now deprecated inf favour of while True > r, g, b = pix[x, y] > if (c == '~') and chr(combine([r % 10, g % 10, b % 10], 10)) == > '~': > return text[:len(text) - 1] This could be: return text[:-2] > c = chr(combineUnits([r % 10, g % 10, b % 10], 10)) > text = text + c > > if y == width - 1: > y = 0 > x = x + 1 > else: > y = y + 1 Again, this is repeated code so could go in a helper function. I didn't notice anything that would be v3 specific. Also I can't comment on the algorithm since I don't really know what its doing! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Mon Jul 13 12:38:22 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 13 Jul 2009 05:38:22 -0500 Subject: [Tutor] Pythonify this code! In-Reply-To: References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> Message-ID: > > > > I tried my hand at steganography >> > > Never heard of it before![snip] > > I didn't notice anything that would be v3 specific. Also I can't > comment on the algorithm since I don't really know what its > doing! > Alan, Steganography's really neat! You should look into it. Basically what his code does is takes an image, and it twiddles the least significant bits of each pixel to store a message in it (eg. make tweak each RGB value of each pixel to be either even or odd, and you can encode binary directly in the image!). The image looks practically identical to the original (moreso the less data you encode per pixel) and you can store hidden messages. It's interesting, it's along the same lines as cryptography only it's in the field of "let's hide it so they don't even know there's a message at all!" like those guys who would shave slaves' heads and write messages on them and wait for the hair to grow out. When they were stopped and searched by the enemy, they came out clean, and the guy just has to know to "look under the hair", as it were (or in this case, look at the bits) and they can get the original message. Obviously the main caveat is that you have to use lossless image formats such as PNG or the compression algorithm will destroy your steganography. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhubig at gmail.com Mon Jul 13 12:50:20 2009 From: mhubig at gmail.com (Markus Hubig) Date: Mon, 13 Jul 2009 12:50:20 +0200 Subject: [Tutor] for statement with addition ... Message-ID: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> Hi @all, within diveintopython I often found a for-statement like this: f for f in bla: print f So what actually is the first f for ... is it just to declare f before starting the for loop? I can't find any information on python.org and it's hard to google this kinda stuff. - Markus -- -------------------"it's like this"------ even samurai have teddy bears and even teddy bears get drunk -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Jul 13 13:21:51 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 13 Jul 2009 07:21:51 -0400 Subject: [Tutor] Pythonify this code! In-Reply-To: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> Message-ID: <4A5B18CF.20406@ieee.org> Muhammad Ali wrote: > Hi, > > This is my first attempt at python. I tried my hand at steganography for > fun. The code includes separate, combine, encode, decode functions. The > separate function takes a number and it's base and returns a list containing > each digit of the number in a list, vice versa for combine. The encode > function encodes each char's ascii value into each pixel's RGB values at the > least significant end. The decode function does the opposite. e.g., > > a = 97, so if we have at a pixel r, g, b (230, 107, 155) it will become > (230, 109, 157) when it's encoded. > > Since I am new and don't speak the python idiom yet, I would like the > experts to pythonify the following code as much as possible for both python > 2.6 and 3.0. Any other suggestion to improve the quality would also be > highly appreciated > > Thanks a lot! > > > #The code starts here: > > def separate(num, base): > li = [] > while num / base > 0: > li.insert(0, num % base) > num = num / base > > li.insert(0,num) > return li > > def combine(tup, base): > num = 0 > mul = pow(base, len(tup) - 1) > for i in tup: > num = num + i * mul > mul = mul / base > > return num > > > #Will make changes to the original image and not to a copy! You have been > warned! > import Image > > def encode(img, text): > x = 0 > y = 0 > height, width = img.size > > text = text + "~~" > > if len(text) > height * width: > return false > > pix = img.load() > > for c in text: > li = separate(ord(c), 10) > > if(len(li) == 1): > li.insert(0, 0) > li.insert(0, 0) > elif(len(li) == 2): > li.insert(0, 0) > > r, g, b = pix[x, y] > > r = r - (r % 10) + li[0] > if (r > 255): > r = r - 10 > > g = g - (g % 10) + li[1] > if (g > 255): > g = g - 10 > > b = b - (b % 10) + li[2] > if (b > 255): > b = b - 10 > > pix[x,y] = (r,g,b) > > if y == width - 1: > y = 0 > x = x + 1 > else: > y = y + 1 > > img.save(img.filename) > > def decode(img): > x = 0 > y = 0 > text = "" > c = "" > height, width = img.size > pix = img.load() > while 1: > r, g, b = pix[x, y] > if (c == '~') and chr(combine([r % 10, g % 10, b % 10], 10)) == '~': > return text[:len(text) - 1] > > c = chr(combineUnits([r % 10, g % 10, b % 10], 10)) > text = text + c > > if y == width - 1: > y = 0 > x = x + 1 > else: > y = y + 1 > > Pretty good for your first Python code. Clearly you have some experience in other language(s). Comments follow, no particular order. Import should be at begin of module, unless it's just plain not possible. Functions should have doc-strings, explaining what they do, and what the arguments look like. For example, first two functions wouldn't work with floats, only ints. There also should be comments stating what ranges of values are legal. For example, num is a positive integer, and base is an integer between one and 250 or so. separate() could be simplified and optimized, some depending on the range of expected parameters, but below we'll see that it should be replaced entirely. So don't optimize prematurely. separate() and combine() both naturally want to do the digits in the oppposite order, and nothing else cares. But again, it's premature optimization. Looking at encode(), we see that the only call to separate() is with 10 as a base. And it immediately takes the nicely formatted number, and pads it to 3 digits. Sounds like a standard formatting operation to me, so why not just use the format method with a 3 for width? Then loop over the string, or even use a list comprehension on it. encode() refers to }false", but the built-in value is called "False" encode() uses repetitive code to combine two tuple/lists. Ideal for a separate function, perhaps using zip(). Then we could replace 14 lines with: pix[x, y] =pixel(pix[x, y], li) in encode(), row/column incrementing could be simplified, and common case sped up: y += 1 if y == width: y, x = 0, x+1 Incidentally, aren't you processing the pixels in column-major order? Doesn't matter much for tiny images, but for symmetric designs, it's usually better to keep memory accesses localized, to reduce swapping. I could be all wet here, though, just going on memory. decode() refers to combineUnits() in one of its two calls, but it's actually called combine(). Further, there's no need to call it twice. Better would be to have two "c" variables, maybe calling one of them 'lastc' lastc = c c = chr(combineUnits([r % 10, g % 10, b % 10], 10)) if (c == '~') and lstc == '~': return text[:len(text) - 1] In decode(), while 1 is usually spelled: while True Hope these help. DaveA From rumzster at gmail.com Mon Jul 13 13:22:28 2009 From: rumzster at gmail.com (Rommel Asibal) Date: Mon, 13 Jul 2009 05:22:28 -0600 Subject: [Tutor] for statement with addition ... In-Reply-To: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> References: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> Message-ID: Markus, That looks like a typo. remove it and it should work. On Mon, Jul 13, 2009 at 4:50 AM, Markus Hubig wrote: > Hi @all, > > within diveintopython I often found a for-statement like this: > > f for f in bla: > print f > > So what actually is the first f for ... is it just to declare f before > starting the for loop? I can't find any information on python.org > and it's hard to google this kinda stuff. > > - Markus > > -- > -------------------"it's like this"------ > even samurai have teddy bears > and even teddy bears get drunk > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jul 13 13:37:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Jul 2009 07:37:45 -0400 Subject: [Tutor] for statement with addition ... In-Reply-To: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> References: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> Message-ID: <1c2a2c590907130437y4f19d357r811d0c956b53e085@mail.gmail.com> On Mon, Jul 13, 2009 at 6:50 AM, Markus Hubig wrote: > Hi @all, > > within diveintopython I often found a for-statement like this: > > f for f in bla: > ??? print f > > So what actually is the first f for ... is it just to declare f before > starting the for loop? I can't find any information on python.org > and it's hard to google this kinda stuff. That is not Python, maybe a copy/paste artifact? Omit the initial 'f '. Can you point to an example on the web site or in the printed book? Kent From rumzster at gmail.com Mon Jul 13 13:56:46 2009 From: rumzster at gmail.com (Rommel Asibal) Date: Mon, 13 Jul 2009 05:56:46 -0600 Subject: [Tutor] Xampp & Python Message-ID: Hello All, I am trying to go through the "Python Power!" book and i am at the part where i need to setup a web server. I am thinking of using XAMPP and have checked its site and wanted to try using mod_python. I am using Python 3.1 but from initial looks it seems mod_python doesnt support it, could someone verify if that is correct? Does that mean i have to go to python 2.6 for it to work? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Jul 13 13:57:54 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 13 Jul 2009 07:57:54 -0400 Subject: [Tutor] thesaurus In-Reply-To: <41fcacc90907122035u9be4311nacab6ef7e6536a51@mail.gmail.com> References: <425199.99164.qm@web86709.mail.ird.yahoo.com> <41fcacc90907111115x79077ca6kd13ab98b85b75037@mail.gmail.com> <221443.59063.qm@web86703.mail.ird.yahoo.com> <41fcacc90907111304o294736ct3828ae8535640868@mail.gmail.com> <4A59063C.7020102@ieee.org> <41fcacc90907111516q155c3f88ma4dc8c61daf79717@mail.gmail.com> <41fcacc90907121201y277586caj87b6458376cc4d81@mail.gmail.com> <4A5A7452.3040103@ieee.org> <41fcacc90907122035u9be4311nacab6ef7e6536a51@mail.gmail.com> Message-ID: <4A5B2142.7080206@ieee.org> Pete Froslie wrote: > The url function btw: > > def url(): > > > fin = open("journey_test.txt", "r") > response = re.split(r"[/|/,\n, , ,:\"\"\.?,)(\-\<>\[\]'\r']", > fin.read()) > thesaurus = API_URL + response[word_number] + '/' #API_URL is > established at the start of the code > return thesaurus > > > yes. Essentially, it grabs each word from a text file and combines it with > the other stuff to create a url string that I send through an API to an > online thesaurus. I was attempting to strip it this way as a weak method for > cleaning out the words I don't want searched from the text file. > > Along with the the other functions the code currently scans a text file and > replaces each of its words with one of their synonyms.. slightly legible > gibberish, but that's what I'm interested in for now. It is a project to > help me start learning pyhton as well being intended to take a different > form in an artwork I'm working on. > > thanks. > petef > > BTW, constants like API_URL are fine uses for globals. I can't get my head around this url() function definition, or how it would be called. It appears that your program looks like: Open the file and find out how many words are in it. for each word, Open the file again, parse the whole thing yet again, to figure out the nth word. Then throw away the parsing, plus any information about where in the file the word was found, just keeping a generated URL use the URL to access a website, looking up a replacement word. Re-open the file, parse it till you find something resembling the word involved, then substitute the synonym, and write it back out. So if you have a file with 1000 words in it, you'll open it and parse it 2001 times. And part of your symptoms result from the second parsing trying to replace words that aren't really words. If I were you, I'd simplify the problem, and solve the simplified problem in a pretty way, keeping in mind what the complete problem is. Then expand it incrementally from there. For example, instead of a website, you can build a map of synonyms (see my example earlier). Just a dozen should be fine for testing. Instead of a file with arbitrary text, you could use a simple string of words, without punctuation, capitalization or other complexities. Now, write a set of functions that solve that problem, and gradually add in the complexities of the original problem. And try to do each operation once, both for efficiency and to avoid errors when it's slightly different the two times you might do it. To me that means the final program should have this kind of flow: Open the file, and start parsing. if the next sequence is punctuation and white space, copy it to the output. if the next sequence is a word, extract it, call synonym() on it, and copy that to the output continue till the infile is done Perhaps copy the outfile on top of the infile. See the suggestions for functions I made much earlier in this thread. DaveA From davea at ieee.org Mon Jul 13 14:08:22 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 13 Jul 2009 08:08:22 -0400 Subject: [Tutor] for statement with addition ... In-Reply-To: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> References: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> Message-ID: <4A5B23B6.7030707@ieee.org> Markus Hubig wrote: > Hi @all, > > within diveintopython I often found a for-statement like this: > > f for f in bla: > print f > > So what actually is the first f for ... is it just to declare f before > starting the for loop? I can't find any information on python.org > and it's hard to google this kinda stuff. > > - Markus > > Please give us a reference, as to exactly where you saw that. It gives a syntax error in Python 2.62, as I expected it would. That's not how a for statement works. On the other hand, if you enclose that phrase in square brackets, it makes a list comprehension. mylist = [f for f in bla] A list comprehension builds a new list, where the first pieces says what goes into the list, and the second part describes how to generate it. In this case, if bla is already a list, this just copies the list. But consider mylist = [f*f for f in bla] That builds a new list from the old, where each item is the square of the corresponding old item. List comprehension is something you can look up in the help. Also look up generator expression, which uses similar syntax. DaveA From mhubig at gmail.com Mon Jul 13 15:44:09 2009 From: mhubig at gmail.com (Markus Hubig) Date: Mon, 13 Jul 2009 15:44:09 +0200 Subject: [Tutor] for statement with addition ... In-Reply-To: <4A5B23B6.7030707@ieee.org> References: <1a3190fd0907130350l12ea7161xb09b3ffd6353ac29@mail.gmail.com> <4A5B23B6.7030707@ieee.org> Message-ID: <1a3190fd0907130644n7ac6be52y5e672abdfbbf9088@mail.gmail.com> On Mon, Jul 13, 2009 at 2:08 PM, Dave Angel wrote: > Markus Hubig wrote: > >> Hi @all, >> >> within diveintopython I often found a for-statement like this: >> >> f for f in bla: >> print f >> >> So what actually is the first f for ... is it just to declare f before >> starting the for loop? I can't find any information on python.org >> and it's hard to google this kinda stuff. >> >> - Markus >> >> >> > Please give us a reference, as to exactly where you saw that. It gives a > syntax error in Python 2.62, as I expected it would. That's not how a for > statement works. > > > On the other hand, if you enclose that phrase in square brackets, it makes > a list comprehension. > > mylist = [f for f in bla] > > A list comprehension builds a new list, where the first pieces says what > goes into the list, and the second part describes how to generate it. In > this case, if bla is already a list, this just copies the list. But > consider > mylist = [f*f for f in bla] > > That builds a new list from the old, where each item is the square of the > corresponding old item. > > List comprehension is something you can look up in the help. Also look up > generator expression, which uses similar syntax. > > > DaveA > Yes your right, the examples are enclosed in square brackets ... so this is the explanation I was looking for, thank you. And now I also found the explanation in diveintopython! ;-) - Markus -- -------------------"it's like this"------ even samurai have teddy bears and even teddy bears get drunk -------------- next part -------------- An HTML attachment was scrubbed... URL: From t.scrace at gmail.com Mon Jul 13 16:21:19 2009 From: t.scrace at gmail.com (Thomas Scrace) Date: Mon, 13 Jul 2009 15:21:19 +0100 Subject: [Tutor] Saving class instances In-Reply-To: References: Message-ID: Hi everyone, I am new to Python (and to programming) and, now that I have worked through most of Learning Python, I have set myself the exercise of writing a little text-based program to catalogue the contents of my CD collection. I have written enough code to allow me to create instances of an Album class with attributes like name, artist, year etc. However, I am at a loss as to how to save these instances so that they can be retrieved the next time I run the program. I assume I need to write them to a file somehow, and while I know how to write and read to and from files, I do not know how to write instances. I am sure this has an obvious and easy answer but I just cannot find it anywhere! If anybody could help I would be most grateful. Tom On 13 Jul 2009, at 14:44, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: for statement with addition ... (Rommel Asibal) > 2. Re: for statement with addition ... (Kent Johnson) > 3. Xampp & Python (Rommel Asibal) > 4. Re: thesaurus (Dave Angel) > 5. Re: for statement with addition ... (Dave Angel) > 6. Re: for statement with addition ... (Markus Hubig) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 13 Jul 2009 05:22:28 -0600 > From: Rommel Asibal > To: Markus Hubig > Cc: tutor at python.org > Subject: Re: [Tutor] for statement with addition ... > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Markus, > > That looks like a typo. remove it and it should work. > > On Mon, Jul 13, 2009 at 4:50 AM, Markus Hubig > wrote: > >> Hi @all, >> >> within diveintopython I often found a for-statement like this: >> >> f for f in bla: >> print f >> >> So what actually is the first f for ... is it just to declare f >> before >> starting the for loop? I can't find any information on python.org >> and it's hard to google this kinda stuff. >> >> - Markus >> >> -- >> -------------------"it's like this"------ >> even samurai have teddy bears >> and even teddy bears get drunk >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 2 > Date: Mon, 13 Jul 2009 07:37:45 -0400 > From: Kent Johnson > To: Markus Hubig > Cc: tutor at python.org > Subject: Re: [Tutor] for statement with addition ... > Message-ID: > <1c2a2c590907130437y4f19d357r811d0c956b53e085 at mail.gmail.com> > Content-Type: text/plain; charset=ISO-8859-1 > > On Mon, Jul 13, 2009 at 6:50 AM, Markus Hubig wrote: >> Hi @all, >> >> within diveintopython I often found a for-statement like this: >> >> f for f in bla: >> ??? print f >> >> So what actually is the first f for ... is it just to declare f >> before >> starting the for loop? I can't find any information on python.org >> and it's hard to google this kinda stuff. > > That is not Python, maybe a copy/paste artifact? Omit the initial 'f > '. Can you point to an example on the web site or in the printed book? > > Kent > > > ------------------------------ > > Message: 3 > Date: Mon, 13 Jul 2009 05:56:46 -0600 > From: Rommel Asibal > To: Python Tutor List > Subject: [Tutor] Xampp & Python > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Hello All, > > I am trying to go through the "Python Power!" book and i am at the > part > where i need to setup a web server. I am thinking of using XAMPP > and have > checked its site and wanted to try using mod_python. I am using > Python 3.1 > but from initial looks it seems mod_python doesnt support it, could > someone > verify if that is correct? Does that mean i have to go to python > 2.6 for it > to work? > > > Thanks! > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 4 > Date: Mon, 13 Jul 2009 07:57:54 -0400 > From: Dave Angel > To: Pete Froslie > Cc: Alan Gauld , tutor at python.org, Dave > Angel > Subject: Re: [Tutor] thesaurus > Message-ID: <4A5B2142.7080206 at ieee.org> > Content-Type: text/plain; charset=UTF-8; format=flowed > > Pete Froslie wrote: >> The url function btw: >> >> def url(): >> >> >> fin = open("journey_test.txt", "r") >> response = re.split(r"[/|/,\n, , ,:\"\"\.?,)(\-\<>\[\]'\r']", >> fin.read()) >> thesaurus = API_URL + response[word_number] + '/' #API_URL is >> established at the start of the code >> return thesaurus >> >> >> yes. Essentially, it grabs each word from a text file and combines >> it with >> the other stuff to create a url string that I send through an API >> to an >> online thesaurus. I was attempting to strip it this way as a weak >> method for >> cleaning out the words I don't want searched from the text file. >> >> Along with the the other functions the code currently scans a text >> file and >> replaces each of its words with one of their synonyms.. slightly >> legible >> gibberish, but that's what I'm interested in for now. It is a >> project to >> help me start learning pyhton as well being intended to take a >> different >> form in an artwork I'm working on. >> >> thanks. >> petef >> >> > BTW, constants like API_URL are fine uses for globals. > > I can't get my head around this url() function definition, or how it > would be called. It appears that your program looks like: > > Open the file and find out how many words are in it. > for each word, > Open the file again, parse the whole thing yet again, to figure out > the nth word. Then throw away the parsing, plus any information about > where in the file the word was found, just keeping a generated URL > use the URL to access a website, looking up a replacement word. > Re-open the file, parse it till you find something resembling the > word involved, then substitute the synonym, and write it back out. > > > So if you have a file with 1000 words in it, you'll open it and > parse it > 2001 times. And part of your symptoms result from the second parsing > trying to replace words that aren't really words. > > If I were you, I'd simplify the problem, and solve the simplified > problem in a pretty way, keeping in mind what the complete problem is. > Then expand it incrementally from there. > > For example, instead of a website, you can build a map of synonyms > (see > my example earlier). Just a dozen should be fine for testing. > Instead of a file with arbitrary text, you could use a simple string > of > words, without punctuation, capitalization or other complexities. > > Now, write a set of functions that solve that problem, and gradually > add > in the complexities of the original problem. > > > And try to do each operation once, both for efficiency and to avoid > errors when it's slightly different the two times you might do it. > To > me that means the final program should have this kind of flow: > > Open the file, and start parsing. > if the next sequence is punctuation and white space, copy it to > the output. > if the next sequence is a word, extract it, call synonym() on it, > and copy that to the output > continue till the infile is done > Perhaps copy the outfile on top of the infile. > > See the suggestions for functions I made much earlier in this thread. > > > DaveA > > > ------------------------------ > > Message: 5 > Date: Mon, 13 Jul 2009 08:08:22 -0400 > From: Dave Angel > To: Markus Hubig > Cc: tutor at python.org > Subject: Re: [Tutor] for statement with addition ... > Message-ID: <4A5B23B6.7030707 at ieee.org> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Markus Hubig wrote: >> Hi @all, >> >> within diveintopython I often found a for-statement like this: >> >> f for f in bla: >> print f >> >> So what actually is the first f for ... is it just to declare f >> before >> starting the for loop? I can't find any information on python.org >> and it's hard to google this kinda stuff. >> >> - Markus >> >> > Please give us a reference, as to exactly where you saw that. It > gives > a syntax error in Python 2.62, as I expected it would. That's not > how a > for statement works. > > > On the other hand, if you enclose that phrase in square brackets, it > makes a list comprehension. > > mylist = [f for f in bla] > > A list comprehension builds a new list, where the first pieces says > what > goes into the list, and the second part describes how to generate it. > In this case, if bla is already a list, this just copies the list. > But > consider > mylist = [f*f for f in bla] > > That builds a new list from the old, where each item is the square of > the corresponding old item. > > List comprehension is something you can look up in the help. Also > look > up generator expression, which uses similar syntax. > > > DaveA > > > ------------------------------ > > Message: 6 > Date: Mon, 13 Jul 2009 15:44:09 +0200 > From: Markus Hubig > To: tutor at python.org > Subject: Re: [Tutor] for statement with addition ... > Message-ID: > <1a3190fd0907130644n7ac6be52y5e672abdfbbf9088 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Mon, Jul 13, 2009 at 2:08 PM, Dave Angel wrote: > >> Markus Hubig wrote: >> >>> Hi @all, >>> >>> within diveintopython I often found a for-statement like this: >>> >>> f for f in bla: >>> print f >>> >>> So what actually is the first f for ... is it just to declare f >>> before >>> starting the for loop? I can't find any information on python.org >>> and it's hard to google this kinda stuff. >>> >>> - Markus >>> >>> >>> >> Please give us a reference, as to exactly where you saw that. It >> gives a >> syntax error in Python 2.62, as I expected it would. That's not >> how a for >> statement works. >> >> >> On the other hand, if you enclose that phrase in square brackets, >> it makes >> a list comprehension. >> >> mylist = [f for f in bla] >> >> A list comprehension builds a new list, where the first pieces says >> what >> goes into the list, and the second part describes how to generate >> it. In >> this case, if bla is already a list, this just copies the list. But >> consider >> mylist = [f*f for f in bla] >> >> That builds a new list from the old, where each item is the square >> of the >> corresponding old item. >> >> List comprehension is something you can look up in the help. Also >> look up >> generator expression, which uses similar syntax. >> >> >> DaveA >> > > Yes your right, the examples are enclosed in square brackets ... > so this is the explanation I was looking for, thank you. > And now I also found the explanation in > diveintopython >! > ;-) > > - Markus > > -- > -------------------"it's like this"------ > even samurai have teddy bears > and even teddy bears get drunk > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 65, Issue 56 > ************************************* From wodemoneke at gmail.com Mon Jul 13 18:25:19 2009 From: wodemoneke at gmail.com (Daniel Woodhouse) Date: Mon, 13 Jul 2009 19:25:19 +0300 Subject: [Tutor] Saving class instances In-Reply-To: References: Message-ID: <4c0a037d0907130925l62af4383j843d789c4a1aad30@mail.gmail.com> I think you are better off using a database in this situation, sqlite3 is a good choice since no extra setup is required. See http://docs.python.org/library/sqlite3.html And to answer your question, the python pickle module can save class instances, see http://docs.python.org/library/pickle.html Regards, Daniel Woodhouse On Mon, Jul 13, 2009 at 5:21 PM, Thomas Scrace wrote: > Hi everyone, > > I am new to Python (and to programming) and, now that I have worked through > most of Learning Python, I have set myself the exercise of writing a little > text-based program to catalogue the contents of my CD collection. > > I have written enough code to allow me to create instances of an Album > class with attributes like name, artist, year etc. However, I am at a loss > as to how to save these instances so that they can be retrieved the next > time I run the program. I assume I need to write them to a file somehow, > and while I know how to write and read to and from files, I do not know how > to write instances. > > I am sure this has an obvious and easy answer but I just cannot find it > anywhere! > > If anybody could help I would be most grateful. > > Tom > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jul 13 18:53:02 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 13 Jul 2009 16:53:02 +0000 (GMT) Subject: [Tutor] Pythonify this code! In-Reply-To: References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> Message-ID: <334226.92267.qm@web86711.mail.ird.yahoo.com> Steganography's really neat! You should look into it. > > I did a quick lookup on Wikipedia. > Basically what his code does is takes an image, and it twiddles the least significant bits > > Interestingly when I was at university the head of signal processing was into crypto stuff and was looking for a student to do some work on cryptography based on images. He asked me because I had done some vacation work on DES and RSA but I wasn't really interested (too much heavy math!). > I wonder if this is the kibnd of stuff he was working on... >Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From t.scrace at gmail.com Mon Jul 13 18:59:37 2009 From: t.scrace at gmail.com (Thomas Scrace) Date: Mon, 13 Jul 2009 17:59:37 +0100 Subject: [Tutor] Saving class instances In-Reply-To: References: Message-ID: <6081E5E3-1E09-4327-BB13-F2E853D800BC@gmail.com> I think I will give both approaches a go, since this is just a learning exercise anyway. Thanks very much for your help. Oh, and sorry for accidentally quoting the whole digest last time. Won't happen again! Tom On 13 Jul 2009, at 17:53, tutor-request at python.org wrote: > I think you are better off using a database in this situation, > sqlite3 is a > good choice since no extra setup is required. See > http://docs.python.org/library/sqlite3.html > > And to answer your question, the python pickle module can save class > instances, see http://docs.python.org/library/pickle.html > > > Regards, > Daniel Woodhouse -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jul 13 19:30:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Jul 2009 18:30:32 +0100 Subject: [Tutor] Saving class instances References: Message-ID: "Thomas Scrace" wrote > class with attributes like name, artist, year etc. However, I am at a > loss as to how to save these instances so that they can be retrieved > the next time I run the program. I assume I need to write them to a > file somehow, That's one way and you can find an example and some advice on how to handle subclassing in the OOP topic of my tutor. You can also pickle them or even use shelve for random access retrieval later (see the pickle and shelve module docs) If you have lots of CDs - like thousands! - you might be better off with a database because then you can do sophisticated searches. But OTOH iTunes works pretty well just using a folder structure! :-) > I am sure this has an obvious and easy answer but I just cannot find > it anywhere! Actually no. Saving and retrieving object instances (known as persisting objects in OOP speak) was one of the biggest challenges facing the OOP paradigm when it got started in the real world. Many different solutions have evolved from flat text files to dedicated Object databases, and everyting in between, but it remains a task frought with difficulty, especially on large scale projects. For simpler programs things like Pickle and Shelve are probably the simplest and best solutions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Mon Jul 13 21:49:57 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 13 Jul 2009 15:49:57 -0400 Subject: [Tutor] browser encoding standards? Message-ID: Hi everyone, I just ran into a glitch that got me wondering about the proper encoding to use when outputting data for non-technical folks. I took pains to ensure that I converted a number of XML feeds to UTF-8 prior to storage in a database. And then, when pulling the feed data from a database to generate an HTML file, I once again was careful to write the data to the HTML file using UTF-8. The problem I stumbled into is that when I used UTF-8, several characters showed up as gobbledygook in my Firefox browser. Specifically, the characters "\u201c" and "\u201d" (quote marks) were not carrying over. Some googling revealed that I should change my browser's default character set. I switched form Western ISO to UTF-8, and sure enough, the quote marks appeared correctly. My concern now is that this "solution" is far from obvious. The data is intended to be emailed as an HTML attachment to numerous non-technical folks in my office in America, and they likely have no idea about browser encodings and the ability to change them. So the question -- given my target audience, is there a particular encoding (such as Windows-1252) that would guarantee the file would render properly in the most browsers? Or is it better to always use UTF-8 and let people figure things out for themselves? With the latter, I worry that the file will appear like sloppy work when in fact it's a just a browser setting issue.... Advice is greatly appreciated! Serdar From stefan_ml at behnel.de Mon Jul 13 22:01:50 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 13 Jul 2009 22:01:50 +0200 Subject: [Tutor] browser encoding standards? In-Reply-To: References: Message-ID: Serdar Tumgoren wrote: > I just ran into a glitch that got me wondering about the proper > encoding to use when outputting data for non-technical folks. > > I took pains to ensure that I converted a number of XML feeds to UTF-8 > prior to storage in a database. And then, when pulling the feed data > from a database to generate an HTML file, I once again was careful to > write the data to the HTML file using UTF-8. > > The problem I stumbled into is that when I used UTF-8, several > characters showed up as gobbledygook in my Firefox browser. > Specifically, the characters "\u201c" and "\u201d" (quote marks) were > not carrying over. I guess you forgot to output a tag that defines the content-type of the page. http://www.w3.org/International/O-charset Stefan From zstumgoren at gmail.com Mon Jul 13 22:08:40 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 13 Jul 2009 16:08:40 -0400 Subject: [Tutor] browser encoding standards? In-Reply-To: References: Message-ID: > I guess you forgot to output a tag that defines the content-type of > the page. Aha! Yes indeed. I was just writing out data quick and dirty for testing purposes and forgot to write out the headers. I added Content Header info and all works fine. Thanks! From amit.pureenergy at gmail.com Mon Jul 13 23:04:16 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Tue, 14 Jul 2009 02:34:16 +0530 Subject: [Tutor] gtk.Notebook error Message-ID: Hi , I am having problem with adding pages to gtk.Notebook : What I want is to be able to pass a random container widget to a new tab: thus my code is : class SmNotebook(gtk.Notebook): def __init__(self): gtk.Notebook.__init__(self) #set the tab properties self.set_property('homogeneous', True) #we do not show the tab if there is only one tab i total self.set_property('show-tabs', True) def new_tab(self,widget_to_render,title='Page'): nbpages = self.get_n_pages() self.append_page(widget_to_render) Now while creating I do : def new_tab(widget,widget_render): notebook.new_tab(widget_render) notebook = SmNotebook() box.pack_start(notebook) box2=gtk.VBox() icons = gtk.STOCK_ABOUT image = gtk.Image() image.set_from_stock(icons, gtk.ICON_SIZE_DIALOG) box2.pack_start(image,False) button.connect("clicked", new_tab,box2) * I have deleted the parts of the code that did not seem to be required . The later part of the code is just for testing.. when I do this I get a warning : smnotebook.py:18: GtkWarning: Can't set a parent on widget which has a parent. what am I doing wrong here?? -- A-M-I-T S|S From alan.gauld at btinternet.com Tue Jul 14 01:42:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jul 2009 00:42:46 +0100 Subject: [Tutor] gtk.Notebook error References: Message-ID: "Amit Sethi" wrote > I am having problem with adding pages to gtk.Notebook : I know nothing about Gtk so I could mbe missing something here but.... > Now while creating I do : > > def new_tab(widget,widget_render): > > notebook.new_tab(widget_render) > > notebook = SmNotebook() These 2 lines look suspicious. First you access a method of notebook then you assign a new object to notebook. Is the original object lost? Or is it doing something as a side-effect that keeps it around? It seems to me it would be better to have two separate names for the two objects? > box.pack_start(notebook) This will be the new object used here, I assume thats what you wanted? > box2=gtk.VBox() > icons = gtk.STOCK_ABOUT > image = gtk.Image() > image.set_from_stock(icons, gtk.ICON_SIZE_DIALOG) > box2.pack_start(image,False) > button.connect("clicked", new_tab,box2) > > when I do this I get a warning : smnotebook.py:18: GtkWarning: > Can't set a parent on widget which has a parent. Do you get a full stack trace or just that one lline? It always helps to see the full trace if its there. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jul 14 01:47:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jul 2009 00:47:09 +0100 Subject: [Tutor] browser encoding standards? References: Message-ID: "Serdar Tumgoren" wrote > The problem I stumbled into is that when I used UTF-8, several > characters showed up as gobbledygook in my Firefox browser. > Specifically, the characters "\u201c" and "\u201d" (quote marks) were > not carrying over. Some googling revealed that I should change my > browser's default character set. I switched form Western ISO to UTF-8, > and sure enough, the quote marks appeared correctly. I don't know the answer but I can commiserate because I had the same issue with Firefox on my tutorial. I had edited the raw materials topic uising a web editor and the resultant text then had the quotes showing up as blocks. I re-edited the file in vim and put back "normal" quotes and that seemed to fix it, but given that every other browser seemed happy with it, it was annoying. I'll look forward to the responses from those more familiar with the vagaries of multiple encodings on the web... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jul 14 01:55:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jul 2009 00:55:33 +0100 Subject: [Tutor] browser encoding standards? References: Message-ID: "Serdar Tumgoren" wrote >> I guess you forgot to output a tag that defines the content-type >> of >> the page. > > Aha! Yes indeed. I was just writing out data quick and dirty for > testing purposes and forgot to write out the headers. I added Content > Header info and all works fine. OK, What kind of meta tag should I include? I have a couple, but not very many meta tags in my files. I try to minimalise content and maintain HTML 3.2 compatibility for oldr browsers. What would a content-type meta line look like to get round this quoting problem? My O'Reilly pocket reference suggests: Would that suffice? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Tue Jul 14 02:05:42 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 13 Jul 2009 20:05:42 -0400 Subject: [Tutor] browser encoding standards? In-Reply-To: References: Message-ID: > That's precisely the solution that worked for me, though I should say that I only tested this in Firefox 3 on Ubuntu 9.04. The below blog post circa 2006 suggests that IE at least uses some behind-the-scenes magic to decide on an encoding when the declaration doe not appear in the Content headers. http://www.joelonsoftware.com/articles/Unicode.html But I can't say I know how browsers handle the issue these days. I too would be interested in hearing from others on this topic. Meantime, for anyone else who stumbles into this, below are a few links I've found useful as I try to wrap my brain around Unicode (several have been mentioned on this list previously). http://eric.themoritzfamily.com/2008/11/21/python-encodings-and-unicode/ http://evanjones.ca/python-utf8.html http://wesc.livejournal.com/1743.html http://www.amk.ca/python/howto/unicode http://code.djangoproject.com/browser/django/trunk/django/utils/encoding.py From pedrooconnell at gmail.com Tue Jul 14 07:54:26 2009 From: pedrooconnell at gmail.com (pedro) Date: Tue, 14 Jul 2009 01:54:26 -0400 Subject: [Tutor] find and replace relative to an nearby search string References: <8C7AA8BB6604454D8A8C947C5D42D444@AWA2> Message-ID: Hi and thanks everyone for the enlightenment. I guess pyparsing is the way to go then. I just installed it and am trying it out. It looks good for all the stuff I need to do in Nuke frequently. I am going to do a bit of testing with Paul's solution. Cheers Pete From tmatsumoto at gmx.net Tue Jul 14 08:49:59 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 08:49:59 +0200 Subject: [Tutor] While and for loops Message-ID: <20090714064959.192850@gmx.net> Hello, The other day I was playing with a while loop with a for loop nested inside. Within the for loop I had a condition to break the loop, but when loop ran it never existed the loop. I went back and looked in Programming Python to read about loops and I've got two questions (related to each other). Can you run for loops in while loops and if yes, why did my if condition not break the loop? I read that loops sort of have an order of precedence, does that have anything to do with this problem? while True: for i in items: if i > 10: break else: -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From tmatsumoto at gmx.net Tue Jul 14 08:58:18 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 08:58:18 +0200 Subject: [Tutor] assigning list to keys Message-ID: <20090714065818.29280@gmx.net> Hello, The other day I needed to pack a dictionary, the value of each key was a list. In the code I was packing the list and the dictionary at the same time. First I tried something like this: list = [] dict = {} x = 1 dict['int'] = list.append(x) The result was {'int': None}. Why is the value None? Cheers, T -- Neu: GMX Doppel-FLAT mit Internet-Flatrate + Telefon-Flatrate f?r nur 19,99 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02 From tmatsumoto at gmx.net Tue Jul 14 09:00:26 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 09:00:26 +0200 Subject: [Tutor] While and for loops In-Reply-To: <1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry> References: <20090714064959.192850@gmx.net> <1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry> Message-ID: <20090714070026.192850@gmx.net> Okay, So how would you break out from this situation? T -------- Original-Nachricht -------- > Datum: Tue, 14 Jul 2009 06:57:41 +0000 > Von: sli1que at yahoo.com > An: "Todd Matsumoto" > Betreff: Re: [Tutor] While and for loops > Your break is for the for loop not the while. The condition true never > goes false so your in a infinite loop > Sent from my Verizon Wireless BlackBerry > > -----Original Message----- > From: "Todd Matsumoto" > > Date: Tue, 14 Jul 2009 08:49:59 > To: > Subject: [Tutor] While and for loops > > > Hello, > > The other day I was playing with a while loop with a for loop nested > inside. > > Within the for loop I had a condition to break the loop, but when loop ran > it never existed the loop. I went back and looked in Programming Python to > read about loops and I've got two questions (related to each other). > > Can you run for loops in while loops and if yes, why did my if condition > not break the loop? > > I read that loops sort of have an order of precedence, does that have > anything to do with this problem? > > while True: > > for i in items: > if i > 10: > break > else: > > > > -- > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From wescpy at gmail.com Tue Jul 14 09:05:30 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Jul 2009 00:05:30 -0700 Subject: [Tutor] While and for loops In-Reply-To: <20090714064959.192850@gmx.net> References: <20090714064959.192850@gmx.net> Message-ID: <78b3a9580907140005k474d1debpddbd0827ff0be3f0@mail.gmail.com> > Can you run for loops in while loops and if yes, why did my if condition not break the loop? > > I read that loops sort of have an order of precedence, does that have anything to do with this problem? todd, welcome to Python! you're right in that your questions are related to each other because the answer to both of your questions is the same: you can only break out of the innermost loop (from where you have your break statement). if you need to break out of the outer one, you need another break statement not contained in another loop. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From a.t.hofkamp at tue.nl Tue Jul 14 09:12:42 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 14 Jul 2009 09:12:42 +0200 Subject: [Tutor] While and for loops In-Reply-To: <20090714070026.192850@gmx.net> References: <20090714064959.192850@gmx.net> <1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry> <20090714070026.192850@gmx.net> Message-ID: <4A5C2FEA.4070406@tue.nl> Todd Matsumoto wrote: >> while True: >> >> for i in items: >> if i > 10: >> break >> else: >> >> > Okay, > > So how would you break out from this situation? > finished = False while not finished: for i in items: if i > 10: finished = True # Do not do the next while-iteration break # and break out of the for loop else: From tmatsumoto at gmx.net Tue Jul 14 09:14:07 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 09:14:07 +0200 Subject: [Tutor] While and for loops In-Reply-To: <78b3a9580907140005k474d1debpddbd0827ff0be3f0@mail.gmail.com> References: <20090714064959.192850@gmx.net> <78b3a9580907140005k474d1debpddbd0827ff0be3f0@mail.gmail.com> Message-ID: <20090714071407.29260@gmx.net> Okay, I'm not sure if this is good practice, but I could assign a variable within the while loop, that is assigned something that will then break the outer loop. while True: breakout = True for i in items: if i > 10: breakout = False else: if break is False: break Is the above do-able? Is there a better way? T -------- Original-Nachricht -------- > Datum: Tue, 14 Jul 2009 00:05:30 -0700 > Von: wesley chun > An: Todd Matsumoto > CC: tutor at python.org > Betreff: Re: [Tutor] While and for loops > > Can you run for loops in while loops and if yes, why did my if condition > not break the loop? > > > > I read that loops sort of have an order of precedence, does that have > anything to do with this problem? > > > todd, > > welcome to Python! you're right in that your questions are related to > each other because the answer to both of your questions is the same: > you can only break out of the innermost loop (from where you have your > break statement). if you need to break out of the outer one, you need > another break statement not contained in another loop. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com -- Neu: GMX Doppel-FLAT mit Internet-Flatrate + Telefon-Flatrate f?r nur 19,99 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02 From wescpy at gmail.com Tue Jul 14 09:16:30 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Jul 2009 00:16:30 -0700 Subject: [Tutor] While and for loops In-Reply-To: <4A5C2FEA.4070406@tue.nl> References: <20090714064959.192850@gmx.net> <1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry> <20090714070026.192850@gmx.net> <4A5C2FEA.4070406@tue.nl> Message-ID: <78b3a9580907140016g709715fcu341e728fbace3284@mail.gmail.com> >> So how would you break out from this situation? > > finished = False > while not finished: > ? ? > ? ? for i in items: > ? ? ? ? if i > 10: > ? ? ? ? ? ? finished = True ?# Do not do the next while-iteration > ? ? ? ? ? ? break ? ? ? ? ? ?# and break out of the for loop > ? ? ? ? else: > ? ? ? ? ? ? this solution is workable as well, plus it avoids having 2 break statements in the code. it "breaks" out of the while-loop in a natural way, making its conditional False. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tmatsumoto at gmx.net Tue Jul 14 09:17:26 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 09:17:26 +0200 Subject: [Tutor] While and for loops In-Reply-To: <78b3a9580907140016g709715fcu341e728fbace3284@mail.gmail.com> References: <20090714064959.192850@gmx.net> <1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry> <20090714070026.192850@gmx.net> <4A5C2FEA.4070406@tue.nl> <78b3a9580907140016g709715fcu341e728fbace3284@mail.gmail.com> Message-ID: <20090714071726.29270@gmx.net> Okay, Thanks guys. That explains it. Cheers, T -------- Original-Nachricht -------- > Datum: Tue, 14 Jul 2009 00:16:30 -0700 > Von: wesley chun > An: "A.T.Hofkamp" > CC: Todd Matsumoto , "tutor at python.org" > Betreff: Re: [Tutor] While and for loops > >> So how would you break out from this situation? > > > > finished = False > > while not finished: > > ? ? > > ? ? for i in items: > > ? ? ? ? if i > 10: > > ? ? ? ? ? ? finished = True ?# Do not do the next while-iteration > > ? ? ? ? ? ? break ? ? ? ? ? ?# and break out of the for loop > > ? ? ? ? else: > > ? ? ? ? ? ? > > > this solution is workable as well, plus it avoids having 2 break > statements in the code. it "breaks" out of the while-loop in a natural > way, making its conditional False. > > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Python Web Development with Django", Addison Wesley, (c) 2009 > http://withdjango.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com -- Neu: GMX Doppel-FLAT mit Internet-Flatrate + Telefon-Flatrate f?r nur 19,99 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02 From wescpy at gmail.com Tue Jul 14 09:09:51 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Jul 2009 00:09:51 -0700 Subject: [Tutor] assigning list to keys In-Reply-To: <20090714065818.29280@gmx.net> References: <20090714065818.29280@gmx.net> Message-ID: <78b3a9580907140009w13189d35i9f4a61cf10e8acb7@mail.gmail.com> > The other day I needed to pack a dictionary, the value of each key was a list. In the code I was packing the list and the dictionary at the same time. First I tried something like this: > > list = [] > dict = {} > x = 1 > > dict['int'] = list.append(x) > > The result was {'int': None}. Why is the value None? the reason why the value is None is because the output of the list append() method is None (and will always be None unless they change it). the sole purpose of the append() method is to add an element to the end of a list. in your case, you added the integer 1 to your list named 'list'. that's all it does... 'list' is changed, and no value to return is necessary, hence the reason why Python returns None. if you want the last value you appended in your code, you need to access list[-1]. on another note: you should avoid naming your variables with the same names as data types, i.e., list, str, dict, tuple, int, etc., because you shadow/hide the factory function of the same name. in other words, in your code above, you can no longer access list() nor dict(). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Tue Jul 14 09:12:59 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Jul 2009 00:12:59 -0700 Subject: [Tutor] While and for loops In-Reply-To: <20090714070026.192850@gmx.net> References: <20090714064959.192850@gmx.net> <1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry> <20090714070026.192850@gmx.net> Message-ID: <78b3a9580907140012k27b11394ra63745e6da379c33@mail.gmail.com> > So how would you break out from this situation? as i mentioned in my other msg, you need another break statement that is *not* in another loop. in your case, not in the for-loop. you need a break statement somewhere within your while block (again, that's not in any other loop). IOW, it should be indented at the same level as the for-loop. it's up to you to determine the logic with which you call your break, because if you just put it out there, your while will only run at most once (or less than once). -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Tue Jul 14 09:19:38 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Jul 2009 00:19:38 -0700 Subject: [Tutor] While and for loops In-Reply-To: <20090714071407.29260@gmx.net> References: <20090714064959.192850@gmx.net> <78b3a9580907140005k474d1debpddbd0827ff0be3f0@mail.gmail.com> <20090714071407.29260@gmx.net> Message-ID: <78b3a9580907140019t6488fc1ck2b13a85c333e32a2@mail.gmail.com> > I'm not sure if this is good practice, but I could assign a variable within the while loop, that is assigned something that will then break the outer loop. > > while True: > ? ?breakout = True > ? ? > ? ?for i in items: > ? ? ? ?if i > 10: > ? ? ? ? ? ?breakout = False > ? ? ? ?else: > ? ? ? ? ? ? > ? ?if break is False: > ? ? ? ?break > > Is the above do-able? Is there a better way? this will work (once you fix the typo), but i prefer the previous solution by A.T. since you're trying to do the same thing. my original suggestion would've been to expand on the problem to find a proper case to break out of each individual loop separately, i.e., you have a reason to break out of the inner one, and a different reason for breaking out of the outer one. but in your case, it looks like you're trying to break out of both due to a single reason, and for that, A.T.'s solution is a more elegant way to do what you just did above. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From cwitts at compuscan.co.za Tue Jul 14 09:33:06 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 14 Jul 2009 09:33:06 +0200 Subject: [Tutor] assigning list to keys In-Reply-To: <20090714065818.29280@gmx.net> References: <20090714065818.29280@gmx.net> Message-ID: <4A5C34B2.8020708@compuscan.co.za> Todd Matsumoto wrote: > Hello, > > The other day I needed to pack a dictionary, the value of each key was a list. In the code I was packing the list and the dictionary at the same time. First I tried something like this: > > list = [] > dict = {} > x = 1 > > dict['int'] = list.append(x) > > The result was {'int': None}. Why is the value None? > > Cheers, > > T > Hi, Appending to a list does so in-place and returns None. If you wish to do what you posted you will need to do it in 2 steps with: list.append(x) dict['int'] = list You should also avoid shadowing built-in names like "list", "dict", "file" etc as you can very easily end up with unexplained errors. Hope that helps. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Tue Jul 14 09:44:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jul 2009 08:44:51 +0100 Subject: [Tutor] While and for loops References: <20090714064959.192850@gmx.net><1378541950-1247554529-cardhu_decombobulator_blackberry.rim.net-605532129-@bxe1129.bisx.prod.on.blackberry><20090714070026.192850@gmx.net> <78b3a9580907140012k27b11394ra63745e6da379c33@mail.gmail.com> Message-ID: "wesley chun" wrote > as i mentioned in my other msg, you need another break statement that > is *not* in another loop. in your case, not in the for-loop. you need > a break statement somewhere within your while block (again, that's not > in any other loop). IOW, it should be indented at the same level as > the for-loop. it's up to you to determine the logic with which you > call your break, because if you just put it out there, your while will > only run at most once (or less than once). And for completeness that would probably look like: while True: for i in items: if i > 10: break # out of the for else: if i > 10: break # out of the while under the same conditions But as Wesley said, for this specific case the Found / notFound sentinel approach is nicer. Although there is a school of thought says break statements are only slightly less evil than goto and should be avoided if possible. In that case you can do it by inverting the logic of the tests: i = 0 while i <= 10: for i in items: if i <= 10: But, as usual with purist approaches the result might look neater buts it is far less efficient and less flexible! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From a.t.hofkamp at tue.nl Tue Jul 14 09:45:29 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 14 Jul 2009 09:45:29 +0200 Subject: [Tutor] While and for loops In-Reply-To: <20090714071407.29260@gmx.net> References: <20090714064959.192850@gmx.net> <78b3a9580907140005k474d1debpddbd0827ff0be3f0@mail.gmail.com> <20090714071407.29260@gmx.net> Message-ID: <4A5C3799.3000604@tue.nl> Todd Matsumoto wrote: > Okay, > > I'm not sure if this is good practice, but I could assign a variable within the while loop, that is assigned something that will then break the outer loop. > > while True: > breakout = True > > for i in items: > if i > 10: > breakout = False > else: > > if break is False: > break The statement "if break is False:" is wrong. Your variable is called "breakout" not "break". In fact, you cannot have "break" as variable, the above code will not be accepted by the Python interpreter. There are also a few improvements possible: You want to use "==" for comparing values. The "is" that you use compares objects rather than values. Also, comparing boolean values with True or False in a condition is not needed, you can use the boolean value directly. In this case "not breakout" will give you the same result. Albert From ali.jan at gmail.com Tue Jul 14 10:46:14 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Tue, 14 Jul 2009 14:46:14 +0600 Subject: [Tutor] Pythonify this code! In-Reply-To: <4A5B18CF.20406@ieee.org> References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> <4A5B18CF.20406@ieee.org> Message-ID: <8acb5ef80907140146s49c2878anf7b7fa283ef57522@mail.gmail.com> Hi everyone, Thanks for the comments Dave and Alan! Based on these I have updated the code... I don't know if this is more readable. @Dave: I kept the original separate and combine function with bases as I thought I would move them to a math library if I need to work in other bases, however now I have followed your advice and made them more specific to the solution. I couldn't understand the bit about how to use format. Could you check it out in the context of the new code? Also didn't get the bit about zip() either, however it got me thinking and I used map instead. I am still not very happy about the separateToList function :( and I hope I haven't been overzealous in using map(). I have also changed the text concatenation. Here's the code: import Image ENDTEXT = '~~' def separateToList(num): """ changes an integer into a list with 0's padded to the left if the number is in tens or units """ assert(num <= 255) s = str(num) li = [] if len(s) > 2: li = [s[0:1], s[1:2], s[2:3]] elif len(s) > 1: li = [0, s[0:1], s[1:2]] elif len(s) > 0: li = [0, 0, s[0:1]] return map(int, li) def getCharFromRGB(rgb): """ takes an rgb tuple and changes it to an ascii char by taking the unit digits of each color """ rgb = map(lambda x: x %10, rgb) ordChar = int(''.join(map(str, rgb))) assert(ordChar <= 255) return chr(ordChar) def hidePartOfCharInColor(color, charDigit): """ take a color as integer not exceeding 255 and replace the unit digit with one of the ascii char's digit """ assert(color <= 255) color -= (color % 10) color += charDigit if (color > 255): color -= 10 return color def incrementRowCol(imgWidth, row, col): row += 1 if row == imgWidth: row, col = 0, col+1 return row, col def encode(img, text): """ Takes PIL image and any string, encodes the text in the image, saving the changes to the image Returns False if text size is greater than pixels """ x = 0 y = 0 height, width = img.size text = text + ENDTEXT if len(text) > height * width: return False pix = img.load() for c in text: ordAsList = separateToList(ord(c)) rgb = pix[x, y] pix[x,y] = tuple(map(hidePartOfCharInColor, rgb, ordAsList)) x, y = incrementRowCol(width, x, y) img.save(img.filename) return True def decode(img): x = 0 y = 0 charList = [] c = "" height, width = img.size pix = img.load() while True: lastc = c c = getCharFromRGB(pix[x, y]) charList.append(c) if (c + lastc == ENDTEXT): return ''.join(charList[:-2]) x, y = incrementRowCol(width, x, y) -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Tue Jul 14 11:03:20 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 14 Jul 2009 11:03:20 +0200 Subject: [Tutor] Pythonify this code! In-Reply-To: <8acb5ef80907140146s49c2878anf7b7fa283ef57522@mail.gmail.com> References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> <4A5B18CF.20406@ieee.org> <8acb5ef80907140146s49c2878anf7b7fa283ef57522@mail.gmail.com> Message-ID: <4A5C49D8.7070008@tue.nl> Muhammad Ali wrote: > def separateToList(num): > """ > changes an integer into a list with 0's padded to the left if the number is in tens or units > """ > assert(num <= 255) > s = str(num) > li = [] > if len(s) > 2: > li = [s[0:1], s[1:2], s[2:3]] > elif len(s) > 1: > li = [0, s[0:1], s[1:2]] > elif len(s) > 0: > li = [0, 0, s[0:1]] > > return map(int, li) return [int(v) for v in ("00" + str(num))[-3:]] Albert From t.scrace at gmail.com Tue Jul 14 12:36:02 2009 From: t.scrace at gmail.com (Thomas Scrace) Date: Tue, 14 Jul 2009 11:36:02 +0100 Subject: [Tutor] Saving class instances In-Reply-To: References: Message-ID: <158478C6-08DE-48CE-97EA-3508F10EDDDE@gmail.com> On 13 Jul 2009, at 22:04, "Alan Gauld" wrote: > That's one way and you can find an example and some advice > on how to handle subclassing in the OOP topic of my tutor. > Wow; thanks! That tutorial was really useful, I will have to check out the rest of the site now. >> I am sure this has an obvious and easy answer but I just cannot find >> it anywhere! > > Actually no. Saving and retrieving object instances (known as > persisting objects in OOP speak) was one of the biggest challenges > facing the OOP paradigm when it got started in the real world. Many > different solutions have evolved from flat text files to dedicated > Object > databases, and everyting in between, but it remains a task frought > with difficulty, especially on large scale projects. > Good to know I wasn't being totally dense. Now that I have got the pickle thing under my belt I am going to have a go at sqllite. Thanks again everybody. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Jul 14 12:54:30 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 14 Jul 2009 06:54:30 -0400 Subject: [Tutor] Pythonify this code! In-Reply-To: <4A5C49D8.7070008@tue.nl> References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> <4A5B18CF.20406@ieee.org> <8acb5ef80907140146s49c2878anf7b7fa283ef57522@mail.gmail.com> <4A5C49D8.7070008@tue.nl> Message-ID: <4A5C63E6.90908@ieee.org> A.T.Hofkamp wrote: >
Muhammad > Ali wrote: >> def separateToList(num): >> """ >> changes an integer into a list with 0's padded to the left if the >> number is in tens or units >> """ >> assert(num <= 255) > > >> s = str(num) >> li = [] >> if len(s) > 2: >> li = [s[0:1], s[1:2], s[2:3]] >> elif len(s) > 1: >> li = [0, s[0:1], s[1:2]] >> elif len(s) > 0: >> li = [0, 0, s[0:1]] >> >> return map(int, li) > > return [int(v) for v in ("00" + str(num))[-3:]] > > > Albert > >
> Or def separateToList(num): """ changes an integer 0-255 into a list of ints, size exactly 3 """ return map(int, list(format(num, "03d"))) From a.t.hofkamp at tue.nl Tue Jul 14 13:25:24 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 14 Jul 2009 13:25:24 +0200 Subject: [Tutor] Pythonify this code! In-Reply-To: <4A5C63E6.90908@ieee.org> References: <8acb5ef80907130101r19d95eefq9a3e7d4cd91a57e1@mail.gmail.com> <4A5B18CF.20406@ieee.org> <8acb5ef80907140146s49c2878anf7b7fa283ef57522@mail.gmail.com> <4A5C49D8.7070008@tue.nl> <4A5C63E6.90908@ieee.org> Message-ID: <4A5C6B24.3000702@tue.nl> Dave Angel wrote: > def separateToList(num): > """ > changes an integer 0-255 into a list of ints, size exactly 3 > """ > return map(int, list(format(num, "03d"))) Nice! Note that the "list" conversion is not needed; when you iterate over a string you automatically get each character in turn: map(int, ("%03d" % num)) Albert From ams28 at sfu.ca Tue Jul 14 01:23:47 2009 From: ams28 at sfu.ca (Andrea Semenik) Date: Mon, 13 Jul 2009 16:23:47 -0700 (PDT) Subject: [Tutor] University student struggling! In-Reply-To: <1312341294.252961247527187979.JavaMail.root@jaguar8.sfu.ca> Message-ID: <1879712445.255321247527427509.JavaMail.root@jaguar8.sfu.ca> Hello Python Tutors! I am a non-computer science major taking a computer programming course. That is the first red flag you should know. Second red flag, the course is poorly, I mean poorly written. third red flag, it is a distance education course, so it is done online. Needless to say I am in big trouble. I have been working on this assignment for days and have gotten nowhere. here are the directions: For this assignment, you will create a web script that lets the user explore RGB colours. On the first page the user sees, they should specify two RGB colours. When they submit this page, they should be presented with a range of colours in between the two. The intermediate colours will be calculated by your program. For example, if the user enters the colours red (100% red, 0% green, 0% blue) and white (100% red, 100% green, 100% blue), your program might output a page containing this: (image of a color box) If you want, you can experiment with an example of a working colour explorer. You can copy HTML and CSS code from this example if you wish. The easiest way to create one of the blocks of colour is with a
like this:
There are a couple of new things here. First, note that you can indicate style information with the style attribute on an HTML tag. This is generally a bad idea, but it's possible for cases just like this where you want to control the style of individual elements in very specific ways. Second, you can specify an RGB colour in CSS by specifying three percentages as in rgb(100%, 50%, 0%). This isn't used as commonly as the hexadecimal method we've used in the course up to now, but it is supported by modern web browsers and will be much easier to work with in our program. In this example, the colour will have a lot of red (100%=F), half green (50%?7) and no blue (0%=0) Here's how you calculate the in-between colours: I'm going to assume the percentage of red the user specified for the first colour is an integer in red1 and the amount of red for colour two is in red2. The number of steps the user requested is in nsteps. If you want the amount of red (as a percent) for colour block i, you can do this (assuming i goes from 0 to nsteps-1): fraction = (i+1.0)/nsteps r = (1-fraction)*red1 + fraction*red2 After this, the variable r will contain the correct percent (as a floating point value). The calculation for green and blue are exactly the same. (You don't have to repeat the calculation of fraction, of course.) Here are some other points about how the program should behave: ? You will have to apply a style sheet to the
tags so they are large enough to see. Something like this might be appropriate: colourblock { width: 10em; height: 1em; } ? Your program must never output more than 150 total colours, no matter how many the user asks for. If the users asks for more, it should only output 150. Having a limitation like this is an essential security measure. If not, someone could ask for 1000000 steps; this would overload the server and someone would probably come asking you why you used so much of the University's bandwidth. [Actually, the course web server automatically limits the size of the page your script can create. This isn't the case on most web servers so you should get into the habit of paying attention to the amount of output you generate. Python scripts on the server are limited to 60k of output.] ? You don't have to worry about catching errors in the user's input. That is, don't worry about the possibility of them entering "abcd" as the number of steps. ? You have to be careful about the spacing when outputting the RGB percentage values. You will have to convert the numbers to strings and concatenate them. For example, this statement will output part of the style attribute: print 'style="background-color: rgb(' + str(r) + '%' ? All of your XHTML (including generated XHTML) and CSS must be valid. I have no idea how to begin!! can you help me? Thank you, Andrea Semenik From kent37 at tds.net Tue Jul 14 13:33:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jul 2009 07:33:50 -0400 Subject: [Tutor] browser encoding standards? In-Reply-To: References: Message-ID: <1c2a2c590907140433n3c19d682je69bdd7eeffc5502@mail.gmail.com> On Mon, Jul 13, 2009 at 7:55 PM, Alan Gauld wrote: > OK, What kind of meta tag should I include? > I have a couple, but not very many meta tags in my files. I try to > minimalise > content and maintain HTML 3.2 compatibility for oldr browsers. > > What would a content-type meta line look like to get round this > quoting problem? My O'Reilly pocket reference suggests: > > > > Would that suffice? Yes, that should do it. The other alternative, if you have control of the web server, is to set the actual content-type header sent by the server. The meta tag is a way to simulate that from the contents of the page. Kent From kent37 at tds.net Tue Jul 14 13:39:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jul 2009 07:39:08 -0400 Subject: [Tutor] assigning list to keys In-Reply-To: <20090714065818.29280@gmx.net> References: <20090714065818.29280@gmx.net> Message-ID: <1c2a2c590907140439x2ff491ddq5257da4a1857824a@mail.gmail.com> On Tue, Jul 14, 2009 at 2:58 AM, Todd Matsumoto wrote: > Hello, > > The other day I needed to pack a dictionary, the value of each key was a list. In the code I was packing the list and the dictionary at the same time. First I tried something like this: > > list = [] > dict = {} > x = 1 > > dict['int'] = list.append(x) I don't know what you mean by "pack a dictionary". A fairly common requirement is for a dictionary that maps keys to a list of values, and a way to accumulate the values from a list of key, value pairs where the keys may repeat. collections.defaultdict is helpful for this, for example: In [3]: from collections import defaultdict In [4]: d = defaultdict(list) In [5]: pairs = [ ('int', 1), ('float', 2.5), ('int', 3), ('float', 3.14) ] In [6]: for k, v in pairs: ...: d[k].append(v) In [7]: d Out[7]: defaultdict(, {'int': [1, 3], 'float': [2.5, 3.1400000000000001]}) The value of d[k] will be a list, either an empty list or a previously created one, so d[k].append() adds a new value to the list. Kent From kent37 at tds.net Tue Jul 14 13:48:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jul 2009 07:48:20 -0400 Subject: [Tutor] University student struggling! In-Reply-To: <1879712445.255321247527427509.JavaMail.root@jaguar8.sfu.ca> References: <1312341294.252961247527187979.JavaMail.root@jaguar8.sfu.ca> <1879712445.255321247527427509.JavaMail.root@jaguar8.sfu.ca> Message-ID: <1c2a2c590907140448j4961ca76g39cbf63d163c74e0@mail.gmail.com> On Mon, Jul 13, 2009 at 7:23 PM, Andrea Semenik wrote: > I have no idea how to begin!! can you help me? What have you done so far? Do you know how to serve and form and respond to form submission? Do you know how to dynamically generate and serve a page of HTML? What are you using to program the server, is it CGI? Here is a place to start: - create a page that shows a form allowing the user to specify the colors - make a CGI that receives the form submission and displays the two specified colors Kent From bgailer at gmail.com Tue Jul 14 14:58:43 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 14 Jul 2009 08:58:43 -0400 Subject: [Tutor] University student struggling! In-Reply-To: <1879712445.255321247527427509.JavaMail.root@jaguar8.sfu.ca> References: <1879712445.255321247527427509.JavaMail.root@jaguar8.sfu.ca> Message-ID: <4A5C8103.9050201@gmail.com> Andrea Semenik wrote: > > I have no idea how to begin!! can you help me? > It sounds like this is not the first assignment in the course. True? If so did you complete them successfully? If so is there anything in the prior assignments that you can build on? Also note that your question includes Python, web servers, HTML. Have you asked the question in other fora? Is there a link to this and prior problems that we can visit? -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Tue Jul 14 15:03:21 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 14 Jul 2009 09:03:21 -0400 Subject: [Tutor] assigning list to keys In-Reply-To: <4A5C34B2.8020708@compuscan.co.za> References: <20090714065818.29280@gmx.net> <4A5C34B2.8020708@compuscan.co.za> Message-ID: <4A5C8219.20400@gmail.com> Christian Witts wrote: > Todd Matsumoto wrote: >> Hello, >> >> The other day I needed to pack a dictionary, the value of each key >> was a list. In the code I was packing the list and the dictionary at >> the same time. First I tried something like this: >> >> list = [] >> dict = {} >> x = 1 >> >> dict['int'] = list.append(x) >> >> The result was {'int': None}. Why is the value None? >> >> Cheers, >> >> T >> > Hi, > > Appending to a list does so in-place and returns None. If you wish to > do what you posted you will need to do it in 2 steps with: > > list.append(x) > dict['int'] = list Don't you mean dict['int'] = list[-1]? > > You should also avoid shadowing built-in names like "list", "dict", > "file" etc as you can very easily end up with unexplained errors. > > Hope that helps. > -- Bob Gailer Chapel Hill NC 919-636-4239 From tmatsumoto at gmx.net Tue Jul 14 15:41:27 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 15:41:27 +0200 Subject: [Tutor] unittests, testing a type Message-ID: <20090714134127.29270@gmx.net> Hi, Does anyone know how to do a unittest assert for a type? So If you have a program returning a Decimal, lets say Decimal("1"), and you want to make sure that what is returned is a Decimal object. At first I thought of importing Decimal and making my own Decimal("1") and doing an assertEquals, but this implies I know what the return type is before getting it. Cheers, T -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From a.t.hofkamp at tue.nl Tue Jul 14 15:45:18 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 14 Jul 2009 15:45:18 +0200 Subject: [Tutor] unittests, testing a type In-Reply-To: <20090714134127.29270@gmx.net> References: <20090714134127.29270@gmx.net> Message-ID: <4A5C8BEE.7040105@tue.nl> Todd Matsumoto wrote: > Hi, > > Does anyone know how to do a unittest assert for a type? > > So If you have a program returning a Decimal, lets say Decimal("1"), and you want to make sure that what is returned is a Decimal object. > > At first I thought of importing Decimal and making my own Decimal("1") and doing an assertEquals, but this implies I know what the return type is before getting it. For new-style classes, you should be able to do type(result) is Decimal (since the class is a singleton, 'is' should work). Albert From tmatsumoto at gmx.net Tue Jul 14 15:59:19 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Tue, 14 Jul 2009 15:59:19 +0200 Subject: [Tutor] unittests, testing a type In-Reply-To: <4A5C8BEE.7040105@tue.nl> References: <20090714134127.29270@gmx.net> <4A5C8BEE.7040105@tue.nl> Message-ID: <20090714135919.146540@gmx.net> Okay, Thanks that worked. I still needed to import the Decimal class and I'm not sure that is okay. The reason why is I'm receiving the Decimal value from another program, if I already know that the value will be a Decimal why test it? Perhaps I'm getting to caught up in this test-driven development thing. Cheers, T -------- Original-Nachricht -------- > Datum: Tue, 14 Jul 2009 15:45:18 +0200 > Von: "A.T.Hofkamp" > An: Todd Matsumoto > CC: "tutor at python.org" > Betreff: Re: [Tutor] unittests, testing a type > Todd Matsumoto wrote: > > Hi, > > > > Does anyone know how to do a unittest assert for a type? > > > > So If you have a program returning a Decimal, lets say Decimal("1"), and > you want to make sure that what is returned is a Decimal object. > > > > At first I thought of importing Decimal and making my own Decimal("1") > and > doing an assertEquals, but this implies I know what the return type is > before > getting it. > > > For new-style classes, you should be able to do > > > type(result) is Decimal > > > > (since the class is a singleton, 'is' should work). > > > Albert -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From kent37 at tds.net Tue Jul 14 16:18:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jul 2009 10:18:32 -0400 Subject: [Tutor] unittests, testing a type In-Reply-To: <4A5C8BEE.7040105@tue.nl> References: <20090714134127.29270@gmx.net> <4A5C8BEE.7040105@tue.nl> Message-ID: <1c2a2c590907140718w53dcc1afve10a5a13e5ba1796@mail.gmail.com> On Tue, Jul 14, 2009 at 9:45 AM, A.T.Hofkamp wrote: > Todd Matsumoto wrote: >> >> Hi, >> >> Does anyone know how to do a unittest assert for a type? > For new-style classes, you should be able to do > > > type(result) is Decimal When possible, it's better to use assertEqual() rather than a plain assert_() because you will get a better error message on failure. If you write self.assert_(type(result) is Decimal) on failure you will get an uninformative message like "assertion failed" If you write self.assertEqual(type(result), Decimal) you will get an error more like "float != Decimal" Kent From kent37 at tds.net Tue Jul 14 16:58:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jul 2009 10:58:32 -0400 Subject: [Tutor] unittests, testing a type In-Reply-To: <20090714135919.146540@gmx.net> References: <20090714134127.29270@gmx.net> <4A5C8BEE.7040105@tue.nl> <20090714135919.146540@gmx.net> Message-ID: <1c2a2c590907140758t23096c43s4c504d9632f373d2@mail.gmail.com> On Tue, Jul 14, 2009 at 9:59 AM, Todd Matsumoto wrote: > Okay, > > Thanks that worked. > > I still needed to import the Decimal class and I'm not sure that is okay. Sure, why not? > The reason why is I'm receiving the Decimal value from another program, if I already know that the value will be a Decimal why test it? Well, why are you testing it? What was the motivation for your original question? It's fine to right a test that verifies that the other program is doing what you expect. That's all any passing test really does, is verify expected behaviour. The benefit is that if the behaviour ever changes your test will fail and you will find out. Kent From kent37 at tds.net Tue Jul 14 17:08:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jul 2009 11:08:11 -0400 Subject: [Tutor] University student struggling! In-Reply-To: <1484470798.379921247583717935.JavaMail.root@jaguar8.sfu.ca> References: <989876474.379661247583646747.JavaMail.root@jaguar8.sfu.ca> <1484470798.379921247583717935.JavaMail.root@jaguar8.sfu.ca> Message-ID: <1c2a2c590907140808t2e885ccjbae7781fdedcb178@mail.gmail.com> Forwarding to the list with my reply. Please use Reply All to respond to the list. On Tue, Jul 14, 2009 at 11:01 AM, Andrea Semenik wrote: > Thank you so much for your quick response. This is really the first assignment of its kind with this course, there was no warm up to get us familiar with python. the only thing we had to do was program a page that showed the current time. But that was easy because all we had to do was use time.asctime(). For this assignment this is what I have done > > import cgi > form = cgi.FieldStorage() > > # print HTTP/HTML header stuff > print "Content-type: text/html" > print > print""" > > > Colour Blend > > > > """ > print > > print "

", form["red1"].value, "

" > print "

", form["green1"].value, "

" > print "

", form["blue1"].value, "

" > print "

", form["red2"].value, "

" > print "

", form["green2"].value, "

" > print "

", form["blue2"].value, "

" > print "

", form["steps"].value, "

" > print > > > I am not sure if that is even right. My page is now showing the values that were input by the user on the previous page. But I feel like that could be the start to something. like there is another step that will then connect these values into making a color box. But I just don't know, I have been trying to read as much as I can about python, but I am overwhelmed. This is a good start. Can you modify this program to show the actual colors in a
, rather than just echoing the numbers? Kent From jcook713 at gmail.com Tue Jul 14 19:11:48 2009 From: jcook713 at gmail.com (J Cook) Date: Tue, 14 Jul 2009 13:11:48 -0400 Subject: [Tutor] How to pass command line variables to this python code... Message-ID: <4A5CBC54.5050004@gmail.com> Hello, I have some autogenerated code from Selenium which I cannot figure out how to pass some command line variables to. For example I could export the same in Perl and it would be for example: use strict; use warnings; use Time::HiRes qw(sleep); use Test::WWW::Selenium; use Test::More "no_plan"; use Test::Exception; my $sel = Test::WWW::Selenium->new( host => "localhost", port => 4444, browser => "*chrome", browser_url => "http://www.google.com/" ); $sel->open_ok("/"); $sel->type_ok("q", "red sox"); I could then go in and add something like: my ($arg1) = shift || "default"; which would pick up the first command line parameter and then I could do something like: $sel->(type_ok, $arg1); All is good here, now Selenium will export the following for Python: from selenium import selenium import unittest, time, re class NewTest(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "http://www.google.com/") self.selenium.start() def test_new(self): sel = self.selenium sel.open("/") sel.type("q", "red sox") def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() Now I am confused on how to pass a command line parameter here. Any suggestions? I would like to be able to run something like: $ python selenium-google-test.py "yankees" Suggestions? TIA Justin From vinces1979 at gmail.com Tue Jul 14 19:36:06 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 14 Jul 2009 11:36:06 -0600 Subject: [Tutor] How to pass command line variables to this python code... In-Reply-To: <4A5CBC54.5050004@gmail.com> References: <4A5CBC54.5050004@gmail.com> Message-ID: <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> First off, selenium is a great tool and the python driver is very powerful there are numerous ways to access cli variables, the quickest import sys print sys.srgv sys.argv will it output a array of all command line args ./selenium-google-test.py yankees will out put: ['selenium-google-test.py', 'yankees'] so args = sys.argv args[0] == 'yankees' True for a more functional way, check out http://docs.python.org/library/getopt.html On Tue, Jul 14, 2009 at 11:11 AM, J Cook wrote: > Hello, > > I have some autogenerated code from Selenium which I cannot figure out how > to pass some command line variables to. For example I could export the same > in Perl and it would be for example: > > > use strict; > use warnings; > use Time::HiRes qw(sleep); > use Test::WWW::Selenium; > use Test::More "no_plan"; > use Test::Exception; > > my $sel = Test::WWW::Selenium->new( host => "localhost", > port => 4444, > browser => "*chrome", > browser_url => " > http://www.google.com/" ); > > $sel->open_ok("/"); > $sel->type_ok("q", "red sox"); > > > I could then go in and add something like: > > my ($arg1) = shift || "default"; > > which would pick up the first command line parameter and then I could do > something like: > > $sel->(type_ok, $arg1); > > All is good here, now Selenium will export the following for Python: > > > from selenium import selenium > import unittest, time, re > > class NewTest(unittest.TestCase): > def setUp(self): > self.verificationErrors = [] > self.selenium = selenium("localhost", 4444, "*chrome", " > http://www.google.com/") > self.selenium.start() > > def test_new(self): > sel = self.selenium > sel.open("/") > sel.type("q", "red sox") > > def tearDown(self): > self.selenium.stop() > self.assertEqual([], self.verificationErrors) > > if __name__ == "__main__": > unittest.main() > > > Now I am confused on how to pass a command line parameter here. Any > suggestions? I would like to be able to run something like: > > $ python selenium-google-test.py "yankees" > > Suggestions? > > > TIA > > Justin > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jul 14 20:09:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jul 2009 19:09:17 +0100 Subject: [Tutor] Saving class instances References: <158478C6-08DE-48CE-97EA-3508F10EDDDE@gmail.com> Message-ID: "Thomas Scrace" wrote > Good to know I wasn't being totally dense. Now that I have got the > pickle thing under my belt I am going to have a go at sqllite. Again, you might find the database topic ijn my tuorial a useful starting point for using SqlLite from Python... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jul 14 20:13:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Jul 2009 19:13:46 +0100 Subject: [Tutor] How to pass command line variables to this python code... References: <4A5CBC54.5050004@gmail.com> Message-ID: "J Cook" wrote > Now I am confused on how to pass a command line parameter here. Any > suggestions? I would like to be able to run something like: > > $ python selenium-google-test.py "yankees" Try the Talking to the User topic in my tutorial, it includes a section on accessing command line args. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jcook713 at gmail.com Tue Jul 14 21:36:40 2009 From: jcook713 at gmail.com (J Cook) Date: Tue, 14 Jul 2009 15:36:40 -0400 Subject: [Tutor] How to pass command line variables to this python code... In-Reply-To: <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> References: <4A5CBC54.5050004@gmail.com> <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> Message-ID: <4A5CDE48.6020405@gmail.com> Ok, So I added the following: from selenium import selenium import unittest, time, re import sys # added this q = sys.argv[1] # added this print q # added this just to see class NewTest(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 4444, "*chrome", "http://www.google.com/") self.selenium.start() def test_new(self): sel = self.selenium sel.open("/") sel.type("q", q) # this is where I want the argument to end up def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() I run the following: $ python selenium-google-test.py yankees yankees Traceback (most recent call last): File "selenium-google-test.py", line 24, in unittest.main() File "/usr/lib/python2.6/unittest.py", line 816, in __init__ self.parseArgs(argv) File "/usr/lib/python2.6/unittest.py", line 843, in parseArgs self.createTests() File "/usr/lib/python2.6/unittest.py", line 849, in createTests self.module) File "/usr/lib/python2.6/unittest.py", line 613, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/usr/lib/python2.6/unittest.py", line 584, in loadTestsFromName parent, obj = obj, getattr(obj, part) AttributeError: 'module' object has no attribute 'yankees' How do I get the argument over to where I need it to be? Justin vince spicer wrote: > First off, selenium is a great tool and the python driver is very powerful > > there are numerous ways to access cli variables, > > the quickest > > import sys > print sys.srgv > > sys.argv will it output a array of all command line args > > ./selenium-google-test.py yankees > will out put: > > ['selenium-google-test.py', 'yankees'] > > so > > args = sys.argv > > args[0] == 'yankees' > True > > for a more functional way, check out > http://docs.python.org/library/getopt.html > > > > On Tue, Jul 14, 2009 at 11:11 AM, J Cook > wrote: > > Hello, > > I have some autogenerated code from Selenium which I cannot figure > out how to pass some command line variables to. For example I could > export the same in Perl and it would be for example: > > > use strict; > use warnings; > use Time::HiRes qw(sleep); > use Test::WWW::Selenium; > use Test::More "no_plan"; > use Test::Exception; > > my $sel = Test::WWW::Selenium->new( host => "localhost", > port => 4444, > browser => "*chrome", > browser_url => > "http://www.google.com/" ); > > $sel->open_ok("/"); > $sel->type_ok("q", "red sox"); > > > I could then go in and add something like: > > my ($arg1) = shift || "default"; > > which would pick up the first command line parameter and then I > could do something like: > > $sel->(type_ok, $arg1); > > All is good here, now Selenium will export the following for Python: > > > from selenium import selenium > import unittest, time, re > > class NewTest(unittest.TestCase): > def setUp(self): > self.verificationErrors = [] > self.selenium = selenium("localhost", 4444, "*chrome", > "http://www.google.com/") > self.selenium.start() > > def test_new(self): > sel = self.selenium > sel.open("/") > sel.type("q", "red sox") > > def tearDown(self): > self.selenium.stop() > self.assertEqual([], self.verificationErrors) > > if __name__ == "__main__": > unittest.main() > > > Now I am confused on how to pass a command line parameter here. Any > suggestions? I would like to be able to run something like: > > $ python selenium-google-test.py "yankees" > > Suggestions? > > > TIA > > Justin > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From vinces1979 at gmail.com Tue Jul 14 21:57:32 2009 From: vinces1979 at gmail.com (vince spicer) Date: Tue, 14 Jul 2009 13:57:32 -0600 Subject: [Tutor] How to pass command line variables to this python code... In-Reply-To: <4A5CDE48.6020405@gmail.com> References: <4A5CBC54.5050004@gmail.com> <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> <4A5CDE48.6020405@gmail.com> Message-ID: <1e53c510907141257i336b7430we2e2b00eedc6734b@mail.gmail.com> Sorry I do remember that issue in the past, the unittest.main takes over the cli variables in order to select modules to run python selenium-google-test.py --help so unittest is assuming yankees is a test module, you can override this functionality however with: unittest.main(argv=['mytestapp']) this will cause the default run all test modules, and allow you to access the argv Hope that helps Vince On Tue, Jul 14, 2009 at 1:36 PM, J Cook wrote: > Ok, > > So I added the following: > > > from selenium import selenium > import unittest, time, re > import sys # added this > > q = sys.argv[1] # added this > print q # added this just to see > > class NewTest(unittest.TestCase): > def setUp(self): > self.verificationErrors = [] > self.selenium = selenium("localhost", 4444, "*chrome", " > http://www.google.com/") > self.selenium.start() > > def test_new(self): > sel = self.selenium > sel.open("/") > sel.type("q", q) # this is where I want the argument to end up > > def tearDown(self): > self.selenium.stop() > self.assertEqual([], self.verificationErrors) > > if __name__ == "__main__": > unittest.main() > > > I run the following: > > $ python selenium-google-test.py yankees > yankees > Traceback (most recent call last): > File "selenium-google-test.py", line 24, in > unittest.main() > File "/usr/lib/python2.6/unittest.py", line 816, in __init__ > self.parseArgs(argv) > File "/usr/lib/python2.6/unittest.py", line 843, in parseArgs > self.createTests() > File "/usr/lib/python2.6/unittest.py", line 849, in createTests > self.module) > File "/usr/lib/python2.6/unittest.py", line 613, in loadTestsFromNames > suites = [self.loadTestsFromName(name, module) for name in names] > File "/usr/lib/python2.6/unittest.py", line 584, in loadTestsFromName > parent, obj = obj, getattr(obj, part) > AttributeError: 'module' object has no attribute 'yankees' > > How do I get the argument over to where I need it to be? > > Justin > > vince spicer wrote: > >> First off, selenium is a great tool and the python driver is very powerful >> >> there are numerous ways to access cli variables, >> >> the quickest >> >> import sys >> print sys.srgv >> >> sys.argv will it output a array of all command line args >> >> ./selenium-google-test.py yankees >> will out put: >> >> ['selenium-google-test.py', 'yankees'] >> >> so >> >> args = sys.argv >> >> args[0] == 'yankees' >> True >> >> for a more functional way, check out >> http://docs.python.org/library/getopt.html >> >> >> >> On Tue, Jul 14, 2009 at 11:11 AM, J Cook > jcook713 at gmail.com>> wrote: >> >> Hello, >> >> I have some autogenerated code from Selenium which I cannot figure >> out how to pass some command line variables to. For example I could >> export the same in Perl and it would be for example: >> >> >> use strict; >> use warnings; >> use Time::HiRes qw(sleep); >> use Test::WWW::Selenium; >> use Test::More "no_plan"; >> use Test::Exception; >> >> my $sel = Test::WWW::Selenium->new( host => "localhost", >> port => 4444, >> browser => "*chrome", >> browser_url => " >> http://www.google.com/" ); >> >> $sel->open_ok("/"); >> $sel->type_ok("q", "red sox"); >> >> >> I could then go in and add something like: >> >> my ($arg1) = shift || "default"; >> >> which would pick up the first command line parameter and then I >> could do something like: >> >> $sel->(type_ok, $arg1); >> >> All is good here, now Selenium will export the following for Python: >> >> >> from selenium import selenium >> import unittest, time, re >> >> class NewTest(unittest.TestCase): >> def setUp(self): >> self.verificationErrors = [] >> self.selenium = selenium("localhost", 4444, "*chrome", >> "http://www.google.com/") >> self.selenium.start() >> >> def test_new(self): >> sel = self.selenium >> sel.open("/") >> sel.type("q", "red sox") >> >> def tearDown(self): >> self.selenium.stop() >> self.assertEqual([], self.verificationErrors) >> >> if __name__ == "__main__": >> unittest.main() >> >> >> Now I am confused on how to pass a command line parameter here. Any >> suggestions? I would like to be able to run something like: >> >> $ python selenium-google-test.py "yankees" >> >> Suggestions? >> >> >> TIA >> >> Justin >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Jul 15 04:36:14 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 14 Jul 2009 22:36:14 -0400 Subject: [Tutor] unittests, testing a type In-Reply-To: <1c2a2c590907140758t23096c43s4c504d9632f373d2@mail.gmail.com> References: <20090714134127.29270@gmx.net> <4A5C8BEE.7040105@tue.nl> <20090714135919.146540@gmx.net> <1c2a2c590907140758t23096c43s4c504d9632f373d2@mail.gmail.com> Message-ID: <4A5D409E.2030408@ieee.org> On Tue, Jul 14, 2009 at 9:59 AM, Todd Matsumoto wrote: >> The reason why is I'm receiving the Decimal value from another program, if I already know that the value will be a Decimal why test it? >> > > How are you receiving it? File, pickle, pipe, socket, exit() return value? When I first read your question, I assumed you meant "from another module." But if it's another process, then you'd better tell us how you're actually getting the value. Maybe it's a Decimal because you just got done converting it to one. DaveA From cwitts at compuscan.co.za Wed Jul 15 08:25:11 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 15 Jul 2009 08:25:11 +0200 Subject: [Tutor] How to pass command line variables to this python code... In-Reply-To: <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> References: <4A5CBC54.5050004@gmail.com> <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> Message-ID: <4A5D7647.2070000@compuscan.co.za> vince spicer wrote: > First off, selenium is a great tool and the python driver is very powerful > > there are numerous ways to access cli variables, > > the quickest > > import sys > print sys.srgv > > sys.argv will it output a array of all command line args > > ./selenium-google-test.py yankees > will out put: > > ['selenium-google-test.py', 'yankees'] > > so > > args = sys.argv > > args[0] == 'yankees' > True That would be false, the first argument (list index zero) is the script name. You would need to do args = sys.argv[1:] if you want to dump the filename from the list. -- Kind Regards, Christian Witts From tmatsumoto at gmx.net Wed Jul 15 08:14:48 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Wed, 15 Jul 2009 08:14:48 +0200 Subject: [Tutor] unittests, testing a type In-Reply-To: <4A5D409E.2030408@ieee.org> References: <20090714134127.29270@gmx.net> <4A5C8BEE.7040105@tue.nl> <20090714135919.146540@gmx.net> <1c2a2c590907140758t23096c43s4c504d9632f373d2@mail.gmail.com> <4A5D409E.2030408@ieee.org> Message-ID: <20090715061448.32920@gmx.net> Hi, Thanks for all the comments so far. DaveA, I'm receiving the value via pyODBC, after running a query on a database. The test is to first make sure the value is a Decimal (pyODBC returns a Decimal object if what is coming from the database is a decimal type). So if I don't have a value that is a Decimal object something is wrong. Cheers, T -------- Original-Nachricht -------- > Datum: Tue, 14 Jul 2009 22:36:14 -0400 > Von: Dave Angel > An: > CC: Todd Matsumoto , tutor at python.org > Betreff: Re: Re: [Tutor] unittests, testing a type > On Tue, Jul 14, 2009 at 9:59 AM, Todd Matsumoto wrote: > >> The reason why is I'm receiving the Decimal value from another program, > if I already know that the value will be a Decimal why test it? > >> > > > > > How are you receiving it? File, pickle, pipe, socket, exit() return > value? When I first read your question, I assumed you meant "from > another module." But if it's another process, then you'd better tell us > how you're actually getting the value. Maybe it's a Decimal because you > just got done converting it to one. > > DaveA -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/chbrowser From tmatsumoto at gmx.net Wed Jul 15 13:41:53 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Wed, 15 Jul 2009 13:41:53 +0200 Subject: [Tutor] decorators, __call__ (able) objects Message-ID: <20090715114153.32910@gmx.net> Hi, Can some one give, or point to some good examples of how @decorators work, and __call__ (able) objects? I'm having trouble getting my head around these techniques (concepts). Cheers, T -- Neu: GMX Doppel-FLAT mit Internet-Flatrate + Telefon-Flatrate f?r nur 19,99 Euro/mtl.!* http://portal.gmx.net/de/go/dsl02 From kent37 at tds.net Wed Jul 15 14:33:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Jul 2009 08:33:33 -0400 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <20090715114153.32910@gmx.net> References: <20090715114153.32910@gmx.net> Message-ID: <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> On Wed, Jul 15, 2009 at 7:41 AM, Todd Matsumoto wrote: > Hi, > > Can some one give, or point to some good examples of how @decorators work, and __call__ (able) objects? Decorators: http://personalpages.tds.net/~kent37/kk/00001.html Kent From vinces1979 at gmail.com Wed Jul 15 16:19:19 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 15 Jul 2009 08:19:19 -0600 Subject: [Tutor] How to pass command line variables to this python code... In-Reply-To: <4A5D7647.2070000@compuscan.co.za> References: <4A5CBC54.5050004@gmail.com> <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> <4A5D7647.2070000@compuscan.co.za> Message-ID: <1e53c510907150719u1752fc54n2f4d7df3fb1c3949@mail.gmail.com> good catch, my mistake args[1] == 'yankees' True On Wed, Jul 15, 2009 at 12:25 AM, Christian Witts wrote: > vince spicer wrote: > >> First off, selenium is a great tool and the python driver is very powerful >> >> there are numerous ways to access cli variables, >> >> the quickest >> >> import sys >> print sys.srgv >> >> sys.argv will it output a array of all command line args >> >> ./selenium-google-test.py yankees >> will out put: >> >> ['selenium-google-test.py', 'yankees'] >> >> so >> >> args = sys.argv >> >> args[0] == 'yankees' >> True >> > That would be false, the first argument (list index zero) is the script > name. You would need to do > args = sys.argv[1:] > if you want to dump the filename from the list. > > -- > Kind Regards, > Christian Witts > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jul 15 16:20:26 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 15 Jul 2009 08:20:26 -0600 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> References: <20090715114153.32910@gmx.net> <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> Message-ID: <1e53c510907150720i5475bff7g4b7e4e24f8810e04@mail.gmail.com> simple example of calling a class class myKlass(object): On Wed, Jul 15, 2009 at 6:33 AM, Kent Johnson wrote: > On Wed, Jul 15, 2009 at 7:41 AM, Todd Matsumoto wrote: > > Hi, > > > > Can some one give, or point to some good examples of how @decorators > work, and __call__ (able) objects? > > Decorators: > http://personalpages.tds.net/~kent37/kk/00001.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jul 15 16:22:14 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 15 Jul 2009 08:22:14 -0600 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <1e53c510907150720i5475bff7g4b7e4e24f8810e04@mail.gmail.com> References: <20090715114153.32910@gmx.net> <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> <1e53c510907150720i5475bff7g4b7e4e24f8810e04@mail.gmail.com> Message-ID: <1e53c510907150722k374d1881l69bfc1069b423629@mail.gmail.com> simple example of calling a class class myKlass(object): def __call__(self, *args, **kws): print "i was called" >> test = myKlass() >> test() >> i was called > > > > On Wed, Jul 15, 2009 at 6:33 AM, Kent Johnson wrote: > >> On Wed, Jul 15, 2009 at 7:41 AM, Todd Matsumoto >> wrote: >> > Hi, >> > >> > Can some one give, or point to some good examples of how @decorators >> work, and __call__ (able) objects? >> >> Decorators: >> http://personalpages.tds.net/~kent37/kk/00001.html >> >> Kent >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From amrita at iisermohali.ac.in Wed Jul 15 14:24:09 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Wed, 15 Jul 2009 17:54:09 +0530 (IST) Subject: [Tutor] just one question Message-ID: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> Hi, i want to ask one thing that suppose i have a .txt file having content like:--- 47 8 ALA H H 7.85 0.02 1 48 8 ALA HA H 2.98 0.02 1 49 8 ALA HB H 1.05 0.02 1 50 8 ALA C C 179.39 0.3 1 51 8 ALA CA C 54.67 0.3 1 52 8 ALA CB C 18.85 0.3 1 53 8 ALA N N 123.95 0.3 1 107 15 ALA H H 8.05 0.02 1 108 15 ALA HA H 4.52 0.02 1 109 15 ALA HB H 1.29 0.02 1 110 15 ALA C C 177.18 0.3 1 111 15 ALA CA C 52.18 0.3 1 112 15 ALA CB C 20.64 0.3 1 113 15 ALA N N 119.31 0.3 1 154 21 ALA H H 7.66 0.02 1 155 21 ALA HA H 4.05 0.02 1 156 21 ALA HB H 1.39 0.02 1 157 21 ALA C C 179.35 0.3 1 158 21 ALA CA C 54.33 0.3 1 now what i want that i will make another .txt file in which first it will write the position of ALA lets say 8, 15, 21 then its name ALA and then the fifth column value for only three atoms C,CA and CB. Means it will be someting like: 8 ALA C = 179.39 CA = 54.67 CB = 18.85 15 ALA C = 177.18 CA = 52.18 CB = 20.64 21 ALA C = 179.35 CA = 54.33 CB = if some value is not there then it will leave that as blank.I am new in python but this is what we want, so how can i do it using python script. Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From vinces1979 at gmail.com Wed Jul 15 16:44:09 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 15 Jul 2009 08:44:09 -0600 Subject: [Tutor] just one question In-Reply-To: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> References: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> Message-ID: <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> one way is: import re infile = open("test.txt", "r") #: open read mode outfile = open("out.tx", "w") #: open write mode for line in infile: values = re.split("\s+", line) # split values on spaces EX: ['47', '8', 'ALA', 'H', 'H', '7.85', '0.02', '1'] outfile.write("%s %s C = %s CA = %s CB = %s" % (values[1], values[2], values[5], values[6], values[7])) infile.close() outfile.close() not tested but should work Vince On Wed, Jul 15, 2009 at 6:24 AM, wrote: > Hi, > > i want to ask one thing that suppose i have a .txt file having content > like:--- > > > 47 8 ALA H H 7.85 0.02 1 > 48 8 ALA HA H 2.98 0.02 1 > 49 8 ALA HB H 1.05 0.02 1 > 50 8 ALA C C 179.39 0.3 1 > 51 8 ALA CA C 54.67 0.3 1 > 52 8 ALA CB C 18.85 0.3 1 > 53 8 ALA N N 123.95 0.3 1 > 107 15 ALA H H 8.05 0.02 1 > 108 15 ALA HA H 4.52 0.02 1 > 109 15 ALA HB H 1.29 0.02 1 > 110 15 ALA C C 177.18 0.3 1 > 111 15 ALA CA C 52.18 0.3 1 > 112 15 ALA CB C 20.64 0.3 1 > 113 15 ALA N N 119.31 0.3 1 > 154 21 ALA H H 7.66 0.02 1 > 155 21 ALA HA H 4.05 0.02 1 > 156 21 ALA HB H 1.39 0.02 1 > 157 21 ALA C C 179.35 0.3 1 > 158 21 ALA CA C 54.33 0.3 1 > > now what i want that i will make another .txt file in which first it will > write the position of ALA lets say 8, 15, 21 then its name ALA and then > the fifth column value for only three atoms C,CA and CB. > > Means it will be someting like: > > 8 ALA C = 179.39 CA = 54.67 CB = 18.85 > 15 ALA C = 177.18 CA = 52.18 CB = 20.64 > 21 ALA C = 179.35 CA = 54.33 CB = > > if some value is not there then it will leave that as blank.I am new in > python but this is what we want, so how can i do it using python script. > > > > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjhynes36 at hotmail.com Wed Jul 15 17:19:32 2009 From: cjhynes36 at hotmail.com (chris Hynes) Date: Wed, 15 Jul 2009 15:19:32 +0000 Subject: [Tutor] objects becoming pointers Message-ID: I guess I have to start somewhere to ask............ I want the user to input a name, say "Chris". I know I can use the code: name=raw_input() I now want: "Chris"=zeros((3,3)) so that when I type: print Chris the return will be an array of zero's 3x3 So that I can understand this deeper, I know that "name" is just a pointer to the object "Chris". I don't want to just change the pointer to something else, like "zeros((3,3))" but I want to make "Chris" become the pointer or the name of the pointer. At least that's what I think I want. _________________________________________________________________ Windows Live? SkyDrive?: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_SD_25GB_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Wed Jul 15 17:29:53 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 15 Jul 2009 16:29:53 +0100 Subject: [Tutor] just one question In-Reply-To: <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> References: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> Message-ID: 2009/7/15 vince spicer : > one way is: > > import re > > infile = open("test.txt", "r") #: open read mode > outfile = open("out.tx", "w") #: open write mode > > for line in infile: > ??? values = re.split("\s+", line) # split values on spaces EX: ['47', '8', > 'ALA', 'H', 'H', '7.85', '0.02', '1'] > ??? outfile.write("%s? %s C =? %s? CA =? %s CB = %s" % (values[1], > values[2], values[5], values[6], values[7])) > > infile.close() > outfile.close() > > not tested but should work > > Vince > That isn't what they're after at all. Something more like from __future__ import with_statement #only works on version 2.5 and later from collections import defaultdict from decimal import Decimal atoms = defaultdict(dict) with open("INPUT_FILENAME_HERE") as f: for line in f: n, pos, ala, at, symb, weight, rad, count = line.split() atoms[int(pos)][at] = Decimal(weight) #modify these lines to fit your needs: positionsNeeded = (8, 15, 21) atomsNeeded = ("C", "CA", "CB") for position in positionsNeeded: print position, "ALA C = %s CA = %s CB = %s" % tuple(atoms[position].get(a,"") for a in atomsNeeded) You would then call it with something like $python myscipt.py > output.txt -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From roadierich at googlemail.com Wed Jul 15 17:33:00 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Wed, 15 Jul 2009 16:33:00 +0100 Subject: [Tutor] objects becoming pointers In-Reply-To: References: Message-ID: 2009/7/15 chris Hynes : > I guess I have to start somewhere to ask............ > > I want the user to input a name, say "Chris". I know I can use the code: > > name=raw_input() > > I now want: > > "Chris"=zeros((3,3)) > > so that when I type: > > print Chris > > the return will be an array of zero's 3x3 > > So that I can understand this deeper, I know that "name" is just a pointer > to the object "Chris". I don't want to just change the pointer to something > else, like "zeros((3,3))" but I want to make "Chris" become the pointer or > the name of the pointer. At least that's what I think I want. > > ________________________________ > Windows Live? SkyDrive?: Get 25 GB of free online storage. Get it on your > BlackBerry or iPhone. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Sorry if I've sent this twice... Why would you want to do that? The closest you can get to that is using exec, but exec is usually considered a code smell. I'd say you're trying to do the wrong thing. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From bgailer at gmail.com Wed Jul 15 17:41:29 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 15 Jul 2009 11:41:29 -0400 Subject: [Tutor] objects becoming pointers In-Reply-To: References: Message-ID: <4A5DF8A9.1010105@gmail.com> chris Hynes wrote: > I guess I have to start somewhere to ask............ > > I want the user to input a name, say "Chris". I know I can use the code: > > name=raw_input() > > I now want: > > "Chris"=zeros((3,3)) This is a FAQ. In Python one is discouraged from dynamically creating variable names. Preferred is a dictionary. names = {} # empty dictionary name=raw_input() names[name]=zeroes((3,3)) print names["Chris"] -- Bob Gailer Chapel Hill NC 919-636-4239 From jcook713 at gmail.com Wed Jul 15 17:06:55 2009 From: jcook713 at gmail.com (J Cook) Date: Wed, 15 Jul 2009 11:06:55 -0400 Subject: [Tutor] How to pass command line variables to this python code... In-Reply-To: <1e53c510907150719u1752fc54n2f4d7df3fb1c3949@mail.gmail.com> References: <4A5CBC54.5050004@gmail.com> <1e53c510907141036p29f2c86du559ce4f93d8f4aa3@mail.gmail.com> <4A5D7647.2070000@compuscan.co.za> <1e53c510907150719u1752fc54n2f4d7df3fb1c3949@mail.gmail.com> Message-ID: <4A5DF08F.9090109@gmail.com> Yeah, I figured that. I got it to work thanks, but I still don't understand how exactly. Coming from Perl I am used to a more procedural type of programming. BTW - Selenium is a great tool for web testing, and the way it will translate your web clickstream into your choice of languages rocks. Justin vince spicer wrote: > good catch, my mistake > > args[1] == 'yankees' > True > > > On Wed, Jul 15, 2009 at 12:25 AM, Christian Witts > > wrote: > > vince spicer wrote: > > First off, selenium is a great tool and the python driver is > very powerful > > there are numerous ways to access cli variables, > > the quickest > > import sys > print sys.srgv > > sys.argv will it output a array of all command line args > > ./selenium-google-test.py yankees > will out put: > > ['selenium-google-test.py', 'yankees'] > > so > > args = sys.argv > > args[0] == 'yankees' > True > > That would be false, the first argument (list index zero) is the > script name. You would need to do > args = sys.argv[1:] > if you want to dump the filename from the list. > > -- > Kind Regards, > Christian Witts > > > From vinces1979 at gmail.com Wed Jul 15 17:44:19 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 15 Jul 2009 09:44:19 -0600 Subject: [Tutor] objects becoming pointers In-Reply-To: References: Message-ID: <1e53c510907150844i5278527bocfe4d747b3ffb33e@mail.gmail.com> not sure exactly why you would want to that, but you could assign attributes to a class EX: class storage: pass >> store = Storage() >> name=raw_input() >> setattr(store, name, zeros(3,3)) >> print store.Chris On Wed, Jul 15, 2009 at 9:19 AM, chris Hynes wrote: > I guess I have to start somewhere to ask............ > > I want the user to input a name, say "Chris". I know I can use the code: > > name=raw_input() > > I now want: > > "Chris"=zeros((3,3)) > > so that when I type: > > print Chris > > the return will be an array of zero's 3x3 > > So that I can understand this deeper, I know that "name" is just a pointer > to the object "Chris". I don't want to just change the pointer to something > else, like "zeros((3,3))" but I want to make "Chris" become the pointer or > the name of the pointer. At least that's what I think I want. > > ------------------------------ > Windows Live? SkyDrive?: Get 25 GB of free online storage. Get it on your > BlackBerry or iPhone. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jul 15 17:44:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Jul 2009 11:44:30 -0400 Subject: [Tutor] objects becoming pointers In-Reply-To: References: Message-ID: <1c2a2c590907150844r46ab0d5ie77d4d24528bb5b6@mail.gmail.com> On Wed, Jul 15, 2009 at 11:19 AM, chris Hynes wrote: > I guess I have to start somewhere to ask............ > > I want the user to input a name, say "Chris". I know I can use the code: > > name=raw_input() > > I now want: > > "Chris"=zeros((3,3)) > > so that when I type: > > print Chris > > the return will be an array of zero's 3x3 The usual way to solve this is to use a dictionary: name = raw_input() values = dict() values[name] = zeros((3, 3)) print values[name] Kent From wescpy at gmail.com Wed Jul 15 20:44:31 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Jul 2009 11:44:31 -0700 Subject: [Tutor] just one question In-Reply-To: References: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> Message-ID: <78b3a9580907151144y4a546a03s52433635945777f5@mail.gmail.com> On Wed, Jul 15, 2009 at 8:29 AM, Rich Lovely wrote: > 2009/7/15 vince spicer : >> : >> import re >> : >> ??? values = re.split("\s+", line) # split values on spaces EX: ['47', '8', > > That isn't what they're after at all. > Something more like > : > ? ? ? ?n, pos, ala, at, symb, weight, rad, count = line.split() > : on a side note, i also discourage the use of regular expressions for this problem when a simpler solution like line.split() will suffice. bringing up an old jwz quote: 'Some people, when confronted with a problem, think ?I know, I'll use regular expressions.? Now they have two problems.' best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Wed Jul 15 21:02:05 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Jul 2009 12:02:05 -0700 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <1e53c510907150722k374d1881l69bfc1069b423629@mail.gmail.com> References: <20090715114153.32910@gmx.net> <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> <1e53c510907150720i5475bff7g4b7e4e24f8810e04@mail.gmail.com> <1e53c510907150722k374d1881l69bfc1069b423629@mail.gmail.com> Message-ID: <78b3a9580907151202p7ec9a45bm14a4c3b043b7d989@mail.gmail.com> >>> > Can some one give, or point to some good examples of how @decorators >>> > work, and __call__ (able) objects? > > simple example of calling a class > > class myKlass(object): > > def __call__(self, *args, **kws): > print "i was called" > > >>> test = myKlass() > >>> test() > i was called close. the example was right, but the description wasn't accurate... you meant, "calling an instance." i'm going to plagarize and rip this right out of section 14.1.4 from "Core Python Programming:" "Python provides the __call__() special method for classes, which allows a programmer to create objects (instances) that are callable. By default, the __call__() method is not implemented, meaning that most instances are not callable. However, if this method is overridden in a class de?nition, instances of such a class are made callable. Calling such instance objects is equivalent to invoking the __call__() method. Naturally, any arguments given in the instance call are passed as arguments to __call__()." as far as decorators go, kent's tutorial is great place to start. here are 2 more articles plus PEP 318, where they were defined: http://www.ibm.com/developerworks/linux/library/l-cpdecor.html http://www.artima.com/weblogs/viewpost.jsp?thread=240808 http://www.python.org/dev/peps/pep-0318 in addition, i devoted section 11.3.6 of Core Python to decorators. finally, it should be mentioned that starting in 2.6, you can now decorate *classes*, as seen here in PEP 3129: http://www.python.org/dev/peps/pep-3129/ hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From vinces1979 at gmail.com Wed Jul 15 21:13:42 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 15 Jul 2009 13:13:42 -0600 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <78b3a9580907151202p7ec9a45bm14a4c3b043b7d989@mail.gmail.com> References: <20090715114153.32910@gmx.net> <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> <1e53c510907150720i5475bff7g4b7e4e24f8810e04@mail.gmail.com> <1e53c510907150722k374d1881l69bfc1069b423629@mail.gmail.com> <78b3a9580907151202p7ec9a45bm14a4c3b043b7d989@mail.gmail.com> Message-ID: <1e53c510907151213o66e396bch761288ae616fa326@mail.gmail.com> agreed much better description, thanks On Wed, Jul 15, 2009 at 1:02 PM, wesley chun wrote: > >>> > Can some one give, or point to some good examples of how @decorators > >>> > work, and __call__ (able) objects? > > > > simple example of calling a class > > > > class myKlass(object): > > > > def __call__(self, *args, **kws): > > print "i was called" > > > > >>> test = myKlass() > > >>> test() > > i was called > > > close. the example was right, but the description wasn't accurate... > you meant, "calling an instance." i'm going to plagarize and rip this > right out of section 14.1.4 from "Core Python Programming:" > > "Python provides the __call__() special method for classes, which allows a > programmer to create objects (instances) that are callable. By default, the > __call__() method is not implemented, meaning that most instances are > not callable. However, if this method is overridden in a class de?nition, > instances of such a class are made callable. Calling such instance objects > is > equivalent to invoking the __call__() method. Naturally, any arguments > given in the instance call are passed as arguments to __call__()." > > as far as decorators go, kent's tutorial is great place to start. here > are 2 more articles plus PEP 318, where they were defined: > > http://www.ibm.com/developerworks/linux/library/l-cpdecor.html > http://www.artima.com/weblogs/viewpost.jsp?thread=240808 > http://www.python.org/dev/peps/pep-0318 > > in addition, i devoted section 11.3.6 of Core Python to decorators. > > finally, it should be mentioned that starting in 2.6, you can now > decorate *classes*, as seen here in PEP 3129: > > http://www.python.org/dev/peps/pep-3129/ > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tmatsumoto at gmx.net Wed Jul 15 21:19:16 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Wed, 15 Jul 2009 21:19:16 +0200 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> References: <20090715114153.32910@gmx.net> <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> Message-ID: <20090715191916.162090@gmx.net> hi kent, thanks, i read through the link but still haven't got my head around this concept. will read on. cheers, t -------- Original-Nachricht -------- > Datum: Wed, 15 Jul 2009 08:33:33 -0400 > Von: Kent Johnson > An: Todd Matsumoto > CC: tutor at python.org > Betreff: Re: [Tutor] decorators, __call__ (able) objects > On Wed, Jul 15, 2009 at 7:41 AM, Todd Matsumoto wrote: > > Hi, > > > > Can some one give, or point to some good examples of how @decorators > work, and __call__ (able) objects? > > Decorators: > http://personalpages.tds.net/~kent37/kk/00001.html > > Kent -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From ctcast at gmail.com Wed Jul 15 20:55:08 2009 From: ctcast at gmail.com (Chris Castillo) Date: Wed, 15 Jul 2009 13:55:08 -0500 Subject: [Tutor] reading complex data types from text file Message-ID: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> I'm having some trouble reading multiple data types from a single text file. say I had a file with names and numbers: bob 100 sue 250 jim 300 I have a few problems. I know how to convert the lines into an integer but I don't know how to iterate through all the lines and just get the integers and store them or iterate through the lines and just get the names and store them. please help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mindboggler12 at gmail.com Wed Jul 15 21:54:16 2009 From: mindboggler12 at gmail.com (jonathan wallis) Date: Wed, 15 Jul 2009 15:54:16 -0400 Subject: [Tutor] help Message-ID: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> i have a duel loop that looks like this while y > 0 and x > 0: i cant figure out if there is a way to make so if one loop ends it says something different than if the other loop ends. -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Wed Jul 15 23:14:36 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 15 Jul 2009 23:14:36 +0200 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> Message-ID: <4A5E46BC.4060406@xs4all.nl> Chris Castillo wrote: > I don't know how to iterate through all the lines and just get the > integers and store them or iterate through the lines and just get the > names and store them. You could use the int() function to try to convert a line to an integer, and if that fails with a ValueError exception, assume that it is a name. names=[] numbers=[] for line in open("mixed.txt"): try: nr=int(line) # it's an integer numbers.append(line) except ValueError: # it's not an integer names.append(line) f=open("numbers.txt","wt") f.write("".join(numbers)) f.close() f=open("names.txt","wt") f.write("".join(names)) f.close() -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From sli1que at yahoo.com Wed Jul 15 23:10:07 2009 From: sli1que at yahoo.com (Eric Walker) Date: Wed, 15 Jul 2009 14:10:07 -0700 (PDT) Subject: [Tutor] help In-Reply-To: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> References: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> Message-ID: <839971.53884.qm@web65412.mail.ac4.yahoo.com> > >From: jonathan wallis >To: tutor at python.org >Sent: Wednesday, July 15, 2009 12:54:16 PM >Subject: [Tutor] help > >>i have a duel loop that looks like this while y > 0 and x > 0: >i cant figure out if there is a way to make so if one loop ends it says something different than if the other loop ends. this is only one loop. Are you saying you want to know if the y went to zero or the x went to zero? From motoom at xs4all.nl Wed Jul 15 23:26:42 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 15 Jul 2009 23:26:42 +0200 Subject: [Tutor] help In-Reply-To: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> References: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> Message-ID: <4A5E4992.5050103@xs4all.nl> jonathan wallis wrote: > i cant figure out if there is a way to make so if one loop ends it says > something different than if the other loop ends. Maybe you could use two separate tests and break out of the loop if x or y gets too low. Because the tests are separated you could say something different for each case. For example: import random x=y=9 while True: print "x is %d, y is %d" % (x,y) if x<=0: print "Loop stopped because X was too low" break if y<=0: print "Loop stopped because Y was too low" break # do something with x and y if random.random()>0.5: x-=1 else: y-=1 -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From bgailer at gmail.com Wed Jul 15 23:38:42 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 15 Jul 2009 17:38:42 -0400 Subject: [Tutor] objects becoming pointers In-Reply-To: References: <4A5DF8A9.1010105@gmail.com> Message-ID: <4A5E4C62.50209@gmail.com> Please always reply-all so a copy goes to the list. chris Hynes wrote: > Ah, there you go, that's what I want to do, dynamically create > variable names. Then I could interactively create as many arrays as I > want to, say Chris1, Chris2, Chris3 and each of these would be > different array with different results. > > But based on what you showed me I'm going to have to at least type: > > print names["Chris"] > > as opposed to just typing: > > print Chris True. As others have pointed out you may use exec to dynamically create variables. Most Python applications pretty quickly evolve beyond simple command line interfaces. At that point dealing with dynamically created names becomes a pain. With a little finessing you can create a class instance with attributes that are names such as Chris. Then you could >>> print c.Chris -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Thu Jul 16 04:23:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Jul 2009 22:23:34 -0400 Subject: [Tutor] objects becoming pointers In-Reply-To: <4A5E4C62.50209@gmail.com> References: <4A5DF8A9.1010105@gmail.com> <4A5E4C62.50209@gmail.com> Message-ID: <1c2a2c590907151923l6a089694q922d6f3ff99caaea@mail.gmail.com> > chris Hynes wrote: >> >> Ah, there you go, that's what I want to do, dynamically create variable >> names. Then I could interactively create as many arrays as I want to, say >> Chris1, Chris2, Chris3 and each of these would be different array with >> different results. >> >> But based on what you showed me I'm going to have to at least type: >> >> print names["Chris"] >> >> as opposed to just typing: >> >> print Chris I'm not sure you have really thought this through. The user typed "Chris", and that value is stored in 'name'. It might just as well have been "Bob" or "Kent". So you can't really say print Chris you need something like print the_thing_called(name) which you might as well spell as print values[name] Kent From eduardo.susan at gmail.com Thu Jul 16 04:33:13 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 15 Jul 2009 20:33:13 -0600 Subject: [Tutor] Can't transform a list of tokens into a text Message-ID: <9356b9f30907151933q64799096we74c0e03a890dc00@mail.gmail.com> Hello, I have a file that was a resulted from a POS-Tagging program, after some transformations, I wanted to restore to it's normal form. So, I used sed to remove the POS-Tags and have something like this: --- Example begins No , thanks.+ at + # this + at + I inserted to mark paragraphs, because the POS-Tagger don't keep paragraph marks He said , " No , thanks . " OK ? --- Example ends --- And I want to transform into this: No, thanks. He said, "No, thanks." OK? --- End example I tried different approaches, and dealing with the quote marks is what is defeating my attempts: I had originally this code: import cStringIO ##import string myoutput = cStringIO.StringIO() f = open(r'C:\mytools\supersed\tradunew.txt') lista = [line.strip() for line in f] punct = '!#$%)*,-.:;<=>?@/\\]^_`}~??' for i, item in enumerate(lista): if item == '"' and lista[i + 1] not in punct: myoutput.write(item) spacer = True elif '+ at +' in item: donewline = item.replace('+ at +','\n ') myoutput.write(donewline) elif item not in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item not in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item in '([{?': myoutput.write(item) else: myoutput.write(item + " ") newlist = myoutput.getvalue().splitlines() myoutput.close() f = open(r'C:\mytools\supersed\traducerto-k.txt', 'w') for line in newlist: f.write(line.lstrip()+'\n') f.close() #=== I tried this version to post in this forum but that gives me an error. I don't know why I don't get an error with the code above which is essentially the same: # -*- coding: cp1252 -*- result = '' lista = [ 'No', ',', 'thanks.+ at +', 'He', 'said', ',', '"', 'no', ',', 'thanks', '.', '"', 'OK', '?', 'Hi'] punct = '!#$%)*,-.:;<=>?@/\\]^_`}~??' for i, item in enumerate(lista): if item == '"' and lista[i + 1] not in punct: result +=item spacer = True elif '+ at +' in item: donewline = item.replace('+ at +','\n ') result += donewline elif item not in punct and lista[i + 1] in punct: result += item elif item in punct and lista[i + 1] in punct: result += item elif item in punct and lista[i + 1] == '"' and spacer: result += item spacer = False elif item not in punct and lista[i + 1] == '"' and spacer: result += item spacer = False elif item in '([{?': result += item else: result += (item + " ") print result #== The error is this: Traceback (most recent call last): File "", line 244, in run_nodebug File "C:\mytools\jointags-v4.py", line 17, in elif item not in punct and lista[i + 1] in punct: IndexError: list index out of range I'm using python 2.6.2 with PyScripter IDE I have tried a so many variations that I'm not sure what I'm doing any more.... I'm just trying to avoid some post-processing with sed again. Thankful, Eduardo From roadierich at googlemail.com Thu Jul 16 04:34:48 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 16 Jul 2009 03:34:48 +0100 Subject: [Tutor] Fwd: The why In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: chris Hynes Date: 2009/7/15 Subject: The why To: roadierich at googlemail.com Well, I'm trying to create an interactive program, let's say I'm running the program, I ask the user to give the array a name, I then do some computations and store the results in that array. While I'm still running the program I might decide to create several more arrays of the same type/dimension with names of my choosing same types of computation. When I'm done, I might have several arrays created, all with different names that I have given them. In the ipython mode I could call up any of these arrays off and on again as I want to visually compare them to each other. I mean I guess what I could do is go back to my code, name the array Chris, let a calculation use x=2, save, run the program, go back in to the code, edit it so that the array is named Bob along with changing x=3, save, run the program a second time. When I'm done I'll now have two arrays, one named Chris the other Bob with different results because I changed some other input paramenters. I just now thought of maybe making one huge array, storing all the results of x=2 and use a conditional satement like if x=2, then name was Chris. But it would be so much easier if I could type print Chris or print Bob and it woulds spit out what those arrays were. > From: roadierich at googlemail.com > Date: Wed, 15 Jul 2009 16:33:00 +0100 > Subject: Re: [Tutor] objects becoming pointers > To: cjhynes36 at hotmail.com > CC: tutor at python.org > > 2009/7/15 chris Hynes : > > I guess I have to start somewhere to ask............ > > > > I want the user to input a name, say "Chris". I know I can use the code: > > > > name=raw_input() > > > > I now want: > > > > "Chris"=zeros((3,3)) > > > > so that when I type: > > > > print Chris > > > > the return will be an array of zero's 3x3 > > > > So that I can understand this deeper, I know that "name" is just a pointer > > to the object "Chris". I don't want to just change the pointer to something > > else, like "zeros((3,3))" but I want to make "Chris" become the pointer or > > the name of the pointer. At least that's what I think I want. > > > > ________________________________ > > Windows Live? SkyDrive?: Get 25 GB of free online storage. Get it on your > > BlackBerry or iPhone. > > _______________________________________________ > > Tutor maillist ?- ?Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > Sorry if I've sent this twice... > > Why would you want to do that? > > The closest you can get to that is using exec, but exec is usually > considered a code smell. I'd say you're trying to do the wrong thing. > > -- > Rich "Roadie Rich" Lovely > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. ________________________________ Windows Live?: Keep your life in sync. Check it out. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From ali.jan at gmail.com Thu Jul 16 05:34:08 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Thu, 16 Jul 2009 09:34:08 +0600 Subject: [Tutor] Can't transform a list of tokens into a text In-Reply-To: <9356b9f30907151933q64799096we74c0e03a890dc00@mail.gmail.com> References: <9356b9f30907151933q64799096we74c0e03a890dc00@mail.gmail.com> Message-ID: <8acb5ef80907152034i56f6baeaqc6e7f6da7d919650@mail.gmail.com> Try changing all instances of list[i + 1] to list[i] On Thu, Jul 16, 2009 at 8:33 AM, Eduardo Vieira wrote: > #=== > I tried this version to post in this forum but that gives me an error. > I don't know why I don't get an error with the code above which is > essentially the same: > # -*- coding: cp1252 -*- > > result = '' > lista = [ > 'No', ',', 'thanks.+ at +', > 'He', 'said', ',', '"', 'no', ',', 'thanks', '.', '"', 'OK', '?', 'Hi'] > > punct = '!#$%)*,-.:;<=>?@/\\]^_`}~??' > for i, item in enumerate(lista): > > if item == '"' and lista[i + 1] not in punct: > result +=item > spacer = True > elif '+ at +' in item: > donewline = item.replace('+ at +','\n ') > result += donewline > elif item not in punct and lista[i + 1] in punct: > result += item > elif item in punct and lista[i + 1] in punct: > result += item > elif item in punct and lista[i + 1] == '"' and spacer: > result += item > spacer = False > elif item not in punct and lista[i + 1] == '"' and spacer: > result += item > spacer = False > elif item in '([{?': > result += item > else: > result += (item + " ") > > print result > > #== > The error is this: > Traceback (most recent call last): > File "", line 244, in run_nodebug > File "C:\mytools\jointags-v4.py", line 17, in > elif item not in punct and lista[i + 1] in punct: > IndexError: list index out of range > > I'm using python 2.6.2 with PyScripter IDE > I have tried a so many variations that I'm not sure what I'm doing any > more.... > I'm just trying to avoid some post-processing with sed again. > > Thankful, > > Eduardo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- http://alitechtips.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Jul 16 08:08:49 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 16 Jul 2009 08:08:49 +0200 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> Message-ID: <4A5EC3F1.7030406@compuscan.co.za> Chris Castillo wrote: > I'm having some trouble reading multiple data types from a single text > file. > > say I had a file with names and numbers: > > bob > 100 > sue > 250 > jim > 300 > > I have a few problems. I know how to convert the lines into an integer > but I don't know how to iterate through all the lines and just get the > integers and store them or iterate through the lines and just get the > names and store them. > > please help. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You could do it with a list comprehension >>> names = [] >>> numbers = [] >>> [numbers.append(int(line.strip())) if line.strip().isdigit() else names.append(line.strip()) for line in open('test.txt','rb') if line.strip()] [None, None, None, None, None, None] >>> names, numbers (['bob', 'sue', 'jim'], [100, 250, 300]) The list comprehension would unfold to for line in open('test.txt', 'rb'): if line.strip(): if line.strip().isdigit(): numbers.append(line.strip()) else: names.append(line.strip()) And from there you can do what you like with the lists. -- Kind Regards, Christian Witts From johan at accesstel.com.au Thu Jul 16 07:56:39 2009 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Thu, 16 Jul 2009 15:56:39 +1000 Subject: [Tutor] XML: changing value of elements In-Reply-To: References: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> Message-ID: <001101ca05da$32052d90$960f88b0$@com.au> I have another question about writing the xml tree to a file. Now, I have parsed and changed my xml tree, but I want to create the same tree multiple times with different values and write it to one file. Let's use this code: import xml.etree.ElementTree as ET doc = ET.parse('signal1.xml') signal_node = doc.getroot()[0] signal_node.set('name', 'Test_Name') I have this in a function and it returns the signal_node everytime I call it, but with a different values. So, How do I take the returned xml and write that to one xml file? Thanks Johan -----Original Message----- From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Stefan Behnel Sent: Thursday, June 11, 2009 4:37 PM To: tutor at python.org Subject: Re: [Tutor] XML: changing value of elements Hi, it's funny how many times I see Python users go: "I have an XML problem, so I'll use minidom." Because then they have two problems. Johan Geldenhuys wrote: > I have a rather complex XML file and I need to change some values inside > this file. > > So far I have been using minidom, but I can't find the thing I am looking > for. > > My code so far: > """ > from xml.dom import minidom > > xmlFile = 'signal1.xml' > xmlDocument = minidom.parse(xmlFile) > > SignalsNode = xmlDocument.firstChild > signalNode = SignalsNode.childNodes[1] > > signalNode.removeAttribute("name") > signalNode.setAttribute("name", "Test_Name") > signalNode.getAttribute("name") > > descElem = signalNode.childNodes[1] That is a lot of code just to say import xml.etree.ElementTree as ET doc = ET.parse('signal1.xml') signal_node = doc.getroot()[0] signal_node.set('name', 'Test_Name') > I know how to manipulate the value of the attributes, but I can't seem to > change the values of eg: "Description" description = signal_node[0] description.text = "New value" > Snippet from my XML file: > > """ > > > > - What's that "" bit? > - name="Model_X" type="Flyer"> > > Some description > > Model_X > > > > - > > normal > > Model X 1 > > > > - type="close"> > > minor > > Model X 2 > > > > > > > """ Stefan _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor No virus found in this incoming message. Checked by AVG - http://www.avg.com Version: 8.0.138 / Virus Database: 270.12.93/2206 - Release Date: 6/27/2009 5:55 PM From tmatsumoto at gmx.net Thu Jul 16 08:09:52 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Thu, 16 Jul 2009 08:09:52 +0200 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <78b3a9580907151202p7ec9a45bm14a4c3b043b7d989@mail.gmail.com> References: <20090715114153.32910@gmx.net> <1c2a2c590907150533j1f89d5edwaebeb331ca97bb3a@mail.gmail.com> <1e53c510907150720i5475bff7g4b7e4e24f8810e04@mail.gmail.com> <1e53c510907150722k374d1881l69bfc1069b423629@mail.gmail.com> <78b3a9580907151202p7ec9a45bm14a4c3b043b7d989@mail.gmail.com> Message-ID: <20090716060952.89850@gmx.net> Thanks guys, In the example the __call__ method has *args and **kws as arguments. Is that required? Also when, in what situation would you use callable objects? Cheers, T -------- Original-Nachricht -------- > Datum: Wed, 15 Jul 2009 12:02:05 -0700 > Von: wesley chun > An: vince spicer , tmatsumoto at gmx.net > CC: Kent Johnson , tutor at python.org > Betreff: Re: [Tutor] decorators, __call__ (able) objects > >>> > Can some one give, or point to some good examples of how @decorators > >>> > work, and __call__ (able) objects? > > > > simple example of calling a class > > > > class myKlass(object): > > > > def __call__(self, *args, **kws): > > print "i was called" > > > > >>> test = myKlass() > > >>> test() > > i was called > > > close. the example was right, but the description wasn't accurate... > you meant, "calling an instance." i'm going to plagarize and rip this > right out of section 14.1.4 from "Core Python Programming:" > > "Python provides the __call__() special method for classes, which allows a > programmer to create objects (instances) that are callable. By default, > the > __call__() method is not implemented, meaning that most instances are > not callable. However, if this method is overridden in a class > de?nition, > instances of such a class are made callable. Calling such instance objects > is > equivalent to invoking the __call__() method. Naturally, any arguments > given in the instance call are passed as arguments to __call__()." > > as far as decorators go, kent's tutorial is great place to start. here > are 2 more articles plus PEP 318, where they were defined: > > http://www.ibm.com/developerworks/linux/library/l-cpdecor.html > http://www.artima.com/weblogs/viewpost.jsp?thread=240808 > http://www.python.org/dev/peps/pep-0318 > > in addition, i devoted section 11.3.6 of Core Python to decorators. > > finally, it should be mentioned that starting in 2.6, you can now > decorate *classes*, as seen here in PEP 3129: > > http://www.python.org/dev/peps/pep-3129/ > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser From vinces1979 at gmail.com Thu Jul 16 08:28:50 2009 From: vinces1979 at gmail.com (Vince Spicer) Date: Thu, 16 Jul 2009 00:28:50 -0600 Subject: [Tutor] decorators, __call__ (able) objects In-Reply-To: <20090716060952.89850@gmx.net> References: <20090715114153.32910@gmx.net> <78b3a9580907151202p7ec9a45bm14a4c3b043b7d989@mail.gmail.com> <20090716060952.89850@gmx.net> Message-ID: <200907160028.50789.vinces1979@gmail.com> no the __call__ function can is like any function def __call__(self, passedin): or simply def __call__(self) *args and **kws explained > http://www.saltycrane.com/blog/2008/01/how-to- use-args-and-kwargs-in-python/ On Thursday 16 July 2009 12:09:52 am Todd Matsumoto wrote: > Thanks guys, > > In the example the __call__ method has *args and **kws as arguments. Is > that required? > > Also when, in what situation would you use callable objects? > > Cheers, > > T > -------- Original-Nachricht -------- > > > Datum: Wed, 15 Jul 2009 12:02:05 -0700 > > Von: wesley chun > > An: vince spicer , tmatsumoto at gmx.net > > CC: Kent Johnson , tutor at python.org > > Betreff: Re: [Tutor] decorators, __call__ (able) objects > > > > >>> > Can some one give, or point to some good examples of how > > >>> > @decorators work, and __call__ (able) objects? > > > > > > simple example of calling a class > > > > > > class myKlass(object): > > > > > > def __call__(self, *args, **kws): > > > print "i was called" > > > > > > >>> test = myKlass() > > > >>> test() > > > > > > i was called > > > > close. the example was right, but the description wasn't accurate... > > you meant, "calling an instance." i'm going to plagarize and rip this > > right out of section 14.1.4 from "Core Python Programming:" > > > > "Python provides the __call__() special method for classes, which allows > > a programmer to create objects (instances) that are callable. By default, > > the > > __call__() method is not implemented, meaning that most instances are > > not callable. However, if this method is overridden in a class > > de?nition, > > instances of such a class are made callable. Calling such instance > > objects is > > equivalent to invoking the __call__() method. Naturally, any arguments > > given in the instance call are passed as arguments to __call__()." > > > > as far as decorators go, kent's tutorial is great place to start. here > > are 2 more articles plus PEP 318, where they were defined: > > > > http://www.ibm.com/developerworks/linux/library/l-cpdecor.html > > http://www.artima.com/weblogs/viewpost.jsp?thread=240808 > > http://www.python.org/dev/peps/pep-0318 > > > > in addition, i devoted section 11.3.6 of Core Python to decorators. > > > > finally, it should be mentioned that starting in 2.6, you can now > > decorate *classes*, as seen here in PEP 3129: > > > > http://www.python.org/dev/peps/pep-3129/ > > > > hope this helps! > > -- wesley > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > > "Core Python Programming", Prentice Hall, (c)2007,2001 > > "Python Fundamentals", Prentice Hall, (c)2009 > > http://corepython.com > > > > wesley.j.chun :: wescpy-at-gmail.com > > python training and technical consulting > > cyberweb.consulting : silicon valley, ca > > http://cyberwebconsulting.com From rabidpoobear at gmail.com Thu Jul 16 09:18:18 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 16 Jul 2009 02:18:18 -0500 Subject: [Tutor] Fwd: The why In-Reply-To: References: Message-ID: You need to read what dictionaries are. Essentially, any time you think "oh I need to keep separate variables for these values, but I won't know what their names are until runtime!" the correct answer is to not try to manipulate them into variables, but to use them as dictionary keys, or organize them into some other data structure that you can recall later. Quick example: x = {} import random while 1: name = raw_input("Name? ") if name.strip() == 'quit': break x[name] = random.randrange(100) print x >>> Name? bob Name? jack Name? thomas Name? quit {'thomas': 39, 'bob': 69, 'jack': 42} On Wed, Jul 15, 2009 at 9:34 PM, Rich Lovely wrote: > ---------- Forwarded message ---------- > From: chris Hynes > Date: 2009/7/15 > Subject: The why > To: roadierich at googlemail.com > > > Well, I'm trying to create an interactive program, let's say I'm > running the program, I ask the user to give the array a name, I then > do some computations and store the results in that array. While I'm > still running the program I might decide to create several more arrays > of the same type/dimension with names of my choosing same types of > computation. When I'm done, I might have several arrays created, all > with different names that I have given them. In the ipython mode I > could call up any of these arrays off and on again as I want to > visually compare them to each other. > > I mean I guess what I could do is go back to my code, name the array > Chris, let a calculation use x=2, save, run the program, go back in to > the code, edit it so that the array is named Bob along with changing > x=3, save, run the program a second time. When I'm done I'll now have > two arrays, one named Chris the other Bob with different results > because I changed some other input paramenters. > > I just now thought of maybe making one huge array, storing all the > results of x=2 and use a conditional satement like if x=2, then name > was Chris. But it would be so much easier if I could type print Chris > or print Bob and it woulds spit out what those arrays were. > >> From: roadierich at googlemail.com >> Date: Wed, 15 Jul 2009 16:33:00 +0100 >> Subject: Re: [Tutor] objects becoming pointers >> To: cjhynes36 at hotmail.com >> CC: tutor at python.org >> >> 2009/7/15 chris Hynes : >> > I guess I have to start somewhere to ask............ >> > >> > I want the user to input a name, say "Chris". I know I can use the code: >> > >> > name=raw_input() >> > >> > I now want: >> > >> > "Chris"=zeros((3,3)) >> > >> > so that when I type: >> > >> > print Chris >> > >> > the return will be an array of zero's 3x3 >> > >> > So that I can understand this deeper, I know that "name" is just a pointer >> > to the object "Chris". I don't want to just change the pointer to something >> > else, like "zeros((3,3))" but I want to make "Chris" become the pointer or >> > the name of the pointer. At least that's what I think I want. >> > >> > ________________________________ >> > Windows Live? SkyDrive?: Get 25 GB of free online storage. Get it on your >> > BlackBerry or iPhone. >> > _______________________________________________ >> > Tutor maillist ?- ?Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> > >> >> Sorry if I've sent this twice... >> >> Why would you want to do that? >> >> The closest you can get to that is using exec, but exec is usually >> considered a code smell. I'd say you're trying to do the wrong thing. >> >> -- >> Rich "Roadie Rich" Lovely >> There are 10 types of people in the world: those who know binary, >> those who do not, and those who are off by one. > > ________________________________ > Windows Live?: Keep your life in sync. Check it out. > > > -- > Rich "Roadie Rich" Lovely > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From srilyk at gmail.com Thu Jul 16 10:29:49 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 16 Jul 2009 03:29:49 -0500 Subject: [Tutor] Replace a character by index Message-ID: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> Hi, My question is more about style/timing than anything else. In my program I'm taking a word and generating "blanks" in that word. For example, the word cat could generate: _at c_t ca_ I have two different ways I can put _ in the word: word = 'cat' ''.join(list(word)[1] = '_') and # I'm not using a constant, but randomly generating where the blank appears word[:1] + '_' + word[1+1:] So, when I use the timeit module I get these results: In [78]: timeit.Timer("''.join(list('foo'))").timeit() Out[78]: 2.9940109252929688 In [80]: timeit.Timer("'foo'[:2]+'_'+'foo'[2+1:]").timeit() Out[80]: 0.63733291625976562 Quite a significant difference. So my question(s): Which method should I use/is more pythonic? Which method do you/have you used? And the ubiquitous 'Why?' Normally I would lean towards the first method because reassigning a value in a list seems more natural than string concatenation. In this particular application I'm not exactly worried about performance - on even an archaic computer I don't think one would notice. TIA for your input, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Thu Jul 16 11:06:52 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 16 Jul 2009 11:06:52 +0200 Subject: [Tutor] Replace a character by index In-Reply-To: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> References: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> Message-ID: <4A5EEDAC.2040005@compuscan.co.za> Wayne wrote: > Hi, > > My question is more about style/timing than anything else. > > In my program I'm taking a word and generating "blanks" in that word. > For example, the word cat could generate: > _at > c_t > ca_ > > I have two different ways I can put _ in the word: > word = 'cat' > > ''.join(list(word)[1] = '_') > > and > > # I'm not using a constant, but randomly generating where the blank > appears > word[:1] + '_' + word[1+1:] > > So, when I use the timeit module I get these results: > > In [78]: timeit.Timer("''.join(list('foo'))").timeit() > Out[78]: 2.9940109252929688 > > In [80]: timeit.Timer("'foo'[:2]+'_'+'foo'[2+1:]").timeit() > Out[80]: 0.63733291625976562 > > Quite a significant difference. > > So my question(s): Which method should I use/is more pythonic? Which > method do you/have you used? And the ubiquitous 'Why?' > > Normally I would lean towards the first method because reassigning a > value in a list seems more natural than string concatenation. In this > particular application I'm not exactly worried about performance - on > even an archaic computer I don't think one would notice. > > TIA for your input, > Wayne > -- > To be considered stupid and to be told so is more painful than being > called gluttonous, mendacious, violent, lascivious, lazy, cowardly: > every weakness, every vice, has found its defenders, its rhetoric, its > ennoblement and exaltation, but stupidity hasn?t. - Primo Levi > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Strings are essentially a list already of characters. What would be slowing down your preferred method #1 would be your explicit cast to a list and then re-joining that list. Strings support item assignment so you can save quite a few cycles just doing word = 'cat' word[1] = '_' which would result in word printing 'c_t'. I'm assuming your use case would be just a call to random with bounds zero -> length of string - 1 and then using that index to replace the character with an underscore and it is much simpler and faster to just use the strings build in index and item assignment. Hope that helps. -- Kind Regards, Christian Witts From cwitts at compuscan.co.za Thu Jul 16 11:12:05 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 16 Jul 2009 11:12:05 +0200 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907160132l2ebebd46o6815f5bd91b6cefb@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <4A5EC3F1.7030406@compuscan.co.za> <50e459210907160132l2ebebd46o6815f5bd91b6cefb@mail.gmail.com> Message-ID: <4A5EEEE5.9090104@compuscan.co.za> Chris Castillo wrote: > why does your 3rd and fourth lines have brackets? > > On Thu, Jul 16, 2009 at 1:08 AM, Christian Witts > > wrote: > > Chris Castillo wrote: > > I'm having some trouble reading multiple data types from a > single text file. > > say I had a file with names and numbers: > > bob > 100 > sue > 250 > jim > 300 > > I have a few problems. I know how to convert the lines into an > integer but I don't know how to iterate through all the lines > and just get the integers and store them or iterate through > the lines and just get the names and store them. > > please help. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > You could do it with a list comprehension > > >>> names = [] > >>> numbers = [] > >>> [numbers.append(int(line.strip())) if line.strip().isdigit() > else names.append(line.strip()) for line in open('test.txt','rb') > if line.strip()] > [None, None, None, None, None, None] > >>> names, numbers > (['bob', 'sue', 'jim'], [100, 250, 300]) > > The list comprehension would unfold to > > for line in open('test.txt', 'rb'): > if line.strip(): > if line.strip().isdigit(): > numbers.append(line.strip()) > else: > names.append(line.strip()) > > And from there you can do what you like with the lists. > > -- > Kind Regards, > Christian Witts > > > >>> [numbers.append(int(line.strip())) if line.strip().isdigit() else names.append(line.strip()) for line in open('test.txt','rb') if line.strip()] [None, None, None, None, None, None] Are you referring to these lines ? If so, the reason is that for Python to recognize it as a list comprehension it needs to be wrapped in square brackets, if you were to use () instead to wrap around it it would become a generator expression (something which is incredibly powerful for larger amounts of data as it iterates when it needs to instead of pre-building everything. And the following line with the Nones on is because that is the output of the calls to .append. Normally you wouldn't see it in your application though. -- Kind Regards, Christian Witts From cwitts at compuscan.co.za Thu Jul 16 11:32:01 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 16 Jul 2009 11:32:01 +0200 Subject: [Tutor] Replace a character by index In-Reply-To: <333efb450907160200p54ca27a7r422333c353a9ea3@mail.gmail.com> References: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> <4A5EEDAC.2040005@compuscan.co.za> <333efb450907160200p54ca27a7r422333c353a9ea3@mail.gmail.com> Message-ID: <4A5EF391.1050001@compuscan.co.za> Wayne wrote: > On Thu, Jul 16, 2009 at 4:06 AM, Christian Witts > > wrote: > > > > Strings are essentially a list already of characters. What would > be slowing down your preferred method #1 would be your explicit > cast to a list and then re-joining that list. Strings support > item assignment so you can save quite a few cycles just doing > > word = 'cat' > word[1] = '_' > > > Not in python they don't! > In [97]: word[1]='_' > --------------------------------------------------------------------------- > TypeError Traceback (most recent call > last) > > /home/wayne/programming/python/sight_words/ in () > > TypeError: 'str' object does not support item assignment > > But of course I already knew that from experience :-P > > -Wayne > Whoops, early morning, lack of coffee, some deadlines on my head to blame for that. :p Rebuilding strings would be faster using concatenation than casting to list and joining, it is the method I prefer when cutting things out. I also find it looks neater and is easier to read. Also '%s%s%s' % (a[:idx], '_', a[idx+1:]) would be preferred over a[:idx] + '_' + a[idx+1:] -- Kind Regards, Christian Witts From gregor.lingl at aon.at Thu Jul 16 11:22:35 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Thu, 16 Jul 2009 11:22:35 +0200 Subject: [Tutor] Replace a character by index In-Reply-To: <4A5EEDAC.2040005@compuscan.co.za> References: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> <4A5EEDAC.2040005@compuscan.co.za> Message-ID: <4A5EF15B.3010803@aon.at> Christian Witts schrieb: > Wayne wrote: >> Hi, >> ... >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > Strings are essentially a list already of characters. What would be > slowing down your preferred method #1 would be your explicit cast to a > list and then re-joining that list. Strings support item assignment > so you can save quite a few cycles just doing > > word = 'cat' > word[1] = '_' > > which would result in word printing 'c_t'. That's simply not true in Python. Try it out! >>> word = "cat" >>> word[1] = "_" Traceback (most recent call last): File "", line 1, in word[1] = "_" TypeError: 'str' object does not support item assignment >>> Gregor > I'm assuming your use case would be just a call to random with bounds > zero -> length of string - 1 and then using that index to replace the > character with an underscore and it is much simpler and faster to just > use the strings build in index and item assignment. > > Hope that helps. > From stefan_ml at behnel.de Thu Jul 16 11:23:25 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 16 Jul 2009 11:23:25 +0200 Subject: [Tutor] XML: changing value of elements In-Reply-To: <001101ca05da$32052d90$960f88b0$@com.au> References: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> <001101ca05da$32052d90$960f88b0$@com.au> Message-ID: Hi, a new question usually merits a new thread. Especially after a longer time, replies to older threads tend to remain unread as people simply don't scroll down far enough to notice them. You were lucky. :) Johan Geldenhuys wrote: > I have another question about writing the xml tree to a file. > > Now, I have parsed and changed my xml tree, but I want to create the same > tree multiple times with different values and write it to one file. > > > Let's use this code: > > import xml.etree.ElementTree as ET > doc = ET.parse('signal1.xml') > signal_node = doc.getroot()[0] > signal_node.set('name', 'Test_Name') > > I have this in a function and it returns the signal_node everytime I call > it, but with a different values. > > So, How do I take the returned xml and write that to one xml file? I'm not sure what you mean here. Do you mean: "multiple XML trees into a single file"? Or each in its own file? BTW, you don't need to re-parse the tree if all you want is to modify it and write it back out. You can either keep changing the tree and write it out multiple times, or deep-copy it (or parts of it) and start over for each step. Although I guess that parsing might be faster than deep-copying, especially for ElementTree. Stefan From cwitts at compuscan.co.za Thu Jul 16 11:51:29 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 16 Jul 2009 11:51:29 +0200 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907160225w3b49430dy1e853e24e461b38@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <4A5EC3F1.7030406@compuscan.co.za> <50e459210907160132l2ebebd46o6815f5bd91b6cefb@mail.gmail.com> <4A5EEEE5.9090104@compuscan.co.za> <50e459210907160225w3b49430dy1e853e24e461b38@mail.gmail.com> Message-ID: <4A5EF821.2090800@compuscan.co.za> Chris Castillo wrote: > Oh okay. gotcha. > so I have what I want basically. I just need to check to see if each > number meets a certain criteria and output something like the > following to a text file. Should I be going about this a different way > or should I still use lists? > > bob below average > sue above average > jim perfect > > > > On Thu, Jul 16, 2009 at 4:12 AM, Christian Witts > > wrote: > > Chris Castillo wrote: > > why does your 3rd and fourth lines have brackets? > > On Thu, Jul 16, 2009 at 1:08 AM, Christian Witts > > >> wrote: > > Chris Castillo wrote: > > I'm having some trouble reading multiple data types from a > single text file. > > say I had a file with names and numbers: > > bob > 100 > sue > 250 > jim > 300 > > I have a few problems. I know how to convert the lines > into an > integer but I don't know how to iterate through all the > lines > and just get the integers and store them or iterate through > the lines and just get the names and store them. > > please help. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > You could do it with a list comprehension > > >>> names = [] > >>> numbers = [] > >>> [numbers.append(int(line.strip())) if > line.strip().isdigit() > else names.append(line.strip()) for line in > open('test.txt','rb') > if line.strip()] > [None, None, None, None, None, None] > >>> names, numbers > (['bob', 'sue', 'jim'], [100, 250, 300]) > > The list comprehension would unfold to > > for line in open('test.txt', 'rb'): > if line.strip(): > if line.strip().isdigit(): > numbers.append(line.strip()) > else: > names.append(line.strip()) > > And from there you can do what you like with the lists. > > -- Kind Regards, > Christian Witts > > > > >>> [numbers.append(int(line.strip())) if line.strip().isdigit() > else names.append(line.strip()) for line in open('test.txt','rb') > if line.strip()] > [None, None, None, None, None, None] > > Are you referring to these lines ? > If so, the reason is that for Python to recognize it as a list > comprehension it needs to be wrapped in square brackets, if you > were to use () instead to wrap around it it would become a > generator expression (something which is incredibly powerful for > larger amounts of data as it iterates when it needs to instead of > pre-building everything. And the following line with the Nones on > is because that is the output of the calls to .append. Normally > you wouldn't see it in your application though. > > -- > Kind Regards, > Christian Witts > > > Ok, I see what you want to do now. The best case for this would be to unfold it into a proper loop instead to maintain readability Name = None Number = None fOut = open('output.txt', 'wb') for line in open('test.txt', 'rb'): line = line.strip() if line: if line.isdigit(): Number = int(line) # Do whatever processing you want now else: Name = line if Name and Number: # Checks to see if Name, Number have values fOut.write('%s\t%s\r\n' % (Name, Number)) Name, Number = None, None # This is done so that you have to have a name and number # before writing to the file, it also then resets the # state of Name, Number to None before continuing fOut.close() What this will do is read in the file a line at a time, if the line is empty is continues to the next one without processing. If the line contains data it will check if it's numeric and if so populate the Number variable and if non-numeric populate the Name variable (gross assumption that it would indeed be a name and not something arbitrary like punctuation etc). Once both variables have been set that data would be written out to file for storing. -- Kind Regards, Christian Witts From stevenbird1 at gmail.com Thu Jul 16 04:38:53 2009 From: stevenbird1 at gmail.com (Steven Bird) Date: Thu, 16 Jul 2009 12:38:53 +1000 Subject: [Tutor] [nltk-users] Can't transform a list of tokens into a text In-Reply-To: <9356b9f30907151933q64799096we74c0e03a890dc00@mail.gmail.com> References: <9356b9f30907151933q64799096we74c0e03a890dc00@mail.gmail.com> Message-ID: <97e4e62e0907151938u675a9a77i18610015ff23f03e@mail.gmail.com> 2009/7/16 Eduardo Vieira : > > Hello, I have a file that was a resulted from a POS-Tagging program, > after some transformations, I wanted to restore to it's normal form. > So, I used sed to remove the POS-Tags and have something like this: Please show us some output from the POS-Tagging program (before the sed processing). -Steven Bird From andreengels at gmail.com Thu Jul 16 12:44:13 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 16 Jul 2009 12:44:13 +0200 Subject: [Tutor] Replace a character by index In-Reply-To: <4A5EF15B.3010803@aon.at> References: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> <4A5EEDAC.2040005@compuscan.co.za> <4A5EF15B.3010803@aon.at> Message-ID: <6faf39c90907160344j44899828qdf57af78e79e1349@mail.gmail.com> On Thu, Jul 16, 2009 at 11:22 AM, Gregor Lingl wrote: > That's simply not true in Python. Try it out! > >>>> word = "cat" >>>> word[1] = "_" > Traceback (most recent call last): > ?File "", line 1, in > ? word[1] = "_" > TypeError: 'str' object does not support item assignment And the reason for that, undoubtedly, is that strings are immutable. -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Thu Jul 16 12:45:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jul 2009 06:45:45 -0400 Subject: [Tutor] Fwd: The why In-Reply-To: References: Message-ID: <1c2a2c590907160345g261123c4x7c77ad099eea365a@mail.gmail.com> > From: chris Hynes > Date: 2009/7/15 > Subject: The why > To: roadierich at googlemail.com > > > Well, I'm trying to create an interactive program, let's say I'm > running the program, I ask the user to give the array a name, I then > do some computations and store the results in that array. While I'm > still running the program I might decide to create several more arrays > of the same type/dimension with names of my choosing same types of > computation. When I'm done, I might have several arrays created, all > with different names that I have given them. In the ipython mode I > could call up any of these arrays off and on again as I want to > visually compare them to each other. You could write your program as a library with functions that create your arrays. For example in myfuncs.py put: def make_zeros(): return zeros((3,3)) Then in ipython: from myfuncs import * # usually import * is discouraged but this is a reasonable use chris = make_zeros() bob = make_zeros() etc. Kent Please Reply All to reply to the list. From kent37 at tds.net Thu Jul 16 12:50:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jul 2009 06:50:31 -0400 Subject: [Tutor] Replace a character by index In-Reply-To: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> References: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> Message-ID: <1c2a2c590907160350t51f2531bjb167b192b747a248@mail.gmail.com> On Thu, Jul 16, 2009 at 4:29 AM, Wayne wrote: > Hi, > > My question is more about style/timing than anything else. > > In my program I'm taking a word and generating "blanks" in that word. For > example, the word cat could generate: > _at > c_t > ca_ > > I have two different ways I can put _ in the word: > word = 'cat' > > ''.join(list(word)[1] = '_') Not in any Python I ever used... In [1]: word = 'cat' In [2]: In [3]: ''.join(list(word)[1] = '_') ------------------------------------------------------------ File "", line 1 SyntaxError: keyword can't be an expression (, line 1) > > and > > # I'm not using a constant, but randomly generating where the blank appears > word[:1] + '_' + word[1+1:] > > So, when I use the timeit module I get these results: > > In [78]: timeit.Timer("''.join(list('foo'))").timeit() > Out[78]: 2.9940109252929688 > > In [80]: timeit.Timer("'foo'[:2]+'_'+'foo'[2+1:]").timeit() > Out[80]: 0.63733291625976562 > > Quite a significant difference. > > So my question(s): Which method should I use/is more pythonic? Which method > do you/have you used? And the ubiquitous 'Why?' Um, the second method is faster and has the advantage of working :-) Seems like a no-brainer to me! Kent From roadierich at googlemail.com Thu Jul 16 12:56:46 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 16 Jul 2009 11:56:46 +0100 Subject: [Tutor] just one question In-Reply-To: <25432.210.212.36.65.1247720486.squirrel@www.iisermohali.ac.in> References: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> <9887.210.212.36.65.1247680711.squirrel@www.iisermohali.ac.in> <25432.210.212.36.65.1247720486.squirrel@www.iisermohali.ac.in> Message-ID: 2009/7/16 : > Thanks for your help I tried your commands like:--- > > from __future__ import with_statement #only works on version 2.5 and later > from collections import defaultdict > from decimal import Decimal > > atoms = defaultdict(dict) > > with open("file1.txt") as f: > ? ?for line in f: > ? ? ? ?n, pos, ala, at, symb, weight, rad, count = line.split() > ? ? ? ?atoms[int(pos)][at] = Decimal(weight) > ? ? ? ?atomsNeeded = ("C", "CA", "CB") > > for k, v in atoms.iteritems(): > ? ?print k, "ALA C = %s CA = %s CB = %s" %tuple(v.get(a,"") for a in > atomsNeeded) > > but it is giving error like:---- > > Traceback (most recent call last): > ?File "a1.py", line 9, in > ? ?n, pos, ala, at, symb, weight, rad, count = line.split() > ValueError: need more than 0 values to unpack > > What I should do. > > > >> 2009/7/15 ?: >>> It is working but the only problem is that it is not taking the values >>> of >>> C, CA and CB from fifth column in front of them i tried in this way >>> like: >>> >>>>>> from __future__ import with_statement >>>>>> from collections import defaultdict >>>>>> from decimal import Decimal >>>>>> atoms = defaultdict(dict) >>>>>> with open("file1.txt") as f: >>> ... ? ? ?for line in f: >>> ... ? ? ? ? ?n, pos, ala, at, symb, weight, rad, count = line.split() >>> ... ? ? ? ? ?atoms[int(pos)][at] = Decimal(weight) >>> ... ? ? ? ? ?positionsNeeded = (8, 15, 21) >>> ... ? ? ? ? ?atomsNeeded = ("C", "CA", "CB") >>> ... ? ? ? ? ?for position in positionsNeeded: >>> ... ? ? ? ? ? ? ?print position, "ALA C = %s CA = %s CB = %s" % >>> tuple(atoms[position].get(a,"values[5]") for a in atomsNeeded) >>> ... >>> 8 ALA C = values[5] CA = values[5] CB = values[5] >>> 15 ALA C = values[5] CA = values[5] CB = values[5] >>> 21 ALA C = values[5] CA = values[5] CB = values[5] >>> Traceback (most recent call last): >>> ?File "", line 3, in >>> ValueError: need more than 0 values to unpack >>> >>> I want that whatever be the corresponding value of C,CA and CB is there >>> in >>> 5th column it will write that, and one more thing that the input file i >>> am >>> having is very big so i can't its 5th column values, but position it >>> should mention >>> >>> so if my file is something like this:--- >>> >>> Amrita Kumari >>> Research Fellow >>> IISER Mohali >>> Chandigarh >>> INDIA >>> >>> >> >> So what you're saying, (I think) is you don't want to have the >> positionsNeeded line. >> >> The problem with the code you tried, is that you've got the last for >> loop indented, whereas it wasn't in my code. ?You have also changed "" >> into "values[5]", and you wonder why it's appearing in your output? >> >> Change the final for loop to the following, and it will do what I >> think you want it to do. >> >> for k, v in atoms.iteritems(): >> ? ? print k, "ALA C = %s CA = %s CB = %s" %tuple(v.get(a,"") for a in >> atomsNeeded) >> >> Make sure it is at the left hand margin, with no spaces before the "for". >> >> Otherwise, think carefully about what you want your program to do, and >> how you can explain it, because I'm not sure anyone here really knows >> what you want your code to do. >> >> Also, please don't fill up the email with any more examples of input >> and output. ?We've seen it three times now, I think we know what it >> should look like in that sense. >> >> -- >> Rich "Roadie Rich" Lovely >> There are 10 types of people in the world: those who know binary, >> those who do not, and those who are off by one. >> > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > That sounds like there is a blank line in the input file. Therefire it should be safe to catch the exception and ignore it. Change the top of the with/for blocks as follows: with open("file1.txt") as f: for line in f: try: n, pos, ala, at, symb, weight, rad, count = line.split() except ValueError: continue else: atoms[int(pos)][at] = Decimal(weight) -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From roadierich at googlemail.com Thu Jul 16 14:18:33 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Thu, 16 Jul 2009 13:18:33 +0100 Subject: [Tutor] just one question In-Reply-To: <17854.210.212.36.65.1247745207.squirrel@www.iisermohali.ac.in> References: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> <9887.210.212.36.65.1247680711.squirrel@www.iisermohali.ac.in> <25432.210.212.36.65.1247720486.squirrel@www.iisermohali.ac.in> <17854.210.212.36.65.1247745207.squirrel@www.iisermohali.ac.in> Message-ID: Please use reply-all, so that emails go to the list as well. 2009/7/16 : > Thankyou for help it is working and giving the result but the only problem > is that it is making a very big file as it is searching for each position > of ALA and first writting its C value then CA then CB like that, is it > possible that it will do all these things but in the output it will give > only the possible of C, CA and CB for each position of ALA:.. > > Like instead of giving all these:--- > > 23 ALA C = ?CA = ?CB = > 21 ALA C = 179.35 CA = 54.33 CB = 17.87 > 15 ALA C = 177.18 CA = 52.18 CB = 20.64 > 8 ALA C = 179.39 CA = 54.67 CB = 18.85 > 23 ALA C = ?CA = ?CB = > 21 ALA C = 179.35 CA = 54.33 CB = 17.87 > ..... > > it will only give:---- > > 8 ALA C = 179.39 CA = 54.67 CB = 18.85 > 15 ALA C = 177.18 CA = 52.18 CB = 20.64 > 21 ALA C = 179.35 CA = 54.33 CB = 17.87 > 23 ALA C = 179.93 CA = 55.84 CB = 17.55 > 33 ALA C = 179.24 CA = 55.58 CB = 19.75 > 38 ALA C = 178.95 CA = 54.33 CB = 18.30 > > > Thanks, > Amrita > > > > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > Either you're not entering the code correctly, or the input file is different to what you've shown us so far. I think you need to send me a copy of the input file - or at least a larger sample than we've had so far so we can see what we're dealing with. The code should be: from __future__ import with_statement from collections import defaultdict from decimal import Decimal atoms = defaultdict(dict) with open("file1.txt") as f: for line in f: try: n, pos, ala, at, symb, weight, rad, count = line.split() except ValueError: continue else: atoms[int(pos)][at] = Decimal(weight) #modify these lines to fit your needs: positionsNeeded = (8, 15, 21) atomsNeeded = ("C", "CA", "CB") for k, v in atoms.iteritems(): print k, "ALA C = %s CA = %s CB = %s" % tuple(v.get(a,"") for a in atomsNeeded) Check you've got the indentation (the spaces at the start of lines) correct, exactly how it is above: this is VERY important in python. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From srilyk at gmail.com Thu Jul 16 14:45:14 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 16 Jul 2009 07:45:14 -0500 Subject: [Tutor] Replace a character by index In-Reply-To: <1c2a2c590907160350t51f2531bjb167b192b747a248@mail.gmail.com> References: <333efb450907160129p2e89b8c7k4027bcdaa9bdb238@mail.gmail.com> <1c2a2c590907160350t51f2531bjb167b192b747a248@mail.gmail.com> Message-ID: <333efb450907160545n4d78a8f3s2c35753bd2da6569@mail.gmail.com> On Thu, Jul 16, 2009 at 5:50 AM, Kent Johnson wrote: > On Thu, Jul 16, 2009 at 4:29 AM, Wayne wrote:> I have > two different ways I can put _ in the word: > > word = 'cat' > > > > ''.join(list(word)[1] = '_') > > Not in any Python I ever used... > In [1]: word = 'cat' > > In [2]: > > In [3]: ''.join(list(word)[1] = '_') > ------------------------------------------------------------ > File "", line 1 > SyntaxError: keyword can't be an expression (, line 1) > Um, the second method is faster and has the advantage of working :-) whoops! What I meant to say was something a bit more like: word = list(word) word[1] = '_' word = ''.join(word) But that's a bit harder to put in a timer so I just used ''.join(list('foo')) Evidently my early morning translation for brevity also translated out successful syntax, doh! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjhynes36 at hotmail.com Thu Jul 16 16:38:36 2009 From: cjhynes36 at hotmail.com (chris Hynes) Date: Thu, 16 Jul 2009 14:38:36 +0000 Subject: [Tutor] interactive naming of pointers In-Reply-To: <1c2a2c590907151923l6a089694q922d6f3ff99caaea@mail.gmail.com> References: <4A5DF8A9.1010105@gmail.com> <4A5E4C62.50209@gmail.com> <1c2a2c590907151923l6a089694q922d6f3ff99caaea@mail.gmail.com> Message-ID: Yeah, I'm not sure if I'm explaining myself well or maybe I'm just trying to make the code too interactive. in my code I would type something like: x=zeros((3,3)) so the pointer called "x" is created by the programmer, but within the code. What if I wanted to prompt my keyboard user to type in a word, like "Chris" and then the program would create: Chris=zeros((3,3)) Whatever code could make this happen I could loop through it several times, create various array names, and when the operator was done, they would have several arrays created with names of their choosing. When I'm in ipython mode, I would have to type Chris=zeros((3,3)), then Bob=zeros((3,3)) and then Kent=zero((3,3)), three separate statements (and gosh what if I wanted more than just these three?). I want my user to create names for their pointers instead of it already being in the code. > I'm not sure you have really thought this through. The user typed > "Chris", and that value is stored in 'name'. It might just as well > have been "Bob" or "Kent". So you can't really say > print Chris > you need something like > print the_thing_called(name) > which you might as well spell as > print values[name] > > Kent _________________________________________________________________ Windows Live? SkyDrive?: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_SD_25GB_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From johan at accesstel.com.au Thu Jul 16 14:07:22 2009 From: johan at accesstel.com.au (Johan Geldenhuys) Date: Thu, 16 Jul 2009 22:07:22 +1000 Subject: [Tutor] XML: changing value of elements and writing to a file In-Reply-To: References: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> <001101ca05da$32052d90$960f88b0$@com.au> Message-ID: <002e01ca060d$fa1aead0$ee50c070$@com.au> Thanks Stefan (decided to continue with a new thread name), I basically wants to create a loop that creates a tree, appends it to the previous tree and write it all to one file...If that makes sense. At the moment my tree is something like this: """ WhatEver """ Now I want to read a dictionary from somewhere and put new values in the name and description. I know how to do that. Now I want to create a loop that creates a new tree: """ HowDee """ Now I want to append these to the data I want to write to a single xml file. """ WhatEver HowDee """ I was thinking of creating a new root element and appending each as a subelement and then writing the root element to the file... I just need some pointers on how to do that. Thanks Johan -----Original Message----- From: tutor-bounces+johan=accesstel.com.au at python.org [mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Stefan Behnel Sent: Thursday, July 16, 2009 7:23 PM To: tutor at python.org Subject: Re: [Tutor] XML: changing value of elements Hi, a new question usually merits a new thread. Especially after a longer time, replies to older threads tend to remain unread as people simply don't scroll down far enough to notice them. You were lucky. :) Johan Geldenhuys wrote: > I have another question about writing the xml tree to a file. > > Now, I have parsed and changed my xml tree, but I want to create the same > tree multiple times with different values and write it to one file. > > > Let's use this code: > > import xml.etree.ElementTree as ET > doc = ET.parse('signal1.xml') > signal_node = doc.getroot()[0] > signal_node.set('name', 'Test_Name') > > I have this in a function and it returns the signal_node everytime I call > it, but with a different values. > > So, How do I take the returned xml and write that to one xml file? I'm not sure what you mean here. Do you mean: "multiple XML trees into a single file"? Or each in its own file? BTW, you don't need to re-parse the tree if all you want is to modify it and write it back out. You can either keep changing the tree and write it out multiple times, or deep-copy it (or parts of it) and start over for each step. Although I guess that parsing might be faster than deep-copying, especially for ElementTree. Stefan _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor Checked by AVG - www.avg.com Version: 8.5.387 / Virus Database: 270.13.16/2240 - Release Date: 07/15/09 17:58:00 From stefan_ml at behnel.de Thu Jul 16 17:07:00 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 16 Jul 2009 17:07:00 +0200 Subject: [Tutor] XML: changing value of elements and writing to a file In-Reply-To: <002e01ca060d$fa1aead0$ee50c070$@com.au> References: <20090610032630.HKZY2116.nskntotgx01p.mx.bigpond.com@JohanPC> <001101ca05da$32052d90$960f88b0$@com.au> <002e01ca060d$fa1aead0$ee50c070$@com.au> Message-ID: Johan Geldenhuys wrote: > Thanks Stefan (decided to continue with a new thread name), ... which isn't quite enough. As long as you reply to the mail, e-mail/news readers will still sort it into the original thread, so many people will not see it. > I basically wants to create a loop that creates a tree, appends it to the > previous tree and write it all to one file...If that makes sense. > > At the moment my tree is something like this: > """ > > WhatEver > > """ > > Now I want to read a dictionary from somewhere and put new values in the > name and description. I know how to do that. Now I want to create a loop > that creates a new tree: > """ > > HowDee > > """ > > Now I want to append these to the data I want to write to a single xml file. > > """ > > WhatEver > > > HowDee > > """ > > I was thinking of creating a new root element and appending each as a > subelement and then writing the root element to the file... That's exactly the right thing since XML requires a single root element. You can do it like this: root = ET.Element("newroot") for key, value in some_dict.iteritems(): signal = ET.SubElement(root, "Signal", name=key) ET.SubElement(signal, "Description").text = value Reading this might help: http://effbot.org/zone/element.htm http://codespeak.net/lxml/tutorial.html#the-element-class Stefan From digitalman66 at gmail.com Thu Jul 16 15:26:53 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Thu, 16 Jul 2009 08:26:53 -0500 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> Message-ID: <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> All lines that come back from a text file come back as strings. You can use string methods to detect the data like so: f = open('test.txt') lines = f.readlines() numbers = [] strings = [] for line in lines: if line.strip().isdigit(): numbers.append(int(line)) else: strings.append(line.strip()) print numbers print strings On Wed, Jul 15, 2009 at 1:55 PM, Chris Castillo wrote: > I'm having some trouble reading multiple data types from a single text > file. > > say I had a file with names and numbers: > > bob > 100 > sue > 250 > jim > 300 > > I have a few problems. I know how to convert the lines into an integer but > I don't know how to iterate through all the lines and just get the integers > and store them or iterate through the lines and just get the names and store > them. > > please help. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jul 16 18:22:51 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 16 Jul 2009 11:22:51 -0500 Subject: [Tutor] interactive naming of pointers In-Reply-To: References: <4A5DF8A9.1010105@gmail.com> <4A5E4C62.50209@gmail.com> <1c2a2c590907151923l6a089694q922d6f3ff99caaea@mail.gmail.com> Message-ID: <333efb450907160922x51970ccfx54d0f3d2781ad779@mail.gmail.com> On Thu, Jul 16, 2009 at 9:38 AM, chris Hynes wrote: > Yeah, I'm not sure if I'm explaining myself well or maybe I'm just trying > to make the code too interactive. > > in my code I would type something like: > > x=zeros((3,3)) > > so the pointer called "x" is created by the programmer, but within the > code. What if I wanted to prompt my keyboard user to type in a word, like > "Chris" and then the program would create: > > Chris=zeros((3,3)) > > Whatever code could make this happen I could loop through it several times, > create various array names, and when the operator was done, they would have > several arrays created with names of their choosing. When I'm in ipython > mode, I would have to type Chris=zeros((3,3)), then Bob=zeros((3,3)) and > then Kent=zero((3,3)), three separate statements (and gosh what if I wanted > more than just these three?). I want my user to create names for their > pointers instead of it already being in the code. > That's what a dictionary effectively does. In [1]: grid = {} In [3]: grid['chris'] = [1, 2, 3] In [4]: grid['bob'] = [3, 2, 1] In [5]: def func(grid): ...: value = raw_input("Enter the name: ") ...: grid[value] = [1,1,1] ...: ...: In [6]: grid Out[6]: {'bob': [3, 2, 1], 'chris': [1, 2, 3]} In [7]: func(grid) Enter the name: Mr. Mann In [8]: grid Out[8]: {'Mr. Mann': [1, 1, 1], 'bob': [3, 2, 1], 'chris': [1, 2, 3]} In [9]: grid['bob'] Out[9]: [3, 2, 1] The key values are unique, just like they would be if you declared them as: chris = [1,2,3] Of course I suppose if you REALLY wanted to use the provided names as variables you could do something that is both pointless and insane: def use_variable(): vname = raw_input("Enter the name of the variable: ") value = raw_input("Enter the value: ") f = open('insane.py', 'w') f.write(vname+'='+value) f.close() use_variable() from insane import * Tested: In [11]: use_var() Enter the var name: foo Enter the value: 'bar' In [12]: from insane import * In [13]: foo Out[13]: 'bar' But really, never, ever do this even if it's possible. I can't think of one single reason that it would be a) a good idea, or b) necessary. Of course I may be wrong and there is a single reason, but your case is not it. > Whatever code could make this happen I could loop through it several times, create various array names, and when the operator > > was done, they would have several arrays created with names of their choosing. It's been stated several times in several ways that dictionaries do this. So use a dictionary! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From amrita at iisermohali.ac.in Thu Jul 16 18:28:41 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Thu, 16 Jul 2009 21:58:41 +0530 (IST) Subject: [Tutor] just one question In-Reply-To: References: <21219.210.212.36.65.1247660649.squirrel@www.iisermohali.ac.in> <1e53c510907150744g3494a2fdgc9684f6e91771539@mail.gmail.com> <9887.210.212.36.65.1247680711.squirrel@www.iisermohali.ac.in> <25432.210.212.36.65.1247720486.squirrel@www.iisermohali.ac.in> <17854.210.212.36.65.1247745207.squirrel@www.iisermohali.ac.in> Message-ID: <18376.210.212.36.65.1247761721.squirrel@www.iisermohali.ac.in> Thankyou very much sir now it is working......it is giving that result which i wanted. Thankyou very much.......... Thanks, Amrita > Please use reply-all, so that emails go to the list as well. > > 2009/7/16 : >> Thankyou for help it is working and giving the result but the only >> problem >> is that it is making a very big file as it is searching for each >> position >> of ALA and first writting its C value then CA then CB like that, is it >> possible that it will do all these things but in the output it will give >> only the possible of C, CA and CB for each position of ALA:.. >> >> Like instead of giving all these:--- >> >> 23 ALA C = ?CA = ?CB = >> 21 ALA C = 179.35 CA = 54.33 CB = 17.87 >> 15 ALA C = 177.18 CA = 52.18 CB = 20.64 >> 8 ALA C = 179.39 CA = 54.67 CB = 18.85 >> 23 ALA C = ?CA = ?CB = >> 21 ALA C = 179.35 CA = 54.33 CB = 17.87 >> ..... >> >> it will only give:---- >> >> 8 ALA C = 179.39 CA = 54.67 CB = 18.85 >> 15 ALA C = 177.18 CA = 52.18 CB = 20.64 >> 21 ALA C = 179.35 CA = 54.33 CB = 17.87 >> 23 ALA C = 179.93 CA = 55.84 CB = 17.55 >> 33 ALA C = 179.24 CA = 55.58 CB = 19.75 >> 38 ALA C = 178.95 CA = 54.33 CB = 18.30 >> >> >> Thanks, >> Amrita >> >> >> >> >> >> Amrita Kumari >> Research Fellow >> IISER Mohali >> Chandigarh >> INDIA >> >> > > Either you're not entering the code correctly, or the input file is > different to what you've shown us so far. > > I think you need to send me a copy of the input file - or at least a > larger sample than we've had so far so we can see what we're dealing > with. > > The code should be: > > from __future__ import with_statement > from collections import defaultdict > from decimal import Decimal > > atoms = defaultdict(dict) > > with open("file1.txt") as f: > for line in f: > try: > n, pos, ala, at, symb, weight, rad, count = line.split() > except ValueError: > continue > else: > atoms[int(pos)][at] = Decimal(weight) > > #modify these lines to fit your needs: > positionsNeeded = (8, 15, 21) > atomsNeeded = ("C", "CA", "CB") > > for k, v in atoms.iteritems(): > print k, "ALA C = %s CA = %s CB = %s" % tuple(v.get(a,"") for a in > atomsNeeded) > > Check you've got the indentation (the spaces at the start of lines) > correct, exactly how it is above: this is VERY important in python. > > -- > Rich "Roadie Rich" Lovely > There are 10 types of people in the world: those who know binary, > those who do not, and those who are off by one. > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From alan.gauld at btinternet.com Thu Jul 16 20:25:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Jul 2009 19:25:51 +0100 Subject: [Tutor] objects becoming pointers References: Message-ID: "chris Hynes" wrote > I want the user to input a name, say "Chris". I know I can use the code: > > name=raw_input() > > I now want: > > "Chris"=zeros((3,3)) > > so that when I type: > > print Chris This is a common misapprehension by beginners. But let me ask you something. Since you will be writing your program code, including the print Chris line, how will you know in advance what names your userrs are going to input? I think you will find it easier to create a dictiobnary of user names with their associated values: name = raw_input() names[name] = value name = raw_input("Which name was it?") print names[name] or even: for name in names: print names[name] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ctcast at gmail.com Thu Jul 16 20:20:01 2009 From: ctcast at gmail.com (Chris Castillo) Date: Thu, 16 Jul 2009 13:20:01 -0500 Subject: [Tutor] reading complex data types from text file In-Reply-To: <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> Message-ID: <50e459210907161120i5176e1do744a399cb26eb6d@mail.gmail.com> *so far I have this and the format is what i want:* ------------------------------------------------------------------------------------------ # Set all necessary variables name = None fileOut = open('outputFile.txt', 'w') total = 0 averageScore = 0 numofScores = 0 score = 0 # Header for output file fileOut.write("Bowling Report\n" + ("-" * 40) + "\n") # Iterate line by line through file to get names and their corresponding scores for line in open('bowlingscores.txt', 'r'): line = line.strip() if line: if line.isdigit(): score = int(line) numofScores += 1 total += score averageScore = total / numofScores # Get average score # Decides where bowler stands compared to the average score if score < averageScore: score = "\tBelow average" elif score > averageScore and score != 300: score = "\tAbove average!" elif score == 300: score = "\tPerfect score!" else: name = line # Checks to see if name and score have values if name and score: fileOut.write('%s\t%s\r\n' % (name, score)) name, score = None, None fileOut.close() ------------------------------------------------------------------------------------ *the problem is that it's not comparing the first bowler's score to the average score and the output file looks like this: * Bowling Report ---------------------------------------- David 120 Hector Perfect score! Mary Below average * is the logic in my if-elif statements wrong or is it just skipping the first bowler's score? * On Thu, Jul 16, 2009 at 8:26 AM, Glen Zangirolami wrote: > All lines that come back from a text file come back as strings. You can use > string methods to detect the data like so: > f = open('test.txt') > lines = f.readlines() > numbers = [] > strings = [] > > for line in lines: > if line.strip().isdigit(): > numbers.append(int(line)) > else: > strings.append(line.strip()) > > print numbers > print strings > > > > On Wed, Jul 15, 2009 at 1:55 PM, Chris Castillo wrote: > >> I'm having some trouble reading multiple data types from a single text >> file. >> >> say I had a file with names and numbers: >> >> bob >> 100 >> sue >> 250 >> jim >> 300 >> >> I have a few problems. I know how to convert the lines into an integer but >> I don't know how to iterate through all the lines and just get the integers >> and store them or iterate through the lines and just get the names and store >> them. >> >> please help. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjhynes36 at hotmail.com Thu Jul 16 20:58:21 2009 From: cjhynes36 at hotmail.com (chris Hynes) Date: Thu, 16 Jul 2009 18:58:21 +0000 Subject: [Tutor] objects becoming pointers In-Reply-To: References: Message-ID: That's just it, you won't know in advance what names the user will type in. Maybe I mean to say dynamically create pointers. For instance, In the morning, I might be working with data regarding methanol and do several iterations and save those iterations in separate arrays with some type of methanol basename (I guess I could just save everything in a huge multidimensional array but it helps me to compartmentalize in to separate smaller arrays by name), later that afternoon I might we doing some formaldehyde calculations so I want those arrays to have some kind of aldehyde name associated with it. I could recall an earlier methanol array that was created. I could go back in to my code and change names. Or I thought I could just leave my program running and just keep on typing in new names as I need them, kind of like giving birth to as many arrays with whatever names as I see fit. Several people have suggested I use dictionary function, and I'll probably do that. Hmmm, is it possible to concantenate a raw_input on to a pointer? Oh well, in the end I think I'm just going to create a mutidimensional array and just access sub parts of it as I need to. Thanks for your help. > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Thu, 16 Jul 2009 19:25:51 +0100 > Subject: Re: [Tutor] objects becoming pointers > > > "chris Hynes" wrote > > > I want the user to input a name, say "Chris". I know I can use the code: > > > > name=raw_input() > > > > I now want: > > > > "Chris"=zeros((3,3)) > > > > so that when I type: > > > > print Chris > > > This is a common misapprehension by beginners. > But let me ask you something. Since you will be writing your > program code, including the > > print Chris > > line, how will you know in advance what names your userrs are > going to input? > > I think you will find it easier to create a dictiobnary of user names > with their associated values: > > name = raw_input() > names[name] = value > > name = raw_input("Which name was it?") > print names[name] > > or even: > > for name in names: > print names[name] > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Windows Live? SkyDrive?: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_SD_25GB_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Jul 16 22:33:17 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 17 Jul 2009 06:33:17 +1000 Subject: [Tutor] help In-Reply-To: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> References: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> Message-ID: jonathan wallis wrote: > i have a duel loop that looks like this while y > 0 and x > 0: > i cant figure out if there is a way to make so if one loop ends it says > something different than if the other loop ends. > while x > 0 or y > 0: ... if x > 0: print 'x is greater than 0' elif y > 0: print 'y is greater than 0' print 'what should happen when both x>0 and y>0 is true?' From pedrooconnell at gmail.com Thu Jul 16 22:55:16 2009 From: pedrooconnell at gmail.com (pedro) Date: Thu, 16 Jul 2009 16:55:16 -0400 Subject: [Tutor] pyparsing complex search Message-ID: Hi, well mabe it's not so complex (just for me). I have this code which works fine: #start########################################################### from pyparsing import * data = """23 different size pry bars hammer the pitchfork pound felt paper staple the felt paper every to inches staple hammer""" def reportACertainWord( st , locn , toks ): theWord = toks[0] if theWord == Word(nums): print "Found '%s' on line %d at column %d" % (theWord, lineno( locn , st ), col( locn , st )) print "The full line of text was:" print "'%s'" % line( locn , st ) print (" "*col( locn , st ))+" ^" print returnedWords = Word(alphanums).setParseAction( reportACertainWord ) OneOrMore(returnedWords).parseString(data) #end################################################################ But what I want to search for is any number plus the word after it. I thought the following code would do it but it doesn't (I only changed the if line). Any help would be appreciated. Pete #start########################################################### from pyparsing import * data = """23 different size pry bars hammer the pitchfork pound felt paper staple the felt paper every to inches staple hammer""" def reportACertainWord( st , locn , toks ): theWord = toks[0] if theWord == Word(nums) + Word( alphas ): print "Found '%s' on line %d at column %d" % (theWord, lineno( locn , st ), col( locn , st )) print "The full line of text was:" print "'%s'" % line( locn , st ) print (" "*col( locn , st ))+" ^" print returnedWords = Word(alphanums).setParseAction( reportACertainWord ) OneOrMore(returnedWords).parseString(data) #end################################################################ From eduardo.susan at gmail.com Thu Jul 16 22:56:47 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 16 Jul 2009 14:56:47 -0600 Subject: [Tutor] Reconstructing phrases from tagged text Message-ID: <9356b9f30907161356o661d29c4l8e41883364b5e9e2@mail.gmail.com> Hello, I'm scratching my head into solving a problem of transforming a POS-Tagged text in a normal text. My biggest problem is that I can't get the quotes to be placed properly. I had tried a different approach but was advised in the nltk list to use this example, but it does not solve the quoting problem... #== Here's the sample code === # -*- coding: cp1252 -*- input = """Titelman NOM riu-se V+P rir em PRP em seu ADJ seu t?pico ADJ t?pico modo NOM modo grosseiro ADJ grosseiro e CONJ e respondeu V responder : SENT : " QUOTE " Voc? P voc? prende V prender a DET a criminosos NOM criminoso e CONJ e a DET a pessoas NOM pessoa m?s ADJ mau , VIRG , mas CONJ mas eu P eu deten??o NOM deten??o s? ADJ s? aos PRP+DET a anabatistas NOM , VIRG , quem PR quem levam V levar vidas NOM vida boas ADJ bom e CONJ e nunca ADV nunca fazem V fazer uso NOM uso da PRP+DET de viol?ncia NOM viol?ncia " QUOTE " . SENT . Ouvi V ouvir dizer V dizer que CONJSUB que o DET o servidor ADJ servidor p?blico NOM p?blico lhe P lhe deu V dar uma DET uma boa ADJ bom resposta NOM resposta : SENT : " QUOTE " Se P se eu P eu deten??o NOM deten??o a PRP a toda ADJ todo a DET a gente NOM gente m? ADJ mau e CONJ e voc? P voc? prende V prender a PRP a toda ADJ todo a DET a gente NOM gente boa ADJ bom , VIRG , quem PR quem ficar? V ficar ? SENT ? " QUOTE " + at + V + at + V ? V Sabes NOM ? SENT ? """ PUNCT = '!#$%)*,-.:;<=>?@/\\]^_`}~??' LINEBREAK = '+ at +' tokens = [line.split()[0] for line in input.splitlines()] # instead output = [] for t in tokens: if t == LINEBREAK: output.append('\n') else: if t not in PUNCT: output.append(' ') output.append(t) print ''.join(output) #== It ouputs this: Titelman riu-se em seu t?pico modo grosseiro e respondeu: " Voc? prende a criminosos e a pessoas m?s, mas eu deten??o s? aos anabatistas, quem levam vidas boas e nunca fazem uso da viol?ncia ". Ouvi dizer que o servidor p?blico lhe deu uma boa resposta: " Se eu deten??o a toda a gente m? e voc? prende a toda a gente boa, quem ficar?? " ? Sabes? You see, the quotes have spaces in between: My old code that didn't do the job as good was this (hairy) one: The removing of tags I had already done with "sed". myoutput = cStringIO.StringIO() f = open(r'C:\mytools\supersed\tradunew.txt') lista = [line.strip() for line in f] punct = '!#$%)*,-.:;<=>?@/\\]^_`}~??' for i, item in enumerate(lista): if item == '"' and lista[i + 1] not in punct: myoutput.write(item) spacer = True elif '+ at +' in item: donewline = item.replace('+ at +','\n ') myoutput.write(donewline) elif item not in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] in punct: myoutput.write(item) elif item in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item not in punct and lista[i + 1] == '"' and spacer: myoutput.write(item) spacer = False elif item in '([{?': myoutput.write(item) else: myoutput.write(item + " ") newlist = myoutput.getvalue().splitlines() myoutput.close() f = open(r'C:\mytools\supersed\traducerto-k.txt', 'w') for line in newlist: f.write(line.lstrip()+'\n') f.close() So a text like this: --- Example begins No , thanks.+ at + # this + at + I inserted to mark paragraphs, because the POS-Tagger don't keep paragraph marks He said , " No , thanks . " OK ? --- Example ends --- And I want to transform into this: No, thanks. He said, "No, thanks." OK? --- End example Thanks. From bgailer at gmail.com Thu Jul 16 23:08:46 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 16 Jul 2009 17:08:46 -0400 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907161120i5176e1do744a399cb26eb6d@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> <50e459210907161120i5176e1do744a399cb26eb6d@mail.gmail.com> Message-ID: <4A5F96DE.90205@gmail.com> Chris Castillo wrote: > *so far I have this and the format is what i want:* > ------------------------------------------------------------------------------------------ > # Set all necessary variables > name = None > fileOut = open('outputFile.txt', 'w') > > total = 0 > averageScore = 0 > numofScores = 0 > score = 0 > > # Header for output file > fileOut.write("Bowling Report\n" + ("-" * 40) + "\n") > > # Iterate line by line through file to get names and their > corresponding scores > for line in open('bowlingscores.txt', 'r'): > line = line.strip() > if line: > if line.isdigit(): > score = int(line) > numofScores += 1 > total += score > > averageScore = total / numofScores # Get average score > > # Decides where bowler stands compared to the average score > if score < averageScore: > score = "\tBelow average" > elif score > averageScore and score != 300: > score = "\tAbove average!" > elif score == 300: > score = "\tPerfect score!" > else: > name = line > > # Checks to see if name and score have values > if name and score: > fileOut.write('%s\t%s\r\n' % (name, score)) > name, score = None, None > > > fileOut.close() > ------------------------------------------------------------------------------------ > *the problem is that it's not comparing the first bowler's score to > the average score and the output file looks like this: > * > Bowling Report > ---------------------------------------- > David 120 > > Hector Perfect score! > > Mary Below average > * > is the logic in my if-elif statements wrong or is it just skipping the > first bowler's score? > * You must process all the scores before computing averages. This means saving each player's score. Use a dictionary with the name as the key and the score as the value. Then go thru the dictionary to compute and report averages. -- Bob Gailer Chapel Hill NC 919-636-4239 From lie.1296 at gmail.com Thu Jul 16 23:12:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 17 Jul 2009 07:12:28 +1000 Subject: [Tutor] interactive naming of pointers In-Reply-To: <333efb450907160922x51970ccfx54d0f3d2781ad779@mail.gmail.com> References: <4A5DF8A9.1010105@gmail.com> <4A5E4C62.50209@gmail.com> <1c2a2c590907151923l6a089694q922d6f3ff99caaea@mail.gmail.com> <333efb450907160922x51970ccfx54d0f3d2781ad779@mail.gmail.com> Message-ID: Wayne wrote: > On Thu, Jul 16, 2009 at 9:38 AM, chris Hynes > wrote: > > Yeah, I'm not sure if I'm explaining myself well or maybe I'm just > trying to make the code too interactive. > > in my code I would type something like: > > x=zeros((3,3)) > > so the pointer called "x" is created by the programmer, but within > the code. What if I wanted to prompt my keyboard user to type in a > word, like "Chris" and then the program would create: > > Chris=zeros((3,3)) > > Whatever code could make this happen I could loop through it several > times, create various array names, and when the operator was done, > they would have several arrays created with names of their choosing. > When I'm in ipython mode, I would have to type Chris=zeros((3,3)), > then Bob=zeros((3,3)) and then Kent=zero((3,3)), three separate > statements (and gosh what if I wanted more than just these three?). > I want my user to create names for their pointers instead of it > already being in the code. > > > That's what a dictionary effectively does. In fact, in python, global name resolution is merely syntax sugar for accessing the global names dictionary. If you want to have an interactive prompting in your own program and the prompting can assign names and stuffs, you should create your own namespace instead of corrupting the interpreter's global namespace (which is a huge security risk and is a latent source of bugs). something like: mynames = {} inputting = True while inputting: name = raw_input('name? ') data = make_zero() mynames[name] = data inputting = not raw_input('continue? (leave blank to continue) ') browsing = True while browsing: name = raw_input('name? ') print mynames[name] browsing = not raw_input('continue? (leave blank to continue) ') or if you don't mind using eval/exec: # a poor man's python interpreter global_ns = {} while True: prompt = raw_input('>>>') exec prompt in global_ns From alan.gauld at btinternet.com Thu Jul 16 23:32:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Jul 2009 22:32:06 +0100 Subject: [Tutor] help References: <57b8984c0907151254i4c78f736mb1d014618b707de7@mail.gmail.com> Message-ID: "jonathan wallis" wrote >i have a duel loop that looks like this > > while y > 0 and x > 0: This is not any kind of loop its a while expression. It should have a body and that would then constitute a single while loop not a dual loop ( a duel lop has something to do with repeatedly settling matters of honor! :-) > i cant figure out if there is a way to make so if one > loop ends it says something different than if the > other loop ends. I'm not certain what you mean by that but I assume you mean you want to determine which variable went out of bounds? If so you can use the else clause of a while loop: while x > 0 and y > 0: choice = raw_input('x or y?') if choice == 'x': x = 0 else: y = 0 else: if x <= 0: print 'it was x' else: print 'it was y' HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ptmcg at austin.rr.com Thu Jul 16 23:57:24 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Jul 2009 16:57:24 -0500 Subject: [Tutor] pyparsing complex search In-Reply-To: References: Message-ID: <743518F679A34D1A84AB5888F956FB83@AWA2> Pedro - If you are trying to extract a simple pattern like a numeric word followed by an alpha word, I would suggest using one of the scanString or searchString methods. scanString is probably the better choice, since you seem to need not only the matching tokens, but also the location within the input string where the match occurs. scanString(sourcestring) is a generator function. For every match, scanString returns: - tokens - the matched tokens themselves (as a ParseResults object) - startloc - starting location of the matched tokens - endloc - ending location of the matched tokens Here is your test program, rewritten to use scanString (I inserted the number '75' in the source string so you can see the results of having multiple matches): from pyparsing import * data = """23 different size pry bars hammer the 75 pitchfork pound felt paper staple the felt paper every to inches staple hammer""" numbrword = Word(nums) alphaword = Word(alphas) for match,locn,endloc in (numbrword+alphaword).scanString(data): num,wrd = match st = data print "Found '%s/%s' on line %d at column %d" % \ (num,wrd, lineno(locn , st ), col( locn , st )) print "The full line of text was:" print "'%s'" % line( locn , st ) print (" "*col( locn , st ))+"^" print With this output: Found '23/different' on line 1 at column 1 The full line of text was: '23 different size pry bars' ^ Found '75/pitchfork' on line 2 at column 12 The full line of text was: 'hammer the 75 pitchfork' ^ Look at the difference between this program and your latest version. The pattern you parsed for is simply "OneOrMore(Word(alphanums))" - to debug a parse action, try using the decorator that comes with pyparsing, traceParseAction, like this: @traceParseAction def reportACertainWord( st , locn , toks ): and it will print out the tokens passed into and out of the parse action. It would have shown you that you weren't just matching ['23', 'different'], but the entire input string. Using scanString is a little simpler than writing a parse action. Also, since scanString is a generator, it will return matches as it finds them. So if you have this file: 123 paper clips ... 10Gb of intervening non-matching text... 456 paper planes scanString will return the match for '123 paper' right away, before processing the intervening 10Gb of non-matching text. Best of luck in your pyparsing efforts! -- Paul From davea at ieee.org Fri Jul 17 02:47:26 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 16 Jul 2009 20:47:26 -0400 Subject: [Tutor] unittests, testing a type In-Reply-To: <20090715061448.32920@gmx.net> References: <20090714134127.29270@gmx.net> <4A5C8BEE.7040105@tue.nl> <20090714135919.146540@gmx.net> <1c2a2c590907140758t23096c43s4c504d9632f373d2@mail.gmail.com> <4A5D409E.2030408@ieee.org> <20090715061448.32920@gmx.net> Message-ID: <4A5FCA1E.5050100@ieee.org> Todd Matsumoto wrote: > Hi, > > Thanks for all the comments so far. > > DaveA, I'm receiving the value via pyODBC, after running a query on a database. The test is to first make sure the value is a Decimal (pyODBC returns a Decimal object if what is coming from the database is a decimal type). So if I don't have a value that is a Decimal object something is wrong. > > Cheers, > > T > -------- Original-Nachricht -------- > >> Datum: Tue, 14 Jul 2009 22:36:14 -0400 >> Von: Dave Angel >> An: >> CC: Todd Matsumoto , tutor at python.org >> Betreff: Re: Re: [Tutor] unittests, testing a type >> > > >> On Tue, Jul 14, 2009 at 9:59 AM, Todd Matsumoto wrote: >> >>>> The reason why is I'm receiving the Decimal value from another program, >>>> >> if I already know that the value will be a Decimal why test it? >> >>>> >>>> >>> >>> >> How are you receiving it? File, pickle, pipe, socket, exit() return >> value? When I first read your question, I assumed you meant "from >> another module." But if it's another process, then you'd better tell us >> how you're actually getting the value. Maybe it's a Decimal because you >> just got done converting it to one. >> >> DaveA >> > > If the value is being passed back from another module, and you therefore want to do an exact test on the type, just do if type(a) == decimal.Decimal: On the other hand, if you just want to know if it's a particular type, or some subclass of that type, use isinstance();. DaveA From pedrooconnell at gmail.com Fri Jul 17 04:03:07 2009 From: pedrooconnell at gmail.com (pedro) Date: Thu, 16 Jul 2009 22:03:07 -0400 Subject: [Tutor] pyparsing complex search References: <743518F679A34D1A84AB5888F956FB83@AWA2> Message-ID: Hi Paul. Thanks. I would like to get better at pyparsing. Can you recommend a good resource for learning. I am finding that what info I have found on the subject (on the web) isn't really explaining it from the ground up as much as I would like. Cheers Pete From davea at ieee.org Fri Jul 17 04:24:04 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 16 Jul 2009 22:24:04 -0400 Subject: [Tutor] objects becoming pointers In-Reply-To: References: Message-ID: <4A5FE0C4.8050705@ieee.org> chris Hynes wrote: > That's just it, you won't know in advance what names the user will type in. Maybe I mean to say dynamically create pointers. For instance, > > In the morning, I might be working with data regarding methanol and do several iterations and save those iterations in separate arrays with some type of methanol basename (I guess I could just save everything in a huge multidimensional array but it helps me to compartmentalize in to separate smaller arrays by name), later that afternoon I might we doing some formaldehyde calculations so I want those arrays to have some kind of aldehyde name associated with it. I could recall an earlier methanol array that was created. > > I could go back in to my code and change names. Or I thought I could just leave my program running and just keep on typing in new names as I need them, kind of like giving birth to as many arrays with whatever names as I see fit. > > Several people have suggested I use dictionary function, and I'll probably do that. Hmmm, is it possible to concantenate a raw_input on to a pointer? > > Oh well, in the end I think I'm just going to create a mutidimensional array and just access sub parts of it as I need to. Thanks for your help. > > What language are you planning to write this in? Python doesn't have pointers. And variables created in one run of the program are not visible next time it runs. And it doesn't have arrays, nor multidimensional anything. Nor "dictionary functions." Who is the user? Is it the same person writing the code, and you just refer to yourself in the 3rd person? Once your code is running, and getting names, it's a bit late to be entering print statements into your code. Are you perhaps running this whole thing from the interpreter prompt? A dictionary is a data structure, like a list is. Each item in a dictionary has a key and a value. Certainly dictionary values may be lists, and keys can be strings like "methanol" or "Chris". From pine508 at hotmail.com Fri Jul 17 05:21:14 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 16 Jul 2009 23:21:14 -0400 Subject: [Tutor] weather scraping with Beautiful Soup Message-ID: Hi, I am interested in gathering simple weather data using Beautiful Soup, but am having trouble understanding what I'm doing. I have searched the archives and so far haven't found enough to get me moving forward. Basically I am trying to start off this example: Grabbing Weather Underground Data with BeautifulSoup http://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/ But I get to the exact same problem that this other person got to in this post: http://groups.google.com/group/beautifulsoup/browse_thread/thread/13eb3dbf713b8a4a Unfortunately, that post never gives enough help for me to understand how to solve that person's or my problem. What I want to understand is how to find the bits of data you want--in this case, say, today's average temperature and whether it was clear or cloudy--within a web page, and then indicate that to Beautiful Soup. Thanks, Che _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_BR_life_in_synch_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Fri Jul 17 05:36:56 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 16 Jul 2009 22:36:56 -0500 Subject: [Tutor] pyparsing complex search In-Reply-To: References: Message-ID: > Hi Paul. Thanks. I would like to get better at pyparsing. Can you > recommend a good resource for learning. I am finding that what info I > have found on the subject (on the web) isn't really explaining it from > the ground up as much as I would like. Hrmmm, not sure what to recommend - I might just point you back to what you have already tried. Where are you looking and what are you finding? The pyparsing source package comes with a directory of examples and htmldoc class documentation. If you just used the easy_install or the Win32 install package, these directories get omitted - try downloading the source package from SourceForge. There is also quite a bit of info at the pyparsing wiki, at http://pyparsing.wikispaces.com. The Discussion tab on the home page has over 1200 posted messages in various discussion threads of people seeking help. You can also visit the Documentation page for some links to presentations that have been given on pyparsing. For basic getting-started type stuff, I'd recommend: - the PyCon'06 presentations I gave - Introduction to Pyparsing - http://wiki.python.org/moin/PyCon2006/Talks#1 An Interactive Adventure Game Engine Built Using Pyparsing - http://wiki.python.org/moin/PyCon2006/Talks#4 - the OnLAMP article (free, but a little old now) - http://onlamp.com/pub/a/python/2006/01/26/pyparsing.html - the 3 articles I wrote for Python Magazine in the past year (not free, you'll have to buy back-issues) Writing a simple Interpreter/Compiler with Pyparsing - http://pymag.phparch.com/c/issue/view/74 Advanced Pyparsing: Implementing a JSON Parser Using Results Names - http://pymag.phparch.com/c/issue/view/79 Create Your Own Domain-Specific Language in Python With Imputil and Pyparsing - http://pymag.phparch.com/c/issue/view/96 - the O'Reilly e-book I wrote (also not free, costs $10) - Getting Started with Pyparsing - http://oreilly.com/catalog/9780596514235/ Does this help? -- Paul From alan.gauld at btinternet.com Fri Jul 17 08:45:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jul 2009 07:45:55 +0100 Subject: [Tutor] weather scraping with Beautiful Soup References: Message-ID: "Che M" wrote Grabbing Weather Underground Data with BeautifulSoup http://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/ But I get to the exact same problem that this other person got to in this post: http://groups.google.com/group/beautifulsoup/browse_thread/thread/13eb3dbf713b8a4a > Unfortunately, that post never gives enough help for me to > understand how to solve that person's or my problem. The posts basocally say go and look at the HTML and find the right tags for the data you need. This is fubndamental to any kind of web scraping, you need to understand the HTML tree well enough to identify where yourt data exists. How familiar are you with HTML and its structures? Can you view the source in your browser and identify the heirarchy of tags to the place where your data lives? > What I want to understand is how to find the bits of data you > want--in this case, say, today's average temperature and whether > it was clear or cloudy--within a web page, Go to the web page and use View Source from your browser. Then its down to you to interpret the HTML. Somne experimentation with print statements might be necessary to check you have the right place. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pine508 at hotmail.com Fri Jul 17 10:01:29 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 04:01:29 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: Message-ID: > The posts basocally say go and look at the HTML and find the > right tags for the data you need. This is fubndamental to any kind of web > scraping, you need to understand the HTML tree well enough to identify > where yourt data exists. > > How familiar are you with HTML and its structures? Reasonably familiar. > Can you view the source in your browser and identify the heirarchy > of tags to the place where your data lives? I can view the source, and have made my own web pages (HTML, CSS). I am less sure about the hierarchy of tags. For example, here is the section around the current temperature:
West of Town, Jamestown, Pennsylvania (PWS)
Updated: 3:00 AM EDT on July 17, 2009
Clear
60.3 °F
The 60.3 is the value I want to extract. It appears to be down within a hierarchy something like:
But I am far from sure I got all that right; it is not easy to look at HTML and match
with
. Unless I am missing something? Do I have to use all of the above in my Beautiful Soup? CM _________________________________________________________________ Windows Live? SkyDrive?: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_SD_25GB_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Fri Jul 17 12:27:36 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 17 Jul 2009 12:27:36 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: Message-ID: <4A605218.7010702@xs4all.nl> Che M wrote: > The 60.3 is the value I want to extract. soup.find("div",id="curcondbox").findNext("span","b").renderContents() -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From brsata at gmail.com Fri Jul 17 09:12:16 2009 From: brsata at gmail.com (=?UTF-8?B?YmFyxLHFnyBhdGE=?=) Date: Fri, 17 Jul 2009 10:12:16 +0300 Subject: [Tutor] How to limit logs Message-ID: hi, i'm writing a log client to recieve logs from socket connection and display on a textbox now i have a few question i used Pmw.ScrolledText but i don't now its buffer size. how can i limit it? and i want to create a log file with logging module but i want to limit log size for example if user sets log file limit to 1000 lines, i have to save last 1000 line on the fly and refresh it until program closed. Any idea ? tkanks... -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jul 17 14:09:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jul 2009 08:09:10 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: Message-ID: <1c2a2c590907170509o32692f28l47b6c71125ff978f@mail.gmail.com> On Thu, Jul 16, 2009 at 11:21 PM, Che M wrote: > Hi, > > I am interested in gathering simple weather data using Beautiful Soup, but > am having trouble understanding what I'm doing.? I have searched the > archives and so far haven't found enough to get me moving forward. > > Basically I am trying to start off this example: > > Grabbing Weather Underground Data with BeautifulSoup > http://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/ > > But I get to the exact same problem that this other person got to in this > post: > http://groups.google.com/group/beautifulsoup/browse_thread/thread/13eb3dbf713b8a4a > > Unfortunately, that post never gives enough help for me to understand how to > solve that person's or my problem. > > What I want to understand is how to find the bits of data you want--in this > case, say, today's average temperature and whether it was clear or > cloudy--within a web page, and then indicate that to Beautiful Soup. One thing that might help is to use the Lite page, if you are not already. It has much less formatting and extraneous information to wade through. You might also look for a site that has weather data formatted for computer. For example the NOAA has forcast data available as plain text: http://forecast.weather.gov/product.php?site=NWS&issuedby=BOX&product=CCF&format=txt&version=1&glossary=0 Kent From stefan_ml at behnel.de Fri Jul 17 14:40:40 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 17 Jul 2009 14:40:40 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: Message-ID: Che M wrote: >
>
>
West of Town, Jamestown, Pennsylvania (PWS)
>
Updated: 3:00 AM EDT on July 17, 2009
>
> >
> > > >
Clear >
> 60.3 °F >
> > The 60.3 is the value I want to extract. It appears to be down within a hierarchy > something like: > >
>
>
> > You may consider using lxml's cssselect module: from lxml import html doc = html.parse("http://some/url/to/parse.html") spans = doc.cssselect("div.bluebox > #curcondbox span.b") print spans[0].text However, I'd rather go for the other "60.3" value using XPath: print doc.xpath('//span[@pwsvariable="tempf"]/@value') Stefan From srilyk at gmail.com Fri Jul 17 16:12:57 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 17 Jul 2009 09:12:57 -0500 Subject: [Tutor] How to limit logs In-Reply-To: References: Message-ID: <333efb450907170712j17a7207al73836c77c4c83ef7@mail.gmail.com> On Fri, Jul 17, 2009 at 2:12 AM, bar?? ata wrote: > hi, > i'm writing a log client to recieve logs from socket connection and display > on a textbox > now i have a few question > i used Pmw.ScrolledText but i don't now its buffer size. how can i limit > it? > and i want to create a log file with logging module but i want to limit log > size > for example if user sets log file limit to 1000 lines, i have to save last > 1000 line on the fly and refresh it until program closed. Any idea ? I don't know if this is the "best" solution, but while the program is open if you simply truncate the file each time and just keep a list of no larger than 1000 lines and write each of those, that would work. Another option is to keep those 1000 lines and just seek to the beginning and rewrite the file each time. This could get pretty expensive as far as disk access goes, though. I don't think there's really a way in python to implement the disk access part, but a circular array (or file write) would work perfect in this situation. But with python, I'd probably just open the file in read/write mode (assuming you want to preserve the log from the previous run), seek to the beginning and write whatever is in the lines. Each time I add a line I'd check len(lines) > 1000: del(lines[0]), then write the lines and seek back to the front of the file. I don't know if there's a more efficient way to do it in python, but that's what I'd do. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From msh at blisses.org Fri Jul 17 17:08:43 2009 From: msh at blisses.org (Matt Herzog) Date: Fri, 17 Jul 2009 11:08:43 -0400 Subject: [Tutor] sftp get single file Message-ID: <20090717150843.GA20678@chicago.blisses.org> Hello All. I need to use paramiko to sftp get a single file from a remote server. The remote file's base name will be today's date (%Y%m%d) dot tab. I need help joining the today with the .tab extension. Do I need globbing? example: 20090716.tab #!/usr/bin/env python import paramiko import glob import os import time hostname = 'sftp.booboo.com' port = 22 username = 'booboo' password = '07N4219?' # glob_pattern='*.tab' today = time.strftime("%Y%m%d") remotepath = today.tab localpath = '/home/data/text' if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(remotepath, localpath) t.close() -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From sander.sweers at gmail.com Fri Jul 17 17:42:35 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 17 Jul 2009 17:42:35 +0200 Subject: [Tutor] sftp get single file In-Reply-To: <20090717150843.GA20678@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> Message-ID: 2009/7/17 Matt Herzog : > Hello All. > > I need to use paramiko to sftp get a single file from a remote server. > The remote file's base name will be today's date (%Y%m%d) dot tab. > I need help joining the today with the .tab extension. Do I need globbing? > > example: 20090716.tab > > #!/usr/bin/env python > import paramiko > import glob > import os > import time > hostname = 'sftp.booboo.com' > port = 22 > username = 'booboo' > password = '07N4219?' > # glob_pattern='*.tab' > today = time.strftime("%Y%m%d") > remotepath = today.tab > localpath = '/home/data/text' > > if __name__ == "__main__": > ? ?t = paramiko.Transport((hostname, port)) > ? ?t.connect(username=username, password=password) > ? ?sftp = paramiko.SFTPClient.from_transport(t) > ? ?sftp.get(remotepath, localpath) > ? ?t.close() > -- You don't need glob if you know in advance what the filename is. Print example below. --- import time today = time.localtime() datestr = time.strftime("%Y%m%d",today) ext = ".tab" print datestr + ext --- Greets Sander From amit.pureenergy at gmail.com Fri Jul 17 18:04:26 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Fri, 17 Jul 2009 21:34:26 +0530 Subject: [Tutor] Very wierd namespace problem Message-ID: I am not able to understand this , perhaps it is an aspect of python I do not understand .... Now usually I would think that for a class class a: ... def __init__(self): ... pass ... def __something__(self): ... pass >>> b=a() >>> dir(b) ['__doc__', '__init__', '__module__', '__something__'] This should be correct .... so now i can refer one of these functions from the object of the same class as obj.__something__() now I have created a class with some functions defined in it but the thing is that they are named in a completely different manner?????(or so I think) <__main__.SmPriceWindow instance at 0x9dd448c> ['_SmPriceWindow__add_columns', '_SmPriceWindow__create_model', '_SmPriceWindow__review_button_click', '_SmPriceWindow__show_all', '_SmPriceWindow__url_button_click', '__doc__', '__init__', '__module__', 'model', 'tree', 'window'] Traceback (most recent call last): File "smnotebook3.py", line 135, in price_button_pressed sw.__show_all() AttributeError: SmPriceWindow instance has no attribute '__show_all' I have refered to these functions(__add_columns ,__create_model etc ... as self.__add_columns as would be expected in the class itself ) This functionality is unexpected according to me .... Since I cannot take much of the space here explaining the code I have pasted here: http://pastebin.com/mddf7a43 -- A-M-I-T S|S From kent37 at tds.net Fri Jul 17 18:12:52 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jul 2009 12:12:52 -0400 Subject: [Tutor] sftp get single file In-Reply-To: References: <20090717150843.GA20678@chicago.blisses.org> Message-ID: <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> On Fri, Jul 17, 2009 at 11:42 AM, Sander Sweers wrote: > import time > > today = time.localtime() > datestr = time.strftime("%Y%m%d",today) > ext = ".tab" > > print datestr + ext You can include literal characters in the format string: In [4]: time.strftime("%Y%m%d.tab",today) Out[4]: '20090717.tab' Kent From pedrooconnell at gmail.com Fri Jul 17 18:26:42 2009 From: pedrooconnell at gmail.com (pedro) Date: Fri, 17 Jul 2009 12:26:42 -0400 Subject: [Tutor] != -1: versus == 1 Message-ID: Hi I have been trying to understand a python script and I keep coming across this kind of structure that says "If it is not equal to negative one" ################################ for line in theLines: if line.find("Source Height") != -1: #etc... ################################### Is there some special reason for this. Why not just write "If it is equal to one" ######################### for line in theLines: if line.find("Source Height") == 1: #etc... ################################### Pete From bill at celestial.net Fri Jul 17 18:37:00 2009 From: bill at celestial.net (Bill Campbell) Date: Fri, 17 Jul 2009 09:37:00 -0700 Subject: [Tutor] != -1: versus == 1 In-Reply-To: References: Message-ID: <20090717163700.GA1763@ayn.mi.celestial.com> On Fri, Jul 17, 2009, pedro wrote: > Hi I have been trying to understand a python script and I keep coming > across this kind of structure > that says "If it is not equal to negative one" > > ################################ > for line in theLines: > if line.find("Source Height") != -1: > #etc... > ################################### > > Is there some special reason for this. Why not just write "If it is > equal to one" The string find method returns -1 if the string is not found, otherwise it returns the 0-based index into the string matching the argument to find. The test above will return -1 if ``Source Heigtht'' is not in line, and one generally wants to have the test return True if there is something to do. The alternative would be to say ``if not line.find('Source Height') == -1: ...'' Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 Windows is a computer virus with a user interface!! From sander.sweers at gmail.com Fri Jul 17 18:37:25 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 17 Jul 2009 18:37:25 +0200 Subject: [Tutor] != -1: versus == 1 In-Reply-To: References: Message-ID: 2009/7/17 pedro : > ################################ > for line in theLines: > ? if line.find("Source Height") != -1: > #etc... > ################################### > > Is there some special reason for this. Why not just write "If it is equal to > one" Yes, str.find() returns -1 on failure. See below the documentation for str.find() | find(...) | S.find(sub [,start [,end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within s[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. Idle example: >>> teststr = 'a' >>> teststr.find('a') 0 >>> teststr.find('b') -1 Greets Sander From keithabt at beyondbb.com Fri Jul 17 18:43:08 2009 From: keithabt at beyondbb.com (keithabt at beyondbb.com) Date: Fri, 17 Jul 2009 12:43:08 -0400 Subject: [Tutor] Form values Message-ID: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> Hi, I am reading values from a form and writing them to a text file. I keep getting a syntax error for outfile=open("filename", "a")I cant see it, does any body else. fileName = "requests.txt" # Create instance of FieldStorage Form = cgi.FieldStorage() # Get data from fields if Form and Form['submit'].value == "Submit": the_name = Form.getvalue('name') the_email = Form.getvalue('email') the_address = Form.getvalue('address') the_telephone = Form.getvalue('telephone') IpAddress = cgi.escape(os.environ["REMOTE_ADDR"]); Time = "(time.localtime()):", time.asctime(time.localtime()) entry = name + '|' + email + '|' + address + '|' + telephone + '|' + IpAddress + '|' + Time + "\n" outfile=open("fileName", "a") outfile.write(entry) outfile.close() From kent37 at tds.net Fri Jul 17 19:02:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jul 2009 13:02:00 -0400 Subject: [Tutor] Very wierd namespace problem In-Reply-To: References: Message-ID: <1c2a2c590907171002t61db5ad3r4d726a524bb1d27b@mail.gmail.com> On Fri, Jul 17, 2009 at 12:04 PM, Amit Sethi wrote: > now I have created a class with some functions defined in it but the > thing is that they are named in a completely different manner?????(or > so I think) > > <__main__.SmPriceWindow instance at 0x9dd448c> > ['_SmPriceWindow__add_columns', '_SmPriceWindow__create_model', > '_SmPriceWindow__review_button_click', '_SmPriceWindow__show_all', > '_SmPriceWindow__url_button_click', '__doc__', '__init__', > '__module__', 'model', 'tree', 'window'] > Traceback (most recent call last): > ?File "smnotebook3.py", line 135, in price_button_pressed > ? ?sw.__show_all() > AttributeError: SmPriceWindow instance has no attribute '__show_all' > > I have refered to these functions(__add_columns ,__create_model etc > ... as self.__add_columns as would be expected in the class itself ?) Names beginning with __ are 'mangled' to make them sort of secret. This is a feature: http://docs.python.org/reference/expressions.html#index-889 Kent From emile at fenx.com Fri Jul 17 19:13:57 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 17 Jul 2009 10:13:57 -0700 Subject: [Tutor] Form values In-Reply-To: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> References: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> Message-ID: On 7/17/2009 9:43 AM keithabt at beyondbb.com said... > Hi, I am reading values from a form and writing them to a text file. I keep getting > a syntax error for outfile=open("filename", "a")I cant see it, does any body else. > There isn't an error in the statement. Try to pare down your code to a short example that causes the error. Then post the actual error and code segment. It's more likely there's an unfinished something before this line... Emile > > fileName = "requests.txt" > # Create instance of FieldStorage > Form = cgi.FieldStorage() > > # Get data from fields > if Form and Form['submit'].value == "Submit": > > the_name = Form.getvalue('name') > the_email = Form.getvalue('email') > the_address = Form.getvalue('address') > the_telephone = Form.getvalue('telephone') > > > IpAddress = cgi.escape(os.environ["REMOTE_ADDR"]); > Time = "(time.localtime()):", time.asctime(time.localtime()) > > entry = name + '|' + email + '|' + address + '|' + telephone + '|' + > IpAddress + '|' + Time + "\n" > > > > > outfile=open("fileName", "a") > outfile.write(entry) > outfile.close() > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pine508 at hotmail.com Fri Jul 17 19:33:03 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 13:33:03 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: <4A605218.7010702@xs4all.nl> References: <4A605218.7010702@xs4all.nl> Message-ID: > Date: Fri, 17 Jul 2009 12:27:36 +0200 > From: motoom at xs4all.nl > To: tutor at python.org > CC: pine508 at hotmail.com > Subject: Re: [Tutor] weather scraping with Beautiful Soup > > Che M wrote: > > > The 60.3 is the value I want to extract. > > soup.find("div",id="curcondbox").findNext("span","b").renderContents() Thanks, but that isn't working for me. Here's my code: --------- import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=43085" page = urllib2.urlopen(url) soup = BeautifulSoup(page) daytemp = soup.find("div",id="curcondbox").findNext("span","b").renderContents() print "Today's temperature in Worthington is: ", daytemp --------- When I try this, I get this error: HTMLParseError: malformed start tag, at line 1516, column 60 Could someone suggest how to proceed? Thanks. CM _________________________________________________________________ Windows Live? SkyDrive?: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_SD_25GB_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jul 17 19:36:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jul 2009 13:36:15 -0400 Subject: [Tutor] Form values In-Reply-To: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> References: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> Message-ID: <1c2a2c590907171036w44d4eca3k9b2d87aec2bd6146@mail.gmail.com> On Fri, Jul 17, 2009 at 12:43 PM, wrote: > Hi, I am reading values from a form and writing them to a text file. I keep getting > a syntax error for outfile=open("filename", "a")I cant see it, does any body else. Indentation problems can cause mysterious syntax errors. Use a text editor that can show spaces and tabs and make sure your indentation is consistent. Kent From motoom at xs4all.nl Fri Jul 17 19:40:17 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 17 Jul 2009 19:40:17 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> Message-ID: <4A60B781.3090208@xs4all.nl> Che M wrote: > Thanks, but that isn't working for me. That's because BeautifulSoup isn't able to parse that webpage, not because the statement I posted doesn't work. I had BeautifulSoup parse the HTML fragment you posted earlier instead of the live webpage. This is actually the first time I see that BeautifulSoup is NOT able to parse a webpage... Greetings, From lie.1296 at gmail.com Fri Jul 17 19:42:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 18 Jul 2009 03:42:28 +1000 Subject: [Tutor] != -1: versus == 1 In-Reply-To: References: Message-ID: pedro wrote: > Hi I have been trying to understand a python script and I keep coming > across this kind of structure > that says "If it is not equal to negative one" > > ################################ > for line in theLines: > if line.find("Source Height") != -1: > #etc... > ################################### > > Is there some special reason for this. Why not just write "If it is > equal to one" > > ######################### > for line in theLines: > if line.find("Source Height") == 1: > #etc... > ################################### Nothing special, it just they have different meaning (and different results). The former (!= -1) tests whether the str.find() method does not fail finding "Source Height" (i.e. str.find() succeeds finding "Source Height") while the latter tests whether "Source Height" is in the second position in the string. But if it were me, I'd write the former (!= -1) with 'in' operator: for line in theLines: if "Source Height" in line: ... From bgailer at gmail.com Fri Jul 17 19:48:10 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 17 Jul 2009 13:48:10 -0400 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907162259s35568073h858081b9cf8df5dd@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> <50e459210907161120i5176e1do744a399cb26eb6d@mail.gmail.com> <4A5F96DE.90205@gmail.com> <50e459210907162259s35568073h858081b9cf8df5dd@mail.gmail.com> Message-ID: <4A60B95A.9090205@gmail.com> Chris Castillo wrote: > how would i go about adding the names to a dictionary as a key and the > scores as a value in this code? > > # refactored for better use of Python, correct logic, and flow scores = {} # empty dictionary total = 0 for line in open("bowlingscores.txt", "r"): if line.strip().isdigit(): score = int(line) scores[name] = score total += score else: name = line.strip() averageScore = total / len(scores) fileOut = open("bowlingaverages.txt", "w") fileOut.write("Bowling Report\n" + ("-" * 50) + "\n") for name, score in scores.items(): if score == 300: score = "\tPerfect score!" elif score < averageScore: score = "\tBelow average" elif score > averageScore: score = "\tAbove average!" else: score = "\tAverage!" print name, score -- Bob Gailer Chapel Hill NC 919-636-4239 From pine508 at hotmail.com Fri Jul 17 19:50:42 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 13:50:42 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: <1c2a2c590907170509o32692f28l47b6c71125ff978f@mail.gmail.com> References: <1c2a2c590907170509o32692f28l47b6c71125ff978f@mail.gmail.com> Message-ID: > Date: Fri, 17 Jul 2009 08:09:10 -0400 > Subject: Re: [Tutor] weather scraping with Beautiful Soup > From: kent37 at tds.net > To: pine508 at hotmail.com > CC: tutor at python.org > > On Thu, Jul 16, 2009 at 11:21 PM, Che M wrote: > > Hi, > > > > I am interested in gathering simple weather data using Beautiful Soup, but > > am having trouble understanding what I'm doing. I have searched the > > archives and so far haven't found enough to get me moving forward. > > > > Basically I am trying to start off this example: > > > > Grabbing Weather Underground Data with BeautifulSoup > > http://flowingdata.com/2007/07/09/grabbing-weather-underground-data-with-beautifulsoup/ > > > > But I get to the exact same problem that this other person got to in this > > post: > > http://groups.google.com/group/beautifulsoup/browse_thread/thread/13eb3dbf713b8a4a > > > > Unfortunately, that post never gives enough help for me to understand how to > > solve that person's or my problem. > > > > What I want to understand is how to find the bits of data you want--in this > > case, say, today's average temperature and whether it was clear or > > cloudy--within a web page, and then indicate that to Beautiful Soup. > > One thing that might help is to use the Lite page, if you are not > already. It has much less formatting and extraneous information to > wade through. I was not aware Weather Underground had a Lite page; thank you, that is good to know. It was easier to figure things out in that HTML. I am getting closer, but still a bit stuck. Here is my code for the Lite page: ------------ import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.wund.com/cgi-bin/findweather/getForecast?query=Worthington%2C+OH" page = urllib2.urlopen(url) soup = BeautifulSoup(page) daytemp = soup.find("div",id="main").findNext("h3").renderContents() print "Today's temperature in Worthington is: ", daytemp ------------- This works, but gives this output: >>> Today's temperature in Worthington is: 75 °F Of course, I just want the 75, not the HTML tags, etc. around it. But I am not sure how to indicate that in Beautiful Soup. So, for example, if I change the soup.find line above to this (to incorporate the ): daytemp = soup.find("div",id="main").findNext("h3", "span").renderContents() then I get the following error: AttributeError: 'NoneType' object has no attribute 'renderContents' (I also don't understand what the point of having a tag with no style content in the page?) Any help is appreciated. This still feels kind of arcane, but I want to understand the general approach to doing this, as later I want to try other weather facts or screen scraping generally. Thanks. CM You might also look for a site that has weather data > formatted for computer. For example the NOAA has forcast data > available as plain text: > http://forecast.weather.gov/product.php?site=NWS&issuedby=BOX&product=CCF&format=txt&version=1&glossary=0 > > Kent _________________________________________________________________ Lauren found her dream laptop. Find the PC that?s right for you. http://www.microsoft.com/windows/choosepc/?ocid=ftp_val_wl_290 -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Fri Jul 17 20:02:22 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 17 Jul 2009 20:02:22 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <1c2a2c590907170509o32692f28l47b6c71125ff978f@mail.gmail.com> Message-ID: <4A60BCAE.1050103@xs4all.nl> Che M wrote: > "http://www.wund.com/cgi-bin/findweather/getForecast?query=Worthington%2C+OH" > > Any help is appreciated. That would be: daytemp = soup.find("div",id="main").findNext("span").renderContents() -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From sander.sweers at gmail.com Fri Jul 17 20:04:00 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 17 Jul 2009 20:04:00 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: <4A60B781.3090208@xs4all.nl> References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: 2009/7/17 Michiel Overtoom : > This is actually the first time I see that BeautifulSoup is NOT able to > parse a webpage... Depends on which version is used. If 3.1 then it is much worse with malformed html than prior releases. See [1] for more info. Greets Sander [1] http://www.crummy.com/software/BeautifulSoup/3.1-problems.html From pine508 at hotmail.com Fri Jul 17 20:28:58 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 14:28:58 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: <4A60BCAE.1050103@xs4all.nl> References: <1c2a2c590907170509o32692f28l47b6c71125ff978f@mail.gmail.com> <4A60BCAE.1050103@xs4all.nl> Message-ID: > Date: Fri, 17 Jul 2009 20:02:22 +0200 > From: motoom at xs4all.nl > To: tutor at python.org > CC: pine508 at hotmail.com > Subject: Re: [Tutor] weather scraping with Beautiful Soup > > Che M wrote: > > > "http://www.wund.com/cgi-bin/findweather/getForecast?query=Worthington%2C+OH" > > > > Any help is appreciated. > > That would be: > > daytemp = soup.find("div",id="main").findNext("span").renderContents() > Thank you, that works! I'll go try some more things and read more of the documentation and if I bump into more confusions I may have more questions. Che _________________________________________________________________ Lauren found her dream laptop. Find the PC that?s right for you. http://www.microsoft.com/windows/choosepc/?ocid=ftp_val_wl_290 -------------- next part -------------- An HTML attachment was scrubbed... URL: From amrita at iisermohali.ac.in Fri Jul 17 20:37:07 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Sat, 18 Jul 2009 00:07:07 +0530 (IST) Subject: [Tutor] how to join two different files Message-ID: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> Hi, I have two large different column datafiles now i want to join them as single multi-column datafile:-- I tried the command:------ >>> file('ala', 'w').write(file('/home/amrita/alachems/chem2.txt', 'r').read()+file('/home/amrita/pdbfile/pdb2.txt', 'r').read()) but it is priniting second file after first, whereas i want to join them columwise like:--- FileA FileB FileC 12 14 12 14 15 + 16 = 15 16 18 17 18 17 20 19 20 19 What command I should use? Thanks, Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From pedrooconnell at gmail.com Fri Jul 17 20:40:02 2009 From: pedrooconnell at gmail.com (pedro) Date: Fri, 17 Jul 2009 14:40:02 -0400 Subject: [Tutor] != -1: versus == 1 References: Message-ID: Thanks for the replies. I think my mistake was assuming that "1" meant "true" when if fact it means "index 1". Whe I tested for "== 1", since "Source Height" was coincidentally at index 1 it returned something which looked like it worked. Thanks for the clarification. And thanks for the suggestion to use "in" that is much more readable. Pete From pine508 at hotmail.com Fri Jul 17 20:42:27 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 14:42:27 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: > 2009/7/17 Michiel Overtoom : > > This is actually the first time I see that BeautifulSoup is NOT able to > > parse a webpage... > > Depends on which version is used. If 3.1 then it is much worse with > malformed html than prior releases. See [1] for more info. > > Greets > Sander > > [1] http://www.crummy.com/software/BeautifulSoup/3.1-problems.html Yes....I just read about the 3.1 problems, and switched to 3.07a, re-ran the exact same code as befor...and it worked perfectly this time. (For those novices who are unsure of how to install a previous version, I found that I only had to simply clear out what BS files I had already under site-packages, and just put the Beautiful Soup.py 3.0.7a file found on the website into that site-packages folder...very easy). Lots of useful information today, thank you to everyone. Che _________________________________________________________________ Windows Live? SkyDrive?: Get 25 GB of free online storage. http://windowslive.com/online/skydrive?ocid=TXT_TAGLM_WL_SD_25GB_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From keithabt at beyondbb.com Fri Jul 17 20:52:07 2009 From: keithabt at beyondbb.com (keithabt at beyondbb.com) Date: Fri, 17 Jul 2009 14:52:07 -0400 Subject: [Tutor] sending to file Message-ID: I have a form and script that works. I can enter values into the fields, however the data will not show up on the server in the text file. The properties for the file is 0777. Can the form cause this problem?
    Please feel out the entire form:
Name:
Email Address:
Mailing Address:
Telephone Number:
""" fileName = "requests.txt" # Create instance of FieldStorage Form = cgi.FieldStorage() # Get data from fields if Form and Form['submit'].value == "Submit": the_name = Form.getvalue('name') the_email = Form.getvalue('email') the_address = Form.getvalue('address') the_telephone = Form.getvalue('telephone') IpAddress = cgi.escape(os.environ["REMOTE_ADDR"]); Time = "(time.localtime()):", time.asctime(time.localtime()) entry = name + '|' + email + '|' + address + '|' + telephone + '|' + IpAddress + '|' + Time + "\n" Outfile=open("fileName", "a") Outfile.write(entry) Outfile.close() From keithabt at beyondbb.com Fri Jul 17 20:55:47 2009 From: keithabt at beyondbb.com (keithabt at beyondbb.com) Date: Fri, 17 Jul 2009 14:55:47 -0400 Subject: [Tutor] sending to a file Message-ID: <84.85.27067.339C06A4@mxo5.broadbandsupport.net> I have a form and script that works. I can enter values into the fields, however the data will not show up on the server in the text file. The properties for the file is 0777. Can the form cause this problem? -------------- next part -------------- A non-text attachment was scrubbed... Name: 28359-form method.docx Type: application/octet-stream Size: 13284 bytes Desc: not available URL: From alan.gauld at btinternet.com Fri Jul 17 20:59:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jul 2009 19:59:11 +0100 Subject: [Tutor] how to join two different files References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> Message-ID: wrote > but it is priniting second file after first, whereas i want to join them > columwise like:--- > > FileA FileB FileC > 12 14 12 14 > 15 + 16 = 15 16 > 18 17 18 17 > 20 19 20 19 > I'm not sure what the plus sign in the second line signifies but otherwise it looks like you will need to process each file line by line and concatenate each string. for line1 in fileA: line2 = fileB.readline() fileC.write("%s\t%s" % line1,line2) You might need to strip the lines before writing them... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Fri Jul 17 21:14:13 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 17 Jul 2009 12:14:13 -0700 Subject: [Tutor] how to join two different files In-Reply-To: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> Message-ID: On 7/17/2009 11:37 AM amrita at iisermohali.ac.in said... > Hi, > > I have two large different column datafiles now i want to join them as > single multi-column datafile:-- > > I tried the command:------ > >>>> file('ala', 'w').write(file('/home/amrita/alachems/chem2.txt', > 'r').read()+file('/home/amrita/pdbfile/pdb2.txt', 'r').read()) > > but it is priniting second file after first, whereas i want to join them > columwise like:--- > > FileA FileB FileC > 12 14 12 14 > 15 + 16 = 15 16 > 18 17 18 17 > 20 19 20 19 > > What command I should use? Assuming it's this simple, otherwise flavor to taste... delim= '\t' file('ala', 'w').writelines( [ delim.join([ii,jj] for ii,jj in zip( [xx.strip() for xx in file('/home/amrita/alachems/chem2.txt','r').readlines() ], file('/home/amrita/pdbfile/pdb2.txt', 'r').readlines() ) ] ) Emile From kent37 at tds.net Fri Jul 17 22:27:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jul 2009 16:27:54 -0400 Subject: [Tutor] how to join two different files In-Reply-To: References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> Message-ID: <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> On Fri, Jul 17, 2009 at 3:14 PM, Emile van Sebille wrote: > delim= '\t' > > file('ala', 'w').writelines( > ?[ delim.join([ii,jj] for ii,jj in > ? ?zip( > ? ? ?[xx.strip() for xx in > ? ? ? ?file('/home/amrita/alachems/chem2.txt','r').readlines() > ? ? ? ?], > ? ? ?file('/home/amrita/pdbfile/pdb2.txt', 'r').readlines() > ? ? ?) > ? ?] > ?) Maybe you could break that up a bit? This is the tutor list, not a one-liner competition! Kent From emile at fenx.com Fri Jul 17 23:25:42 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 17 Jul 2009 14:25:42 -0700 Subject: [Tutor] how to join two different files In-Reply-To: <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> Message-ID: On 7/17/2009 1:27 PM Kent Johnson said... > On Fri, Jul 17, 2009 at 3:14 PM, Emile van Sebille wrote: > >> delim= '\t' >> >> file('ala', 'w').writelines( >> [ delim.join([ii,jj] for ii,jj in >> zip( >> [xx.strip() for xx in >> file('/home/amrita/alachems/chem2.txt','r').readlines() >> ], >> file('/home/amrita/pdbfile/pdb2.txt', 'r').readlines() >> ) >> ] >> ) > > Maybe you could break that up a bit? > This is the tutor list, not a > one-liner competition! > Yeah, I knew that -- but as the OP submitted a one-liner to start with, I simply responded in kind. That's why I put the flavor-to-taste comment on... Emile From pine508 at hotmail.com Fri Jul 17 23:27:33 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 17:27:33 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: OK, got the very basic case to work when using Beautiful Soup 3.0.7a and scraping the Weather Underground Lite page. That gives me the current temperature, etc. Good. But now I would like the average temperature from, say, yesterday. I am again having trouble finding elements in the soup. This is the code: ---------------------- import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KPAJAMES1&month=7&day=16&year=2009" page = urllib2.urlopen(url) soup = BeautifulSoup(page) table = soup.find("td",id="dataTable tm10") print table ------------------------ When I look at the page source for that page, there is this section, which contains the "dataTable tm10" table I want to zoom in on: ------------ -------------- And yet when I run the above code, what it prints is: >> None In other words, it is not finding that table. Why? Help appreciated again. Che _________________________________________________________________ Lauren found her dream laptop. Find the PC that?s right for you. http://www.microsoft.com/windows/choosepc/?ocid=ftp_val_wl_290 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Fri Jul 17 23:49:23 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 17 Jul 2009 14:49:23 -0700 Subject: [Tutor] large strings and garbage collection Message-ID: This was discussed in a previous post but I didn't see a solution. Say, you have for i in veryLongListOfStringValues: s += i As per previous post (http://thread.gmane.org/gmane.comp.python.tutor/54029/focus=54139), (quoting verbatim) "... the following happens inside the python interpreter: 1. get a reference to the current value of s. 2. get a reference to the string value i. 3. compute the new value += i, store it in memory, and make a reference to it. 4. drop the old reference of s (thus free-ing "abc") 5. give s a reference to the newly computed value. After step 3 and before step 4, the old value of s is still referenced by s, and the new value is referenced internally (so step 5 can be performed). In other words, both the old and the new value are in memory at the same time after step 3 and before step 4, and both are referenced (that is, they cannot be garbage collected). ... " As s gets very large, how do you deal with this situation to avoid a memory error or what I think will be a general slowing down of the system if the for-loop is repeated a large number of times. Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jul 18 00:27:32 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jul 2009 23:27:32 +0100 Subject: [Tutor] sending to file References: Message-ID: wrote >I have a form and script that works. I can enter values into the fields, >however > the data will not show up on the server in the text file. The properties > for the > file is 0777. Can the form cause this problem? Does the problem only occur when running it on the web server or does it occur if you run it as yourself? Do you know where the file is trying to write to? Is it the cgi-bin folder or the root folder? What are the permissions of the folder? 777 is probably a bad idea! But let's get the file created first and worry about security later! :-) >
action="http://web.nmsu.edu/~keithabt/cgi-bin/07_index.cgi"> >
    Please feel out the entire form:
>
  Current: High: Low: Average:
Temperature: 73.6 °F 83.3 °F 64.2 °F 74.1 °F
> > > > > > > > > >
Name:
Email Address:
Mailing Address:
Telephone Number: value="telephone">
> > > > """ > fileName = "requests.txt" > # Create instance of FieldStorage > Form = cgi.FieldStorage() > > # Get data from fields > if Form and Form['submit'].value == "Submit": > the_name = Form.getvalue('name') > the_email = Form.getvalue('email') > the_address = Form.getvalue('address') > the_telephone = Form.getvalue('telephone') > > > IpAddress = cgi.escape(os.environ["REMOTE_ADDR"]); > Time = "(time.localtime()):", time.asctime(time.localtime()) > > entry = name + '|' + email + '|' + address + '|' + telephone + '|' + > IpAddress > + '|' + Time + "\n" We'll have more success if you send us the real code. The variables here don't match those above... > > Outfile=open("fileName", "a") > Outfile.write(entry) > Outfile.close() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jul 18 00:32:12 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Jul 2009 23:32:12 +0100 Subject: [Tutor] large strings and garbage collection References: Message-ID: "Dinesh B Vadhia" wrote > This was discussed in a previous post but I didn't see a solution. Say, > you have > > for i in veryLongListOfStringValues: > s += i In general avoid string addition. (Although recent versions of Python have optimised it somewhat) > As s gets very large, how do you deal with this situation to avoid > a memory error or what I think will be a general slowing down > of the system if the for-loop is repeated a large number of times. Avoid string addition. join() is one way, a format string might also work - but I haven't benchmarked that for memory or speed fmt = "%s" * len(biglist) s = fmt % tuple(biglist) Just some ideas... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From roadierich at googlemail.com Sat Jul 18 00:49:23 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Fri, 17 Jul 2009 23:49:23 +0100 Subject: [Tutor] Form values In-Reply-To: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> References: <1E.C8.09691.C1AA06A4@mxo4.broadbandsupport.net> Message-ID: 2009/7/17 : > Hi, I am reading values from a form and writing them to a text file. I keep getting > a syntax error for outfile=open("filename", "a")I cant see it, does any body else. > > > fileName = "requests.txt" > # Create instance of FieldStorage > Form = cgi.FieldStorage() > > # Get data from fields > if Form and Form['submit'].value == "Submit": > > ? ? ? ?the_name = Form.getvalue('name') > ? ? ? ?the_email = Form.getvalue('email') > ? ? ? ?the_address = Form.getvalue('address') > ? ? ? ?the_telephone = Form.getvalue('telephone') > > > ? ? ? ?IpAddress = ?cgi.escape(os.environ["REMOTE_ADDR"]); > ? ? ? ?Time = "(time.localtime()):", time.asctime(time.localtime()) > > ? ? ? ?entry = name + '|' + email + '|' + address + '|' + telephone + '|' + > IpAddress + '|' + Time + "\n" > > > > > ? ? ? ?outfile=open("fileName", "a") > ? ? ? ?outfile.write(entry) > ? ? ? ?outfile.close() > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > There is an error before there: In the line entry = name + '|' + email + '|' + address + '|' + telephone + '|' + IpAddress + '|' + Time + "\n" None of the names are defined except IpAddress and Time. Everything else has "the_" prepended when it is defined earlier in the code, but, as you can see, not in the line were they are accessed. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From wescpy at gmail.com Sat Jul 18 00:50:35 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 17 Jul 2009 15:50:35 -0700 Subject: [Tutor] how to join two different files In-Reply-To: <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> Message-ID: <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> > Maybe you could break that up a bit? This is the tutor list, not a > one-liner competition! rather than one-liners, we can try to create the most "Pythonic" solution. below's my entry. :-) cheers, -wesley myMac$ cat parafiles.py #!/usr/bin/env python from itertools import izip from os.path import exists def parafiles(*files): vec = (open(f) for f in files if exists(f)) data = izip(*vec) [f.close() for f in vec] return data for data in parafiles('fileA.txt', 'fileB.txt'): print ' '.join(d.strip() for d in data) myMac$ cat fileA.txt FileA 12 15 18 20 myMac$ cat fileB.txt FileB 14 16 18 20 22 myMac$ parafiles.py FileA FileB 12 14 15 16 18 18 20 20 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sander.sweers at gmail.com Sat Jul 18 01:09:32 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 18 Jul 2009 01:09:32 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: 2009/7/17 Che M : > table = soup.find("td",id="dataTable tm10") Almost right. attrs should normall be a dict so {'class':'dataTable tm10'} but you can use a shortcut, read on. > ------------------------ > > When I look at the page source for that page, there is this section, which > contains the "dataTable tm10" table I want to zoom in on: > > ------------ > > > > > > > > > > > > > > > > > > -------------- The tag you are looking for is table not td. The tag td is inside the table tag. So with shortcut it looks like, table = soup.find("table","dataTable tm10") or without shortcut, table = soup.find("table",{'class':'dataTable tm10'}) Greets Sander From roadierich at googlemail.com Sat Jul 18 01:19:23 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 18 Jul 2009 00:19:23 +0100 Subject: [Tutor] large strings and garbage collection In-Reply-To: References: Message-ID: 2009/7/17 Dinesh B Vadhia : > This was discussed in a previous post but I didn't see a solution.? Say, you > have > > for i in veryLongListOfStringValues: > ??? s += i > > As per previous post > (http://thread.gmane.org/gmane.comp.python.tutor/54029/focus=54139), > (quoting verbatim) "... the following happens inside the python interpreter: > > 1. get a reference to the current value of s. > 2. get a reference to the string value i. > 3. compute the new value += i, store it in memory, and make a reference to > it. > 4. drop the old reference of s (thus free-ing "abc") > 5. give s a reference to the newly computed value. > > After step 3 and before step 4, the old value of s is still referenced by s, > and the new value is referenced internally (so step 5 can be performed). In > other words, both the old and the new value are in memory at the same time > after step 3 and before step 4, and both are referenced (that is, they > cannot be garbage collected). ... " > > As s gets very large, how do you deal with this situation to avoid a memory > error or what I think will be a general slowing down of the system if the > for-loop is repeated a large number of times. > > Dinesh > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > If all you are doing is concatenating a list of strings, use the str.join() method, which is designed for the job: >>> listOfStrings ['And', 'now', 'for', 'something', 'completely', 'different.'] >>> print " ".join(listOfStrings) And now for something completely different. >>> print "_".join(listOfStrings) And_now_for_something_completely_different. If you need to perform other operations first, you can pass a generator expression as the argument, for example: >>> " ".join((s.upper() if n%2 else s.lower()) for n, s in enumerate(listOfStrings)) 'and NOW for SOMETHING completely DIFFERENT.' Hope that helps you. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From srilyk at gmail.com Sat Jul 18 01:27:52 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 17 Jul 2009 18:27:52 -0500 Subject: [Tutor] sending to a file In-Reply-To: <83.13.27067.AD6F06A4@mxo5.broadbandsupport.net> References: <83.13.27067.AD6F06A4@mxo5.broadbandsupport.net> Message-ID: <333efb450907171627s6e53b28ajfd8b85c14d3918c5@mail.gmail.com> On Fri, Jul 17, 2009 at 5:10 PM, wrote: > > > On Fri Jul 17 17:51 , Wayne sent: > > >On Fri, Jul 17, 2009 at 1:55 PM, wrote: > > > > > > > > > >I have a form and script that works. I can enter values into the fields, > however > > > >the data will not show up on the server in the text file. The properties > for the > > > >file is 0777. Can the form cause this problem? > >Are the properties for the parent directories set to read/write? > >-Wayne > > Yes, they are for the owner. > If the script is being executed from a user that's not the owner, you'll have problems. Try letting the script create the file and see if you still have problems. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Sat Jul 18 02:32:50 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 17 Jul 2009 20:32:50 -0400 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: > Date: Sat, 18 Jul 2009 01:09:32 +0200 > From: sander.sweers at gmail.com > To: tutor at python.org > Subject: Re: [Tutor] weather scraping with Beautiful Soup > > 2009/7/17 Che M : > > table = soup.find("td",id="dataTable tm10") > > Almost right. attrs should normall be a dict so {'class':'dataTable > tm10'} but you can use a shortcut, read on. > > > ------------------------ > > > > When I look at the page source for that page, there is this section, which > > contains the "dataTable tm10" table I want to zoom in on: > > > > ------------ > >
 Current:High:Low:Average:
Temperature: > 73.6 °F > > 83.3 °F > > 64.2 °F > > 74.1 °F >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > -------------- > > The tag you are looking for is table not td. The tag td is inside the > table tag. So with shortcut it looks like, > > table = soup.find("table","dataTable tm10") > > or without shortcut, > > table = soup.find("table",{'class':'dataTable tm10'}) > > Greets > Sander Thank you. I was able to find the table in the soup this way. After a surprising amount of tinkering (for some reason this Soup is more like chowder than broth for me still), I was able to get my goal, that 74.1 above, using this: ------------------- import urllib2 from BeautifulSoup import BeautifulSoup url = "http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KPAJAMES1&month=7&day=16&year=2009" page = urllib2.urlopen(url) soup = BeautifulSoup(page) table = soup.find("table","dataTable tm10") #find the table tbody = table.find("tbody") #find the table's body alltd = tbody.findAll('td') #find all the td's temp_full = alltd[4] #identify the 4th td, the one I want. print 'temp_full = ', temp_full temp = temp_full.findNext('span','b').renderContents() #into the span and b and render print 'temp = ', temp ---------------------- Does this seem like the right (most efficient/readable) way to do this? Thanks for your time. CM _________________________________________________________________ Hotmail? has ever-growing storage! Don?t worry about storage limits. http://windowslive.com/Tutorial/Hotmail/Storage?ocid=TXT_TAGLM_WL_HM_Tutorial_Storage_062009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sat Jul 18 08:31:57 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 17 Jul 2009 23:31:57 -0700 Subject: [Tutor] large strings and garbage collection In-Reply-To: References: Message-ID: join with generator expression is what was needed. terrific! From: Rich Lovely Sent: Friday, July 17, 2009 4:19 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] large strings and garbage collection 2009/7/17 Dinesh B Vadhia : > This was discussed in a previous post but I didn't see a solution. Say, you > have > > for i in veryLongListOfStringValues: > s += i > > As per previous post > (http://thread.gmane.org/gmane.comp.python.tutor/54029/focus=54139), > (quoting verbatim) "... the following happens inside the python interpreter: > > 1. get a reference to the current value of s. > 2. get a reference to the string value i. > 3. compute the new value += i, store it in memory, and make a reference to > it. > 4. drop the old reference of s (thus free-ing "abc") > 5. give s a reference to the newly computed value. > > After step 3 and before step 4, the old value of s is still referenced by s, > and the new value is referenced internally (so step 5 can be performed). In > other words, both the old and the new value are in memory at the same time > after step 3 and before step 4, and both are referenced (that is, they > cannot be garbage collected). ... " > > As s gets very large, how do you deal with this situation to avoid a memory > error or what I think will be a general slowing down of the system if the > for-loop is repeated a large number of times. > > Dinesh > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > If all you are doing is concatenating a list of strings, use the str.join() method, which is designed for the job: >>> listOfStrings ['And', 'now', 'for', 'something', 'completely', 'different.'] >>> print " ".join(listOfStrings) And now for something completely different. >>> print "_".join(listOfStrings) And_now_for_something_completely_different. If you need to perform other operations first, you can pass a generator expression as the argument, for example: >>> " ".join((s.upper() if n%2 else s.lower()) for n, s in enumerate(listOfStrings)) 'and NOW for SOMETHING completely DIFFERENT.' Hope that helps you. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amrita at iisermohali.ac.in Sat Jul 18 08:28:55 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Sat, 18 Jul 2009 11:58:55 +0530 (IST) Subject: [Tutor] how to join two different files In-Reply-To: <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> Message-ID: <11872.210.212.36.65.1247898535.squirrel@www.iisermohali.ac.in> Thankyou sir it is working.....but one more thing i want to ask that if my file will have entries like:--- fileA and fileB 12 10 13 12 14 15 means if their no. of entries will not match then how to combine them(both input files have more than one column). Thanks, Amrita >> Maybe you could break that up a bit? This is the tutor list, not a >> one-liner competition! > > rather than one-liners, we can try to create the most "Pythonic" > solution. below's my entry. :-) > > cheers, > -wesley > > myMac$ cat parafiles.py > #!/usr/bin/env python > > from itertools import izip > from os.path import exists > > def parafiles(*files): > vec = (open(f) for f in files if exists(f)) > data = izip(*vec) > [f.close() for f in vec] > return data > > for data in parafiles('fileA.txt', 'fileB.txt'): > print ' '.join(d.strip() for d in data) > > myMac$ cat fileA.txt > FileA > 12 > 15 > 18 > 20 > > myMac$ cat fileB.txt > FileB > 14 > 16 > 18 > 20 > 22 > > myMac$ parafiles.py > FileA FileB > 12 14 > 15 16 > 18 18 > 20 20 > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From roadierich at googlemail.com Sat Jul 18 08:59:29 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 18 Jul 2009 07:59:29 +0100 Subject: [Tutor] how to join two different files In-Reply-To: <11872.210.212.36.65.1247898535.squirrel@www.iisermohali.ac.in> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> <11872.210.212.36.65.1247898535.squirrel@www.iisermohali.ac.in> Message-ID: 2009/7/18 : > Thankyou sir it is working.....but one more thing i want to ask that if my > file will have entries like:--- > > fileA and fileB > 12 ? ? ? ? 10 > 13 ? ? ? ? 12 > 14 > 15 > > means if their no. of entries will not match then how to combine them(both > input files have more than one column). > > Thanks, > Amrita > > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > That depends entirely on what you want to happen when you encounter a row that doesn't have an entry in one of the files. The previous code, using izip(), will stop at the end of the shortest file. If you want to pad the short file, (i.e. add values to make it the same length as the longer file) you can use itertools.izip_longest(). Look it up in the docs for usage. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From wescpy at gmail.com Sat Jul 18 09:46:32 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 18 Jul 2009 00:46:32 -0700 Subject: [Tutor] how to join two different files In-Reply-To: References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> <11872.210.212.36.65.1247898535.squirrel@www.iisermohali.ac.in> Message-ID: <78b3a9580907180046q79a2f45crfe28c418c342d302@mail.gmail.com> >> Thankyou sir it is working.....but one more thing i want to ask that if my >> file will have entries like:--- >> >> fileA and fileB >> 12 ? ? ? ? 10 >> 13 ? ? ? ? 12 >> 14 >> 15 >> >> means if their no. of entries will not match then how to combine them(both >> input files have more than one column). this is up to you and what type of solution you want to implement. rich (see below) has a great idea that you can use to address your situation. one thing that is *very* important is to not just copy a working solution that tutors have posted, but to truly study each snippet of code to fully understand exactly how every line works, because you will have to come up with solutions on your own at some point, so this should be a good lesson to learn. so far, several examples have been posted, but you should compare and contrast them, and decide for yourself which ones you like, which ones you don't, and why (or why not). you will become a much better Python programmer in a shorter period of time! the tutors are here to help get you jumpstarted with the language, and not necessarily to always provide you with an answer. > That depends entirely on what you want to happen when you encounter a > row that doesn't have an entry in one of the files. ?The previous > code, using izip(), will stop at the end of the shortest file. ?If you > want to pad the short file, (i.e. add values to make it the same > length as the longer file) you can use itertools.izip_longest(). ?Look > it up in the docs for usage. excellent idea... i would highly encourage everyone to study this module. it has breaktaking Python code, much in line with snippets you'd find in the Cookbook, and yes, i expose students to this in my intro Python course! http://docs.python.org/library/itertools.html cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Sat Jul 18 09:57:42 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 18 Jul 2009 00:57:42 -0700 Subject: [Tutor] how to join two different files In-Reply-To: <78b3a9580907180046q79a2f45crfe28c418c342d302@mail.gmail.com> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> <11872.210.212.36.65.1247898535.squirrel@www.iisermohali.ac.in> <78b3a9580907180046q79a2f45crfe28c418c342d302@mail.gmail.com> Message-ID: <78b3a9580907180057l270a45f5n20541f08d6afb8cd@mail.gmail.com> on a related note, there is a module called fileinput that doesn't do what you (the OP) need for this particular problem, but it is one to keep in mind for the future as there may be a situation for which it is the right tool. it doesn't get a lot of buzz but can come in handy -- for me, it was in a code golf* contest. :-) http://docs.python.org/library/fileinput.html * - on the topic of code golf -- http://codegolf.com -- certainly, solutions for these contests shouldn't be placed in production, but they are fun and interesting challenges while exercising your knowledge of a programming language. best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sander.sweers at gmail.com Sat Jul 18 14:28:38 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 18 Jul 2009 14:28:38 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: 2009/7/18 Che M : > table = soup.find("table","dataTable tm10")? #find the table > tbody = table.find("tbody")????????????????? #find the table's body You can do this in one step. tbody = soup.find('tbody') Greets Sander From cpeachey at sfu.ca Sat Jul 18 04:53:44 2009 From: cpeachey at sfu.ca (Cassandra Peachey) Date: Fri, 17 Jul 2009 19:53:44 -0700 (PDT) Subject: [Tutor] Help with % conversion to output colour Message-ID: <224729952.4378001247885624183.JavaMail.root@jaguar7.sfu.ca> Hi, I'm working on an assignment that requires the user RGB requested output to create a colour block in fractional steps.? I'm pretty much down to the last bit, however, I've hit a road block in that my percentages are not showing as a colour block but as the
tag percentages. Any suggestions on what I'm missing to output the %'s into the colour block showing colour? Thanks for any help. Cassandra import cgi form = cgi.FieldStorage() # print HTTP/HTML header stuff print "Content-type: text/html" print print""" Colour Blend

Colour Blend

Here is a mix of the colours you specified:

""" red1 = int(form["red1"].value) green1 = int(form["green1"].value) blue1 = int(form["blue1"].value) red2 = int(form["red2"].value) green2 = int(form["green2"].value) blue2 = int(form["blue2"].value) nsteps = int(form["steps"].value) if nsteps > 150: ??? nsteps = 150 for i in range(0,nsteps-1): ??? fraction = (i+1.0)/nsteps ??? r = (1-fraction)*red1 + fraction*red2 ??? g = (1-fraction)*green1 + fraction*green2 ??? b = (1-fraction)*blue1 + fraction*blue2 ??? print '
" print "" -------------- next part -------------- An HTML attachment was scrubbed... URL: From motoom at xs4all.nl Sat Jul 18 14:37:56 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sat, 18 Jul 2009 14:37:56 +0200 Subject: [Tutor] weather scraping with Beautiful Soup In-Reply-To: References: <4A605218.7010702@xs4all.nl> <4A60B781.3090208@xs4all.nl> Message-ID: <4A61C224.8050601@xs4all.nl> Sander Sweers wrote: > 2009/7/18 Che M : >> table = soup.find("table","dataTable tm10") #find the table >> tbody = table.find("tbody") #find the table's body > > You can do this in one step. > > tbody = soup.find('tbody') Yeah, but what if the document contains multiple tables, and you want explicitely the one with the class 'dataTable tm10'? In such a case it doesn't hurt to progressively narrow down on the wanted element. It also makes the scrape code more robust against page changes. Someone could add an extra table to the start of the page to host a search box, for example. From bgailer at gmail.com Sat Jul 18 15:50:44 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 18 Jul 2009 09:50:44 -0400 Subject: [Tutor] Help with % conversion to output colour In-Reply-To: <224729952.4378001247885624183.JavaMail.root@jaguar7.sfu.ca> References: <224729952.4378001247885624183.JavaMail.root@jaguar7.sfu.ca> Message-ID: <4A61D334.6070202@gmail.com> Cassandra Peachey wrote: > > Hi, > > > > I'm working on an assignment that requires the user RGB requested > output to create a colour block in fractional steps. I'm pretty much > down to the last bit, however, I've hit a road block in that my > percentages are not showing as a colour block but as the
tag > percentages. > > > > Any suggestions on what I'm missing to output the %'s into the colour > block showing colour? > > > > Thanks for any help. > > Cassandra > > > > import cgi > form = cgi.FieldStorage() > > # print HTTP/HTML header stuff > print "Content-type: text/html" > print > print""" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";> > > > Colour Blend > > > >

Colour Blend

>

Here is a mix of the colours you specified:

>
""" > > red1 = int(form["red1"].value) > green1 = int(form["green1"].value) > blue1 = int(form["blue1"].value) > > red2 = int(form["red2"].value) > green2 = int(form["green2"].value) > blue2 = int(form["blue2"].value) > > nsteps = int(form["steps"].value) > > if nsteps > 150: > nsteps = 150 > > for i in range(0,nsteps-1): > fraction = (i+1.0)/nsteps > r = (1-fraction)*red1 + fraction*red2 > g = (1-fraction)*green1 + fraction*green2 > b = (1-fraction)*blue1 + fraction*blue2 > print '
" > The output of that is (e.g.)
" > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From tycho at tycho.ws Sat Jul 18 18:18:25 2009 From: tycho at tycho.ws (Tycho Andersen) Date: Sat, 18 Jul 2009 11:18:25 -0500 Subject: [Tutor] Very wierd namespace problem In-Reply-To: <1c2a2c590907171002t61db5ad3r4d726a524bb1d27b@mail.gmail.com> References: <1c2a2c590907171002t61db5ad3r4d726a524bb1d27b@mail.gmail.com> Message-ID: <49b3a7400907180918jc554edal446f768e5c30a15e@mail.gmail.com> On Fri, Jul 17, 2009 at 12:02 PM, Kent Johnson wrote: > Names beginning with __ are 'mangled' to make them sort of secret. > This is a feature: > http://docs.python.org/reference/expressions.html#index-889 Just to add a bit, this interpreter session may be enlightening: >>> class a: ... def __method(): ... pass ... >>> dir(a()) ['__doc__', '__module__', '_a__method'] \t From dineshbvadhia at hotmail.com Sat Jul 18 23:42:54 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 18 Jul 2009 14:42:54 -0700 Subject: [Tutor] python interpreter vs bat file Message-ID: During recent program testing, I ran a few Python programs from a Windows XP batch file which causes a memory error for one of the programs. If I run the same set of programs from the Python interpreter no memory error occurs. Any idea why this might be? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jul 19 00:17:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Jul 2009 23:17:16 +0100 Subject: [Tutor] python interpreter vs bat file References: Message-ID: "Dinesh B Vadhia" wrote > During recent program testing, I ran a few Python programs > from a Windows XP batch file which causes a memory error > for one of the programs. If I run the same set of programs > from the Python interpreter no memory error occurs. > Any idea why this might be? I'm not sure I understand what you are doing? Are you saying that in your bat file you entered commands like python file1.py python file2.py python file3.py And when you executed that bat file it gave a memory error? If so was that for a specific python file or was it for the bat file itself? And are you also saying that if you start a command window and type at the DOS prompt: C:\> python file1.py C:\> python file2.py C:\> python file3.py You don't get any errors? How are you running the bat file? Are you running it from the same DOS prompt that you run the python commansds or are you starting it some other way? Can you clarify please? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jeff at dcsoftware.com Sun Jul 19 00:24:10 2009 From: jeff at dcsoftware.com (Jeff Johnson) Date: Sat, 18 Jul 2009 15:24:10 -0700 Subject: [Tutor] python interpreter vs bat file In-Reply-To: References: Message-ID: <4A624B8A.6050906@dcsoftware.com> Need more information. Python works on Windows as good as anything else. Maybe even better. Dinesh B Vadhia wrote: > During recent program testing, I ran a few Python programs from a > Windows XP batch file which causes a memory error for one of the > programs. If I run the same set of programs from the Python interpreter > no memory error occurs. Any idea why this might be? > > Dinesh Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com From ctcast at gmail.com Sun Jul 19 07:15:16 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sun, 19 Jul 2009 00:15:16 -0500 Subject: [Tutor] reading complex data types from text file In-Reply-To: <4A60B95A.9090205@gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> <50e459210907161120i5176e1do744a399cb26eb6d@mail.gmail.com> <4A5F96DE.90205@gmail.com> <50e459210907162259s35568073h858081b9cf8df5dd@mail.gmail.com> <4A60B95A.9090205@gmail.com> Message-ID: <50e459210907182215i3a8fda9eo38e3312f3e17eaae@mail.gmail.com> so could I also replace the score of each bowler (key value) in the dictionary with a new key such as "below average" or "above average" according to each if-elif-else structure and then write to a text file in the following format? Jim Above Average Sue Below Average Bob Perfect score On Fri, Jul 17, 2009 at 12:48 PM, bob gailer wrote: > Chris Castillo wrote: > >> how would i go about adding the names to a dictionary as a key and the >> scores as a value in this code? >> >> >> # refactored for better use of Python, correct logic, and flow > > scores = {} # empty dictionary > total = 0 > for line in open("bowlingscores.txt", "r"): > if line.strip().isdigit(): > score = int(line) > scores[name] = score > total += score > else: > name = line.strip() > averageScore = total / len(scores) > fileOut = open("bowlingaverages.txt", "w") > fileOut.write("Bowling Report\n" + ("-" * 50) + "\n") > for name, score in scores.items(): > if score == 300: > score = "\tPerfect score!" > elif score < averageScore: > score = "\tBelow average" > elif score > averageScore: > score = "\tAbove average!" > else: > score = "\tAverage!" > print name, score > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sun Jul 19 07:25:53 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 18 Jul 2009 22:25:53 -0700 Subject: [Tutor] python interpreter vs bat file In-Reply-To: <4A624B8A.6050906@dcsoftware.com> References: <4A624B8A.6050906@dcsoftware.com> Message-ID: Not much more information available. Have a batch file (eg. 'test.bat') with entries: python "program a.py" python "program b.py" python "program c.py" python "program e.py" ... One of the programs (eg. 'program c.py') fails with a memory error when performing a pickle.dump: Traceback (most recent call last): ... File "....py", line 176, in pickleObject pickle.dump(self, f, 2) MemoryError When the programs are run in the same order from the Python interpreter there are no memory errors. This has happened before and it seems odd behavior. Dinesh From: Jeff Johnson Sent: Saturday, July 18, 2009 3:24 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] python interpreter vs bat file Need more information. Python works on Windows as good as anything else. Maybe even better. Dinesh B Vadhia wrote: > During recent program testing, I ran a few Python programs from a > Windows XP batch file which causes a memory error for one of the > programs. If I run the same set of programs from the Python interpreter > no memory error occurs. Any idea why this might be? > > Dinesh Jeff Jeff Johnson jeff at dcsoftware.com Phoenix Python User Group - sunpiggies at googlegroups.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jul 19 08:18:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jul 2009 07:18:08 +0100 Subject: [Tutor] python interpreter vs bat file References: <4A624B8A.6050906@dcsoftware.com> Message-ID: "Dinesh B Vadhia" wrote > Not much more information available. > Have a batch file (eg. 'test.bat') with entries: > > python "program a.py" > python "program b.py" > python "program c.py" > > One of the programs (eg. 'program c.py') fails with a > memory error when performing a pickle.dump: > > Traceback (most recent call last): > ... > File "....py", line 176, in pickleObject > pickle.dump(self, f, 2) > MemoryError > > When the programs are run in the same order from the > Python interpreter there are no memory errors. Can you elaborate on how you run the programs. It looks like an environmental issue so we need to know exactly what you are doing. How do you run the bat file? How do you run the programs "from the Python interpreter" Are you using Windows Explorer or a CMD wondow? or the Start->Run dialog etc? Which folders are you starting from in each case? > This has happened before and it seems odd behavior. So how did you fix it before? I've never seen or heard of this before. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dineshbvadhia at hotmail.com Sun Jul 19 14:40:41 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 19 Jul 2009 05:40:41 -0700 Subject: [Tutor] python interpreter vs bat file Message-ID: 1. Run Python Programs with Batch file Python programs run from a Windows XP batch file (test.bat) in a CMD window initiated from Windows Explorer. All programs except one execute successfully which stops with a memory error but batch file continues to execute other Python programs (as it should). 2. Run Python Programs with Python Interpreter Fire up Python Interpreter, open .py program, Run. When the program with the memory error in 1. is run independently as in 2. it works. Dinesh -------------------------------------------------------------------------------- Message: 4 Date: Sun, 19 Jul 2009 07:18:08 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] python interpreter vs bat file Message-ID: Content-Type: text/plain; format=flowed; charset="Windows-1252"; reply-type=original "Dinesh B Vadhia" wrote > Not much more information available. > Have a batch file (eg. 'test.bat') with entries: > > python "program a.py" > python "program b.py" > python "program c.py" > > One of the programs (eg. 'program c.py') fails with a > memory error when performing a pickle.dump: > > Traceback (most recent call last): > ... > File "....py", line 176, in pickleObject > pickle.dump(self, f, 2) > MemoryError > > When the programs are run in the same order from the > Python interpreter there are no memory errors. Can you elaborate on how you run the programs. It looks like an environmental issue so we need to know exactly what you are doing. How do you run the bat file? How do you run the programs "from the Python interpreter" Are you using Windows Explorer or a CMD wondow? or the Start->Run dialog etc? Which folders are you starting from in each case? > This has happened before and it seems odd behavior. So how did you fix it before? I've never seen or heard of this before. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From goodpotatoes at yahoo.com Sun Jul 19 07:34:53 2009 From: goodpotatoes at yahoo.com (gpo) Date: Sat, 18 Jul 2009 22:34:53 -0700 (PDT) Subject: [Tutor] UnicodeEncodeError Message-ID: <24554280.post@talk.nabble.com> I'm doing a simple excercise in reading a file, and printing each line. However, I'm getting this error. The file is a windows txt file, ecoded in ANSI(ascii). I don't understand why Pythin is displaying a Unicode error. Here is my script: f=open('I:\\PythonScripts\\statement.txt') for line in f: print (line) f.close() statement.txt is just a copy of the text from an article at (http://www.tgdaily.com/content/view/43296/98/) into notepad. The error I get is: Traceback (most recent call last): File "I:\PythonScripts\fileloop.py", line 9, in print (line) File "C:\Python31\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in position 10: character maps to I've looked this up, and see that others have had a similar error; however, I don't see any thing saying what I should be encoding to/from since my input and output files are both ascii. -- View this message in context: http://www.nabble.com/UnicodeEncodeError-tp24554280p24554280.html Sent from the Python - tutor mailing list archive at Nabble.com. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jul 19 14:53:38 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 19 Jul 2009 08:53:38 -0400 Subject: [Tutor] python interpreter vs bat file In-Reply-To: References: Message-ID: <4A631752.5060202@gmail.com> Dinesh B Vadhia wrote: > 1. Run Python Programs with Batch file > Python programs run from a Windows XP batch file (test.bat) in a CMD > window initiated from Windows Explorer. All programs except one > execute successfully which stops with a memory error but batch file > continues to execute other Python programs (as it should). What happens if you open a CMD window, run program 1, close CMD window, and repeat for the other programs? -- Bob Gailer Chapel Hill NC 919-636-4239 From metolone+gmane at gmail.com Sun Jul 19 18:47:02 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 19 Jul 2009 09:47:02 -0700 Subject: [Tutor] UnicodeEncodeError References: <24554280.post@talk.nabble.com> Message-ID: "gpo" wrote in message news:24554280.post at talk.nabble.com... > > I'm doing a simple excercise in reading a file, and printing each line. > However, I'm getting this error. The file is a windows txt file, ecoded > in > ANSI(ascii). I don't understand why Pythin is displaying a Unicode error. > > Here is my script: > > f=open('I:\\PythonScripts\\statement.txt') > for line in f: > print (line) > f.close() > > statement.txt is just a copy of the text from an article at > (http://www.tgdaily.com/content/view/43296/98/) into notepad. > > The error I get is: > > Traceback (most recent call last): > File "I:\PythonScripts\fileloop.py", line 9, in > print (line) > File "C:\Python31\lib\encodings\cp437.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u2014' in > position > 10: character maps to > > I've looked this up, and see that others have had a similar error; > however, > I don't see any thing saying what I should be encoding to/from since my > input and output files are both ascii. Notepad doesn't encode in ASCII. What it calls "ANSI" is the default file system encoding, which on US Windows is cp1252. I see you are using Python 3.1. When not given an explicit encoding, Python 3.1 defaults to the default file system encoding. It successfully reads the file, which happens to contain non-ASCII data. cp1252 supports the Unicode character \u2014 (EM DASH). However, when you try to print the file on the console, the console's default encoding is cp437 and doesn't support this character. On Python 3.1 there is a function, ascii(), that will display the contents of a string using ascii-only. Try print(ascii(line)). Another trick is to switch to Lucida Console font and change the console's code page to 1252 with the command "chcp 1252". This font and code page supports the EM DASH and will display the text properly with print(line). You can also use a shell that supports the full Unicode character set such as Idle or PythonWin instead of the console. -Mark From dkuhlman at rexx.com Sun Jul 19 20:56:15 2009 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sun, 19 Jul 2009 11:56:15 -0700 Subject: [Tutor] python interpreter vs bat file In-Reply-To: References: Message-ID: <20090719185615.GA5356@cutter.rexx.com> On Sun, Jul 19, 2009 at 05:40:41AM -0700, Dinesh B Vadhia wrote: > > 1. Run Python Programs with Batch file > > Python programs run from a Windows XP batch file (test.bat) in a CMD > window initiated from Windows Explorer. All programs except one > execute successfully which stops with a memory error but batch file > continues to execute other Python programs (as it should). > > > > 2. Run Python Programs with Python Interpreter > > Fire up Python Interpreter, open .py program, Run. > Dinesh - Please tell us how you did this. Did you type "python" at a command prompt and then see the ">>>" prompt? If so how did you "open .py program, Run"? Or, did you start Idle (or some other IDE) then click File-->Open, then run with the Run-->RunModule menu item? You have been asked several times for more information. You really need to read: http://catb.org/~esr/faqs/smart-questions.html There are people on this list who are very generous with their time. It's a valuable resource. Please don't waste it. I don't mean to be rude. But, you will help us all, yourself included, if you think carefully when asking a question. - Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From punkbohemian at yahoo.com Sun Jul 19 22:34:09 2009 From: punkbohemian at yahoo.com (Michael) Date: Sun, 19 Jul 2009 13:34:09 -0700 (PDT) Subject: [Tutor] hitting a wall (not a collision detection question :P) Message-ID: <384462.43602.qm@web57508.mail.re1.yahoo.com> I have virtually no background in programming. I'm currently teaching myself python using the following books: Beginning Python - From Novice to Professional by Magnus Lie Hetland Beginning Python by Peter Norton et. al. Making Use of Python by Rashi Gupta Learning Python? by Mark Lutz as well as a variety of tutorials I picked up off the web. I'm using v.2.5.2, and I'm trying to upgrade to 2.6.2, but I'm running Linux/Ubuntu so the upgrade is giving me problems. The main reason I'm not using 3.1 is because all my books talk about 2.x. Ultimately, my goal is to delve into pygame and make some games and maybe some multimedia applications. I'd like my first project to be an old-school style RPG (e.g. Final Fantasy), as something with such simple graphics and interface would be a good benchmark of where I want to go from there. I've been progressing steadily, until now. At this point, I have a pretty solid understanding of strings, integers, tuples, lists, dictionaries, etc. and everything up to functions vs. methods and the basics of classes and OOP. This is where I'm hitting a wall. It's at this point the all the books go off in different directions and I'm not sure a) what I'm learning, b) why I'm learning it, and c) how this is going to help me get to my goals. I'm not really even understanding much of what these books are talking about at this point anyway. It's like a few chapters after "Classes and OOP" were torn out of all of them. So, I'm just wondering what I should be doing at this point. Sorry for the vague question, but I'm pretty lost right now and this is about as specific as I can be. Thanks in advance for any help. Michae -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sun Jul 19 22:39:30 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sun, 19 Jul 2009 13:39:30 -0700 Subject: [Tutor] python interpreter vs bat file Message-ID: Hi Dave Sorry, I wasn't being obtuse. Here is more info: 1. Run Python Programs with Batch file - OS (correction): Windows 64-bit Vista SP2 - Python 2.5.4 64 bit (AMD64) - The Python programs run from a Windows batch file (test.bat) in a CMD window initiated from Windows Explorer. All programs except one execute successfully which stops with a memory error but the batch file continues to execute the other Python programs (as it should). 2. Run Python Programs with Python Interpreter - Start Idle, File/Open .py program, Run/Run Module - When the program with the memory error in 1. is run independently with Idle it works. Bob Gailer suggested running the Python programs individually in CMD one after the other. This is sensible but my test programs run for days and the full suite of programs take longer. The programs are memory intensive (the 64-bit machine has 8gb ram). Hence, it is not easy to test this scenario right now. It seems to me as if Windows is not freeing up memory between Python invocations in the batch file but can't be sure. I said earlier that this has happened before but the fix, as now, is to run the program individually with Idle. Hth ... Dinesh -------------------------------------------------------------------------------- Message: 5 Date: Sun, 19 Jul 2009 11:56:15 -0700 From: Dave Kuhlman To: tutor at python.org Subject: Re: [Tutor] python interpreter vs bat file Message-ID: <20090719185615.GA5356 at cutter.rexx.com> Content-Type: text/plain; charset=us-ascii On Sun, Jul 19, 2009 at 05:40:41AM -0700, Dinesh B Vadhia wrote: > > 1. Run Python Programs with Batch file > > Python programs run from a Windows XP batch file (test.bat) in a CMD > window initiated from Windows Explorer. All programs except one > execute successfully which stops with a memory error but batch file > continues to execute other Python programs (as it should). > > > > 2. Run Python Programs with Python Interpreter > > Fire up Python Interpreter, open .py program, Run. > Dinesh - Please tell us how you did this. Did you type "python" at a command prompt and then see the ">>>" prompt? If so how did you "open .py program, Run"? Or, did you start Idle (or some other IDE) then click File-->Open, then run with the Run-->RunModule menu item? You have been asked several times for more information. You really need to read: http://catb.org/~esr/faqs/smart-questions.html There are people on this list who are very generous with their time. It's a valuable resource. Please don't waste it. I don't mean to be rude. But, you will help us all, yourself included, if you think carefully when asking a question. - Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Sun Jul 19 22:56:32 2009 From: david at pythontoo.com (David) Date: Sun, 19 Jul 2009 16:56:32 -0400 Subject: [Tutor] hitting a wall (not a collision detection question :P) In-Reply-To: <384462.43602.qm@web57508.mail.re1.yahoo.com> References: <384462.43602.qm@web57508.mail.re1.yahoo.com> Message-ID: <4A638880.1060601@pythontoo.com> Michael wrote: > I have virtually no background in programming.. I'm currently teaching > myself python using the following books: > > Beginning Python - From Novice to Professional by Magnus Lie Hetland > Beginning Python by Peter Norton et. al. > Making Use of Python by Rashi Gupta > Learning Python by Mark Lutz > > as well as a variety of tutorials I picked up off the web. I'm using > v.2.5.2, and I'm trying to upgrade to 2.6.2, but I'm running > Linux/Ubuntu so the upgrade is giving me problems. The main reason I'm > not using 3.1 is because all my books talk about 2.x. > > Ultimately, my goal is to delve into pygame and make some games and > maybe some multimedia applications. I'd like my first project to be an > old-school style RPG (e.g. Final Fantasy), as something with such simple > graphics and interface would be a good benchmark of where I want to go > from there. > > I've been progressing steadily, until now. At this point, I have a > pretty solid understanding of strings, integers, tuples, lists, > dictionaries, etc. and everything up to functions vs. methods and the > basics of classes and OOP. This is where I'm hitting a wall. It's at > this point the all the books go off in different directions and I'm not > sure a) what I'm learning, b) why I'm learning it, and c) how this is > going to help me get to my goals. I'm not really even understanding much > of what these books are talking about at this point anyway. It's like a > few chapters after "Classes and OOP" were torn out of all of them. > > So, I'm just wondering what I should be doing at this point. Sorry for > the vague question, but I'm pretty lost right now and this is about as > specific as I can be. Thanks in advance for any help. > > Michae > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I am new to Python and never programed before. What has helped me is to think of something you want to automate, as an example I visit a few different sites each day to view new bugs reported. I made a program that emails me the differences from what I have gathered before. I take a piece of paper and write down the steps that I think this will take then start doing small pieces at a time and check each one to make sure it works, plus this gives me encouragement to continue. -david -- Powered by Gentoo GNU/Linux http://linuxcrazy.com From rabidpoobear at gmail.com Sun Jul 19 23:57:49 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 19 Jul 2009 16:57:49 -0500 Subject: [Tutor] hitting a wall (not a collision detection question :P) In-Reply-To: <384462.43602.qm@web57508.mail.re1.yahoo.com> References: <384462.43602.qm@web57508.mail.re1.yahoo.com> Message-ID: > Ultimately, my goal is to delve into pygame and make some games and maybe > some multimedia applications. I'd like my first project to be an old-school > style RPG (e.g. Final Fantasy), as something with such simple graphics and > interface would be a good benchmark of where I want to go from there I can recommend the book "Game Development with Python and Pygame" by Will McGugan. This may help you when you are working on the game, but you can also just use online resources if you'd like (that's what I did initially.) > > I've been progressing steadily, until now. At this point, I have a pretty > solid understanding of strings, integers, tuples, lists, dictionaries, etc. > and everything up to functions vs. methods and the basics of classes and > OOP. This is where I'm hitting a wall. It's at this point the all the books > go off in different directions and I'm not sure a) what I'm learning, b) why > I'm learning it, and c) how this is going to help me get to my goals. You're at the point now that you should start working on your own simple programs that do things you need to. The best way to learn is to come up with a problem and figure out how to solve it yourself. If you need any hints, we'd be happy to help. See, the thing about programming is that there are a lot of really advanced topics that don't necessarily help you or aren't necessarily useful for every problem. For example, Regular Expressions are very powerful and for certain applications, they're nearly indispensible. However, whenever I write a game in Pygame, I don't hardly ever use them. So writing an application you want to write will help you see the bigger picture, and how all the things you've learned so far can be utilized to achieve whatever goal you desire. Honestly if you already understand OOP and classes, you're a lot further along than a lot of people are. When I started writing Python I didn't understand OOP at all. In fact I went through quite a few programs without using it whatsoever. Later on, when I learned what OOP was, I went back and modified my programs and in some cases it simplified them quite a bit. But in some cases it wasn't even necessary and was maybe even more confusing to use OOP. I'm a Computer Science grad student right now, but everything that gets covered in class I've already learned through my own experimentation with Python, to a pretty large extent. You can learn a great deal independently, if you really want to. Free online resources and books go into incredibly advanced detail that you aren't expected to grasp immediately. It's a progressive thing. Try writing some simple apps and if you come up with a problem that you can't solve with the tools you have already learned how to use (or can't solve easily - most things in Python should be easy), let us know and we'll tell you which next section of the book you should read. HTH, -Luke From alan.gauld at btinternet.com Mon Jul 20 00:22:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jul 2009 23:22:47 +0100 Subject: [Tutor] python interpreter vs bat file References: Message-ID: "Dinesh B Vadhia" wrote > Bob Gailer suggested running the Python programs individually > in CMD one after the other. This is sensible but my test programs > run for days and the full suite of programs take longer. OK, But it can't take longer than in IDLE? Or even in the bat file. So you can start the program running and then iconify it. The reason this is important is that IDLE catches some errors that the normal python interpreter does not So IDLE may be masking a real problem in your code. However... > The programs are memory intensive (the 64-bit machine > has 8gb ram). Hence, it is not easy to test this scenario > right now. Have you chedked in Task Manager how much RAM the python programs use up - they should be visible in the process tab. If it is a lot then maybe we can rewrite the code to use less memory (Or maybe leak less memory). > It seems to me as if Windows is not freeing up memory > between Python invocations in the batch file but can't be > sure. Windows should free up the memory, but it might depend on how you run the programs. In your earlier post you said the bat file contained lines like python foo.py python bar.py You could try usng the start command instead, as in: start foo.py You might want to explore the /I, /B and /WAIT options start gives you a lot more control over the execution environment. Notice you don;t need the 'python' because start uses the file association. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jul 20 00:36:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jul 2009 23:36:03 +0100 Subject: [Tutor] hitting a wall (not a collision detection question :P) References: <384462.43602.qm@web57508.mail.re1.yahoo.com> Message-ID: "Michael" wrote > ...everything up to functions vs. methods and the basics of classes > and OOP. This is where I'm hitting a wall. It's at this point the all the > books go off in different directions OK, First thing is don;t worry about it, you are far from alone. Many, Many programmers (even long term pros) find the transition from functions to objects really hard to adjust to. Not surprising, since it doers require a new way of thinking about program structure. Eventually the OOP way will become second nature, in fact you might even find it hard to think about ordinary functions after a while! But it can take a while. > and I'm not sure a) what I'm learning, b) why I'm learning it, > and c) how this is going to help me get to my goals. It might be good to throw us some specific questions and we can try to answer them. General questions tend to produce vague answers! You can try my tutorial on OOP to see if that helps. Follow it up with the case study to see OOP in action. > I'm not really even understanding much of what these books > are talking about at this point anyway. Again, anything you are unsure about tell us and we can try to explain. That isd what this klist is really good at because there are many different perspectives who have all gone through the same learning curve. Someone likely has the same way if thinking about it as you do! > It's like a few chapters after "Classes and OOP" were torn out of all of > them. :-) > So, I'm just wondering what I should be doing at this point. Start writing code. Don't worry about OOP too much but look out for when you use objects in normal python code - like strings and files for example - and see how the library writers did things. Look for things in your code that sound like they might be objects, try writing a class to bring together the data and the functions that work on that data. The more you use objects and classes the more familiar they become and what works and doesn't work becomes obvious. Until you use them it all remains somewhat academic. > this is about as specific as I can be. Go back to those tutorials and find the bits you aren't sure about and just ask - what does this mean? How should I use this? And why? Is this a sensible way to program this? etc etc... We will try to help. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jul 20 00:39:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 19 Jul 2009 23:39:10 +0100 Subject: [Tutor] UnicodeEncodeError References: <24554280.post@talk.nabble.com> Message-ID: "Mark Tolonen" wrote > ... I see you are using Python 3.1. ... > > You can also use a shell that supports the full Unicode character set > such as Idle or PythonWin instead of the console. As a matter of interest - and somewhat off topic - does anyone know if there is a Python 3 (3.0 or 3.1) version of Pythonwin out yet? Too lazy to look :-) Alan G From cosmicsand27 at yahoo.com Mon Jul 20 01:12:50 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Sun, 19 Jul 2009 16:12:50 -0700 (PDT) Subject: [Tutor] Using insert method on a list matrix Message-ID: <980911.94039.qm@web43411.mail.sp1.yahoo.com> I would like to know how I could use the insert method in a List matrix eg. for the matrix below M=[[1,2,3], [3,2,1], [4,3,2]] if wanted to insert the string 'pod' in list [0] before [1] in list [0] in M using the built in method insert How would I go about doing this? I've tried may List Comprehension possibilities but none of then worked. Below are some of the things I tried. >>> M=[[1,2,3], [3,2,1], [4,3,2]] >>> M.insert([1][1], 'pod') Traceback (most recent call last): File "", line 1, in M.insert([1][1], 'pod') IndexError: list index out of range >>> [row[0] for row in M.insert(1, 'pod')] Traceback (most recent call last): File "", line 1, in [row[0] for row in M.insert(1, 'pod')] TypeError: 'NoneType' object is not iterable >>> M.insert(1,'pod') >>> M [[1, 2, 3], 'pod', 'pod', [3, 2, 1], [4, 3, 2]] >>> M.insert[0](1,'pod') Traceback (most recent call last): File "", line 1, in M.insert[0](1,'pod') TypeError: 'builtin_function_or_method' object is unsubscriptable Any help is greatly appreciated! Thanks! -Raj -------------- next part -------------- An HTML attachment was scrubbed... URL: From ksterling at mindspring.com Mon Jul 20 02:16:11 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Sun, 19 Jul 2009 20:16:11 -0400 (EDT) Subject: [Tutor] Using insert method on a list matrix Message-ID: <25022013.1248048971478.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Mon Jul 20 02:53:30 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sun, 19 Jul 2009 17:53:30 -0700 Subject: [Tutor] UnicodeEncodeError References: <24554280.post@talk.nabble.com> Message-ID: "Alan Gauld" wrote in message news:h407ah$lcg$1 at ger.gmane.org... > > "Mark Tolonen" wrote >> ... I see you are using Python 3.1. ... >> >> You can also use a shell that supports the full Unicode character set >> such as Idle or PythonWin instead of the console. > > As a matter of interest - and somewhat off topic - does anyone > know if there is a Python 3 (3.0 or 3.1) version of Pythonwin out yet? > > Too lazy to look :-) Yes. PythonWin 214 is the latest version and supports 3.0 and 3.1. -Mark From pine508 at hotmail.com Mon Jul 20 03:01:48 2009 From: pine508 at hotmail.com (Che M) Date: Sun, 19 Jul 2009 21:01:48 -0400 Subject: [Tutor] hitting a wall (not a collision detection question :P) In-Reply-To: <384462.43602.qm@web57508.mail.re1.yahoo.com> References: <384462.43602.qm@web57508.mail.re1.yahoo.com> Message-ID: So, I'm just wondering what I should be doing at this point. Sorry for the vague question, but I'm pretty lost right now and this is about as specific as I can be. Thanks in advance for any help. Michae I started from scratch a 3 years ago and my advice would be: - Accept confusion. Marinate in it. Don't fight it. Clarity will come, with time. It is easy to get overwhelmed early. Take a break, get some hours of slow wave sleep, it will be clearer next time you engage it, probably. - "I'm in a hurry, so dress me slowly". Clarity and rushing don't mix well ever, but it is particularly bad with computer code. - Make your function names meaningful: long enough to tell what they do. Make functions verbs, like GetDatabaseInformation(), and not just Database() or worse, D(). (This is my opinion, at least). And comment your own practice code with explanations if that is helpful to you. - Keep a notebook/file of what you have learned and where to find it again online if you need to refresh. - Use this list and other lists (if there is a pyGame list, e.g.). Great people in the Python community. Ask good questions, too: http://catb.org/esr/faqs/smart-questions.html - Once you have the basics a bit beyond "Hello, World!", don't just try to learn everything--learn *per task*. So find what task you want, and try something simple to begin, establish that, and then move on. - Tutorials I've enjoyed and learned from: Alan Gauld's Learning to Program http://www.freenetpages.co.uk/hp/alan.gauld/ Effbot's Guide to the Standard Python Library http://effbot.org/zone/librarybook-index.htm Various Beginner video screencasts on ShowMeDo, incl. lots on beginning Python. www.showMeDo.com Good luck, Che _________________________________________________________________ Bing? brings you maps, menus, and reviews organized in one place. Try it now. http://www.bing.com/search?q=restaurants&form=MLOGEN&publ=WLHMTAG&crea=TXT_MLOGEN_Local_Local_Restaurants_1x1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From ctcast at gmail.com Mon Jul 20 04:56:30 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sun, 19 Jul 2009 21:56:30 -0500 Subject: [Tutor] reading complex data types from text file In-Reply-To: <50e459210907182215i3a8fda9eo38e3312f3e17eaae@mail.gmail.com> References: <50e459210907151155w30a924faneda1d2ac8ffc33db@mail.gmail.com> <24a9d1f30907160626l4d9ec239i996e22e7a42231b1@mail.gmail.com> <50e459210907161120i5176e1do744a399cb26eb6d@mail.gmail.com> <4A5F96DE.90205@gmail.com> <50e459210907162259s35568073h858081b9cf8df5dd@mail.gmail.com> <4A60B95A.9090205@gmail.com> <50e459210907182215i3a8fda9eo38e3312f3e17eaae@mail.gmail.com> Message-ID: <50e459210907191956v43e446ecs8cb0b662ea37467b@mail.gmail.com> okay so I figured my program out. I am posting the final version so if someone else is having problems with something like this it may benefit the community. (comments are included to help those who might not understand the code) ------------------------------------------------------------------------------------------------------------ ''' Program reads names of bowlers and their corresponding scores, then writes their names to a new text file with a description of either below average, average, above average or a perfect score ''' scores = {} # empty dictionary total = 0 #initalize total to 0 value for line in open("bowlingscores.txt", "r"): # iterate through txt file with names and scores if line.strip().isdigit(): score = int(line) # convert score into int type scores[name] = score # add scores to dictionary total += score # add score to running total else: name = line.strip() # if the line isn't a digit name will be the key in the dictionary averageScore = total / len(scores) # get average of all scores fileOut = open("bowlingaverages.txt", "w") # create a file to write names and scores to fileOut.write("Bowling Report\n" + ("-" * 50) + "\n") # header for name, score in scores.items(): #iterate through each score in the dictionary to get an score value for each player if score == 300: score = "\tPerfect score!\n" scores[name] = score elif score < averageScore: score = "\tBelow average\n" scores[name] = score elif score > averageScore: score = "\tAbove average!\n" scores[name] = score else: score = "\tAverage!\n" scores[name] = score for items in scores.items(): #iterate through the items in the dictionary and format them to the output file fileOut.write("%s%s\n" % items) --------------------------------------------------------------------------------------- your output for this code should look like this inside the text file: *Bowling Report -------------------------------------------------- sue Below average bill Above average! nat Below average tom Perfect score!* Thanks to everyone who helped me with this. On Sun, Jul 19, 2009 at 12:15 AM, Chris Castillo wrote: > so could I also replace the score of each bowler (key value) in the > dictionary with a new key such as "below average" or "above average" > according to each if-elif-else structure and then write to a text file in > the following format? > > Jim Above Average > Sue Below Average > Bob Perfect score > > > On Fri, Jul 17, 2009 at 12:48 PM, bob gailer wrote: > >> Chris Castillo wrote: >> >>> how would i go about adding the names to a dictionary as a key and the >>> scores as a value in this code? >>> >>> >>> # refactored for better use of Python, correct logic, and flow >> >> scores = {} # empty dictionary >> total = 0 >> for line in open("bowlingscores.txt", "r"): >> if line.strip().isdigit(): >> score = int(line) >> scores[name] = score >> total += score >> else: >> name = line.strip() >> averageScore = total / len(scores) >> fileOut = open("bowlingaverages.txt", "w") >> fileOut.write("Bowling Report\n" + ("-" * 50) + "\n") >> for name, score in scores.items(): >> if score == 300: >> score = "\tPerfect score!" >> elif score < averageScore: >> score = "\tBelow average" >> elif score > averageScore: >> score = "\tAbove average!" >> else: >> score = "\tAverage!" >> print name, score >> >> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From yam.matt at gmail.com Mon Jul 20 09:04:32 2009 From: yam.matt at gmail.com (Mazhar Hussain) Date: Mon, 20 Jul 2009 13:04:32 +0600 Subject: [Tutor] Pygame Message-ID: Hello All! My name is Mazhar Hussain, and I am new to python, in fact, I am new to programming as a whole. I dont know if its the right list to talk about this. I am really interested in 2d games, especially 2d games. I am also interested in making games. I searched for a lot of programming languages but I didnt like anyone of them, either they were too hard to learn or not suitable to make games. But then I found Python. I had heard that it was very easy to learn and great for making games, it also had a binding for SDL called pygame. But the main games I want to create are: a pokemon clone, a megaman battle network clone and a world of goo like game. I just want to know if I can make these type of games with pygame(before learning python). If it can then I'll start learning python right away but if it cant then I think I may better find another language. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jul 20 09:33:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Jul 2009 08:33:29 +0100 Subject: [Tutor] Using insert method on a list matrix References: <980911.94039.qm@web43411.mail.sp1.yahoo.com> Message-ID: "Raj Medhekar" wrote >I would like to know how I could use the insert method in a > List matrix OK, A list "matrix" is just a list containing other lists. TThere is nothing special about it, it is just an ordinary list. You could do it in two steps: firstList = M[0] firstList.insert(0,'pod') But it is just as easy to do it directly... > eg. for the matrix below > > M=[[1,2,3], [3,2,1], [4,3,2]] > > if wanted to insert the string 'pod' in list [0] before [1] in list [0] > in M You said it right the first time. You want to insert 'pod' into list[0], ie M[0] So you must call the insert method of that object and specify the index of the insertion there: 0 in your case. M[0].insert(...) >>>> M=[[1,2,3], [3,2,1], [4,3,2]] >>>> M.insert([1][1], 'pod') This makes no sense since insert() takes a single index because lists (always!) have a single dimension. In M's case it is a list of 3 elements, which elements just happen to be lists too. Also insert does not expect the index to be in brackets. >>>> [row[0] for row in M.insert(1, 'pod')] insert() returns None so the loop in this comprehension breaks, But you do get the insert syntax right this time. M should now look like M=[[1,2,3], 'pod', [3,2,1], [4,3,2]] >>>> M.insert(1,'pod') >>>> M > [[1, 2, 3], 'pod', 'pod', [3, 2, 1], [4, 3, 2]] You got it right here too but you are inserting it into M not into the first element of M. >>>> M.insert[0](1,'pod') So, one more time, it should be M[0].insert(0,'pod') HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jul 20 09:42:38 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Jul 2009 08:42:38 +0100 Subject: [Tutor] Pygame References: Message-ID: "Mazhar Hussain" wrote > Hello All! My name is Mazhar Hussain, and I am new to python, Welcome to the tutor list > new to programming as a whole. I dont know if its the right list to talk > about this. Yes, we are here to help people learning Python, many of whom are also learning programming. There are a set of tutorials on the Python web site specifically designed for new programmers, here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers You will notice one of these is specifically targetted at games writers. > I am really interested in 2d games, especially 2d games. I am also > interested in making games. I guess you might like games? > called pygame. But the main games I want to create are: a pokemon clone, > a > megaman battle network clone and a world of goo like game. I can't really help there, I've only heard of pokemon and never even seen it! Buty Pygame can produce a lot of games and even standard python can deliver simple interactive games. Unless you want the very fastest shoot 'em up type games Pygame should suffice. And if you do want the fastest shoot 'em up you have an awful lot of learning to do first!! :-) > If it can then I'll start learning python right away but if it cant then > I > think I may better find another language. If you start learning python you will probably learn the fundamentals of programming much faster than if you use abnother language. Even if you then move to something else more "hard core" - like C++ - you will find the lessons you learned in Python still apply. Once you know one programming language learning a new one is very much easier. Finally, stick to Python v2 just now, Python v3 is not best suited to beginners yet. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From dineshbvadhia at hotmail.com Mon Jul 20 11:08:26 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 20 Jul 2009 02:08:26 -0700 Subject: [Tutor] python interpreter vs bat file Message-ID: Running time in CMD and IDLE - Program running time is about the same in both CMD and IDLE - The programs take a long time to run NOT because of runaway processes that are using up memory - The programs are being optimized with each successive generation to reduce resources and time but the limitations boil down to Python for-loops (within functions) and sorts (probably the subject of another note to Tutor). IDLE masking program errors - Could be but ... - The programs work under IDLE and return the correct results - At this point I decided to run the programs from a batch file Batch file method - Except for one program, all other programs work using the batch file method. - The program with the error is run under IDLE and combined at the end with the output of the batch file programs and correct results are returned. Program memory use - The program with the memory error uses a lot of memory but the data structures should fit into available memory as it does when run with IDLE Use of DOS Start command - I'll try out the /I, /B and /WAIT commands in the next run and will let you know what happens. Thanks. Dinesh -------------------------------------------------------------------------------- Message: 1 Date: Sun, 19 Jul 2009 23:22:47 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] python interpreter vs bat file Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Dinesh B Vadhia" wrote > Bob Gailer suggested running the Python programs individually > in CMD one after the other. This is sensible but my test programs > run for days and the full suite of programs take longer. OK, But it can't take longer than in IDLE? Or even in the bat file. So you can start the program running and then iconify it. The reason this is important is that IDLE catches some errors that the normal python interpreter does not So IDLE may be masking a real problem in your code. However... > The programs are memory intensive (the 64-bit machine > has 8gb ram). Hence, it is not easy to test this scenario > right now. Have you chedked in Task Manager how much RAM the python programs use up - they should be visible in the process tab. If it is a lot then maybe we can rewrite the code to use less memory (Or maybe leak less memory). > It seems to me as if Windows is not freeing up memory > between Python invocations in the batch file but can't be > sure. Windows should free up the memory, but it might depend on how you run the programs. In your earlier post you said the bat file contained lines like python foo.py python bar.py You could try usng the start command instead, as in: start foo.py You might want to explore the /I, /B and /WAIT options start gives you a lot more control over the execution environment. Notice you don;t need the 'python' because start uses the file association. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ Message: 2 Date: Sun, 19 Jul 2009 23:36:03 +0100 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] hitting a wall (not a collision detection question :P) Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Michael" wrote > ...everything up to functions vs. methods and the basics of classes > and OOP. This is where I'm hitting a wall. It's at this point the all the > books go off in different directions OK, First thing is don;t worry about it, you are far from alone. Many, Many programmers (even long term pros) find the transition from functions to objects really hard to adjust to. Not surprising, since it doers require a new way of thinking about program structure. Eventually the OOP way will become second nature, in fact you might even find it hard to think about ordinary functions after a while! But it can take a while. > and I'm not sure a) what I'm learning, b) why I'm learning it, > and c) how this is going to help me get to my goals. It might be good to throw us some specific questions and we can try to answer them. General questions tend to produce vague answers! You can try my tutorial on OOP to see if that helps. Follow it up with the case study to see OOP in action. > I'm not really even understanding much of what these books > are talking about at this point anyway. Again, anything you are unsure about tell us and we can try to explain. That isd what this klist is really good at because there are many different perspectives who have all gone through the same learning curve. Someone likely has the same way if thinking about it as you do! > It's like a few chapters after "Classes and OOP" were torn out of all of > them. :-) > So, I'm just wondering what I should be doing at this point. Start writing code. Don't worry about OOP too much but look out for when you use objects in normal python code - like strings and files for example - and see how the library writers did things. Look for things in your code that sound like they might be objects, try writing a class to bring together the data and the functions that work on that data. The more you use objects and classes the more familiar they become and what works and doesn't work becomes obvious. Until you use them it all remains somewhat academic. > this is about as specific as I can be. Go back to those tutorials and find the bits you aren't sure about and just ask - what does this mean? How should I use this? And why? Is this a sensible way to program this? etc etc... We will try to help. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bhaaluu at gmail.com Mon Jul 20 11:39:22 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 20 Jul 2009 05:39:22 -0400 Subject: [Tutor] Pygame In-Reply-To: References: Message-ID: Python Programming for the Absolute Beginner Second Edition. Michael Dawson. Boston, MA: Thomson Course Technology, 2006. ISBN-13: 978-1-59863-112-8 ISBN-10: 1-59863-112-8 No experience required to learn Python programming. This book will teach you the basics of Python programming through simple game creation. You'll learn to: Build, slice, and index strings. Work with functions, Read from and write to text files, Create and manipulate sprites, Tackle object-oriented programming, Create a GUI, and work sound, music, and create animation. The book comes with a CD that has Python 2.3.5 PyGame 1.6 LiveWires 2.0 <--customized version for this book Source code and projects from the book. If you can make it through Dawson's book, you'll be prepared to tackle PyGame tutorials such as: Game Programming by Andy Harris (ISBN-13: 978-0-470-06822-9) http://www.cs.iupui.edu/~aharris/pygame/ or Beginning Game Development with Python and Pygame: >From Novice to Professional by Will McGugan (ISBN-13: 978-1590598726) The PyGame site also has beginnner tutorials. http://www.pygame.org/docs/ Look for Michael Dawson's book, and start programming text-based games in Python from the very first chapter! By the end of the book, you'll be programming 2D arcade-style games. (447 pages) Hopefully helpful. -- b h a a l u u at g m a i l dot c o m Gnu/Linux IS user-friendly. It's NOT ignorant-friendly or idiot-friendly. On Mon, Jul 20, 2009 at 3:04 AM, Mazhar Hussain wrote: > ?Hello All! My name is Mazhar Hussain, and I am new to python, in fact, I am > new to programming as a whole. I dont know if its the right list to talk > about this. > ?I am really interested in 2d games, especially 2d games. I am also > interested in making games. I searched for a lot of programming languages > but I didnt like anyone of them, either they were too hard to learn or not > suitable to make games. But then I found Python. I had heard that it was > very easy to learn and great for making games, it also had a binding for SDL > called pygame. But the main games I want to create are: a pokemon clone, a > megaman battle network clone and a world of goo like game. I just want to > know if I can make these type of games with pygame(before learning python). > If it can then I'll start learning python right away but if it cant then I > think I may better find another language. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From ldl08 at gmx.net Mon Jul 20 12:00:44 2009 From: ldl08 at gmx.net (David) Date: Mon, 20 Jul 2009 18:00:44 +0800 Subject: [Tutor] Pygame In-Reply-To: References: Message-ID: <4A64404C.7090004@gmx.net> Mazhar, bhaaluu wrote: > Python Programming for the Absolute Beginner Second Edition. > Michael Dawson. > Boston, MA: Thomson Course Technology, 2006. > ISBN-13: 978-1-59863-112-8 > ISBN-10: 1-59863-112-8 This is, in my judgment, a good suggestion, provided you are working on a Windows system. Otherwise some of the tools Dawson introduces will not work. So, start here, and move on to McGugan's book thereafter. David From bhaaluu at gmail.com Mon Jul 20 13:16:24 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 20 Jul 2009 07:16:24 -0400 Subject: [Tutor] Pygame In-Reply-To: <4A64404C.7090004@gmx.net> References: <4A64404C.7090004@gmx.net> Message-ID: On Mon, Jul 20, 2009 at 6:00 AM, David wrote: > Mazhar, > > bhaaluu wrote: >> Python Programming for the Absolute Beginner Second Edition. >> Michael Dawson. >> Boston, MA: Thomson Course Technology, 2006. >> ISBN-13: 978-1-59863-112-8 >> ISBN-10: 1-59863-112-8 > This is, in my judgment, a good suggestion, provided you are working on > a Windows system. Otherwise some of the tools Dawson introduces will not > work. > So, start here, and move on to McGugan's book thereafter. > > David > I was able to work through Dawson's entire book on a Gnu/Linux system, using X (Window system), Konsole, and the vim plain text editor. Dawson uses a customized version of LiveWires towards the end of the book. You must install the customized version for Dawson's examples to work with Gnu/Linux. I've worked through some of the source code for McGugan's book. It seems to lean more towards 3D programming than 2D programming. The Andy Harris book is geared to 2D programming in PyGame, and is a good beginner introduction to PyGame. You should already know some Python before reading Harris' book because he doesn't really give a Python programming tutorial. So, Dawson --> Harris --> McGugan is a good syllabus for Game Programming in Python/PyGame. -- b h a a l u u at g m a i l dot c o m Gnu/Linux IS user-friendly. It's NOT ignorant-friendly or idiot-friendly. From srilyk at gmail.com Mon Jul 20 14:59:30 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 20 Jul 2009 07:59:30 -0500 Subject: [Tutor] Pygame In-Reply-To: References: Message-ID: <333efb450907200559v4ea35c1aq15a9c7c4831aee53@mail.gmail.com> On Mon, Jul 20, 2009 at 2:04 AM, Mazhar Hussain wrote: > Hello All! My name is Mazhar Hussain, and I am new to python, in fact, I > am new to programming as a whole. I dont know if its the right list to talk > about this. > I am really interested in 2d games, especially 2d games. I am also > interested in making games. I searched for a lot of programming languages > but I didnt like anyone of them, either they were too hard to learn or not > suitable to make games. But then I found Python. I had heard that it was > very easy to learn and great for making games, it also had a binding for SDL > called pygame. But the main games I want to create are: a pokemon clone, a > megaman battle network clone and a world of goo like game. I just want to > know if I can make these type of games with pygame(before learning python). > If it can then I'll start learning python right away but if it cant then I > think I may better find another language. > Take a look at these games: http://www.pyweek.org/all_games/ I believe this one: http://www.pyweek.org/e/gamebyalex2/ was written with the pyglet library. I'd say it'd be a good challenge to write the pokemon clone. The "battles" part would probably not take you too long. If you devote around an hour a day to learning and an hour working on your project, I'd guess you could be done with the battle part in around six months, if you're working on the project solo. Of course having the tutor list to help you when you run into problems will help you reach that mark ;) I'd recommend writing some sort of text-menu based version first, and then extending that into a graphical version. If you get your code properly broken up into functions and classes (which you'll learn more about later) it should be fairly simple to wrap the graphics around it. Anyway, others have also offered great advice, and Alan Gauld's tutorial is one of the many high-quality online tutorials for learning to program, specifically in python. Another great thing about the pyweek games is when you download them you can examine the source code so you can see exactly how many lines of code went into writing the games. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From gys1101 at hotmail.com Mon Jul 20 11:15:08 2009 From: gys1101 at hotmail.com (GAONEO) Date: Mon, 20 Jul 2009 17:15:08 +0800 Subject: [Tutor] I need help to the Python blackjack code Message-ID: Hi This is the first code that I have programed. I think there is something wrong with it. It is not a loop and computer seems wont bust. In the game, ace will be fixed as low (value=1). And can you write documentation comments for the first 39lines. kind regards Neo Gao _________________________________________________________________ ????? Windows Live ????????????? http://www.microsoft.com/china/windows/windowslive/products/photo-gallery-edit.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: balckjack.py URL: From kent37 at tds.net Mon Jul 20 15:12:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Jul 2009 09:12:48 -0400 Subject: [Tutor] hitting a wall (not a collision detection question :P) In-Reply-To: <384462.43602.qm@web57508.mail.re1.yahoo.com> References: <384462.43602.qm@web57508.mail.re1.yahoo.com> Message-ID: <1c2a2c590907200612r4fc6b55ah88f9b13142ec73f4@mail.gmail.com> On Sun, Jul 19, 2009 at 4:34 PM, Michael wrote: > I've been progressing steadily, until now. At this point, I have a pretty > solid understanding of strings, integers, tuples, lists, dictionaries, etc. > and everything up to functions vs. methods and the basics of classes and > OOP. This is where I'm hitting a wall. It's at this point the all the books > go off in different directions and I'm not sure a) what I'm learning, b) why > I'm learning it, and c) how this is going to help me get to my goals. I'm > not really even understanding much of what these books are talking about at > this point anyway. It's like a few chapters after "Classes and OOP" were > torn out of all of them. > > So, I'm just wondering what I should be doing at this point. Maybe you are ready to try a simple game? You could try the pygame tutorial, see if you get an idea for a simple game you can work on. Kent From srilyk at gmail.com Mon Jul 20 15:24:25 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 20 Jul 2009 08:24:25 -0500 Subject: [Tutor] I need help to the Python blackjack code In-Reply-To: References: Message-ID: <333efb450907200624t5e9f1e8dl6f96ca94ea291008@mail.gmail.com> 2009/7/20 GAONEO > Hi > > This is the first code that I have programed. I think there is > something wrong with it. It is not a loop and computer seems wont bust. In > the game, > > ace will be fixed as low (value=1). And can you write documentation > comments for the first 39lines. > > your score is 87 you bust you lose and computer wins twist (t) or stick (s)?s you choose stick It is computers turn computer stick computer score is 63 you win and computer loses twist (t) or stick (s)? Evidently you don't stop on either your bust or the computer bust. Maybe you should try writing out in more or less plain language how a game of blackjack works. What happens first? What happens next? In the casino if the deal has a hard OR soft 17, it always stands (or sticks in your program). See if you can make the computer stop once it reaches 17. Also see if you can make the program stop once the user makes it to 21. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From yam.matt at gmail.com Mon Jul 20 16:57:11 2009 From: yam.matt at gmail.com (Mazhar Hussain) Date: Mon, 20 Jul 2009 20:57:11 +0600 Subject: [Tutor] Thanks! Message-ID: Thanks for all your help guys! I will try to buy all those books so that if I find something in one book not understandable, I will look for it in another book. Again Thanks. This list really is Helpful! -------------- next part -------------- An HTML attachment was scrubbed... URL: From cosmicsand27 at yahoo.com Mon Jul 20 17:39:10 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Mon, 20 Jul 2009 08:39:10 -0700 (PDT) Subject: [Tutor] Using insert method on a list matrix In-Reply-To: <25022013.1248048971478.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> References: <25022013.1248048971478.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> Message-ID: <662593.64459.qm@web43402.mail.sp1.yahoo.com> Thanks that works! But what if I wanted to modify 2 of the three lists in 2 different positions? Could you please let me know how I would go about doing that? Thanks! -Raj ________________________________ From: Ken Oliver To: Raj Medhekar ; Python Tutor Sent: Sunday, July 19, 2009 8:16:11 PM Subject: Re: [Tutor] Using insert method on a list matrix try M[0].insert(0, 'pod') -----Original Message----- > >From: Raj Medhekar > >Sent: Jul 19, 2009 7:12 PM > >To: Python Tutor > >Subject: [Tutor] Using insert method on a list matrix > > > > >I would like to know how I could use the insert method in a List matrix eg. for the matrix below > >M=[[1,2,3], [3,2,1], [4,3,2]] > >if wanted to insert the string 'pod' in list [0] before [1] in list [0] in M using the built in method insert How would I go about doing this? I've tried may List Comprehension possibilities but none of then worked. Below are some of the things I tried. > >>>> M=[[1,2,3], [3,2,1], [4,3,2]] >>>> M.insert([1][1], 'pod') > >Traceback (most recent call last): > File "", line 1, in > M.insert([1][1], 'pod') >IndexError: list index out of range >>>> [row[0] for row in M.insert(1, 'pod')] > >Traceback (most recent call last): > File > "", line 1, in > [row[0] for row in M.insert(1, 'pod')] >TypeError: 'NoneType' object is not iterable >>>> M.insert(1,'pod') >>>> M >[[1, 2, 3], 'pod', 'pod', [3, 2, 1], [4, 3, 2]] >>>> M.insert[0](1,'pod') > >Traceback (most recent call last): > File "", line 1, in > M.insert[0](1,'pod') >TypeError: 'builtin_function_or_method' object is unsubscriptable > > >Any help is greatly appreciated! Thanks! > >-Raj > > . -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Mon Jul 20 18:26:20 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 20 Jul 2009 12:26:20 -0400 Subject: [Tutor] advice on creating and working with a complex data structure Message-ID: Hi everyone, I'm working with a database of campaign finance filings, and I'm trying to create a data structure that captures the fact that: - there can be multiple races - races can have multiple candidates - candidates can have multiple campaign committees - campaign committees can file multiple reports I'm trying to pull these records from a database and output them to an HTML file in sorted order. Here's an example of the data I'll be pulling: records_from_db = ( # name, party, cmte_id, state, district, risk_rating, filing_type, filing_num ['Mike Brown','Rep','C0035820','FL','15','tossup','F3','8183'], ['Mike Brown','Rep','C0035820','FL','15','tossup','F3','8149'], ['Susan Miller','Dem','C0013802','FL','15','tossup','F3','2180'], ) I was leaning toward creating a nested data structure like this: races={'FL-15': {'status':'tossup', 'candidates': {'Susan Miller': {'party':'Dem', 'cmtes': {'C0013802': {'2180':'F3'}, }, # end cmtes }, #end Susan Miller 'Mike Brown': {'party':'Rep', 'cmtes': {'C0035820': {'8183':'F3', '2810':'F3'}, 'C0015823': {'3900':'F3X'}, }, #end cmtes }, #end Mike Brown }, #end Candidates }, #End FL-15 } #end races dict Once I've created the data object, I'd like to group the output by race, party, candidate, committee and filing, so that when I output in my template, it appears like this: FL-15: Dem Susan Miller C0035820 2180 Rep Mike Brown C0035820 8149 8183 I've been looking at Cookbook examples that rely on the setdefault method to add key:value pairs to a dictionary, but I wasn't sure how to implement that approach for a data structure with so many layers of nesting. Based on all of the above, I had a few questions: * Is the best approach to create some type of a Race class that can store all these varying data points for each race? * Should I be using some type of recursive function to handle all the levels of nesting? * Given the above data structure, what sorting approach is most appropriate? And of course, please let me know if there's a simpler approach I'm overlooking that would meet my requirements. As always, the advice is appreciated. Regards, Serdar From lukepadawan at gmail.com Mon Jul 20 18:35:31 2009 From: lukepadawan at gmail.com (Lucas P Melo) Date: Mon, 20 Jul 2009 13:35:31 -0300 Subject: [Tutor] advice on creating and working with a complex data structure In-Reply-To: References: Message-ID: <4A649CD3.4010801@gmail.com> Serdar Tumgoren wrote: > And of course, please let me know if there's a simpler approach I'm > overlooking that would meet my requirements. > > As always, the advice is appreciated. You could just create some classes with methods to handle the insertion and deletion of those data. You could also keep a 'dict' to get objects given a string (or int). I hope it helps. Regards, Lucas From lie.1296 at gmail.com Mon Jul 20 19:16:22 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 21 Jul 2009 03:16:22 +1000 Subject: [Tutor] Using insert method on a list matrix In-Reply-To: <662593.64459.qm@web43402.mail.sp1.yahoo.com> References: <25022013.1248048971478.JavaMail.root@elwamui-norfolk.atl.sa.earthlink.net> <662593.64459.qm@web43402.mail.sp1.yahoo.com> Message-ID: Raj Medhekar wrote: > Thanks that works! But what if I wanted to modify 2 of the three lists > in 2 different positions? Could you please let me know how I would go > about doing that? M[0].insert(2, 'foo') M[2].insert(1, 'bar') From alan.gauld at btinternet.com Mon Jul 20 19:48:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Jul 2009 18:48:14 +0100 Subject: [Tutor] advice on creating and working with a complex data structure References: Message-ID: "Serdar Tumgoren" wrote > I'm working with a database of campaign finance filings, and I'm > trying to create a data structure that captures the fact that: > - there can be multiple races > - races can have multiple candidates > - candidates can have multiple campaign committees > - campaign committees can file multiple reports Have you considered using classes? This looks like a fairly natural fit for race, candidate, committee and maybe report casses > I'm trying to pull these records from a database and output them to an > HTML file in sorted order. Each class could have a render method that retuirns an HTML fragment as a string... > Once I've created the data object, I'd like to group the output by > race, party, candidate, committee and filing, so that when I output in > my template, it appears like this: You could provide support for a sort method that would do the grouping for yopu... > I've been looking at Cookbook examples that rely on the setdefault > method to add key:value pairs to a dictionary, but I wasn't sure how > to implement that approach for a data structure with so many layers of > nesting. One level at a time! But with classes there would be less nesting and more relatinships > * Is the best approach to create some type of a Race class that can > store all these varying data points for each race? I think you want a lot more than a Race class, see above. > * Should I be using some type of recursive function to handle all the > levels of nesting? Probably not, a simple inter-bject relationship will make traversal much easier > And of course, please let me know if there's a simpler approach I'm > overlooking that would meet my requirements. I think creating more objects and getting each object to handle fetching the stuff from its next level down would be simpler HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zstumgoren at gmail.com Mon Jul 20 20:03:19 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Mon, 20 Jul 2009 14:03:19 -0400 Subject: [Tutor] advice on creating and working with a complex data structure In-Reply-To: References: Message-ID: > Have you considered using classes? This looks like a fairly natural fit for > race, candidate, committee and maybe report casses Aha, okay, the multiple classes approach makes sense. But would these be nested classes, perhaps inheriting attributes from their parent classes? E.g.: class Race class Candidate class Committee class Filing From bgailer at gmail.com Mon Jul 20 21:13:10 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 20 Jul 2009 15:13:10 -0400 Subject: [Tutor] advice on creating and working with a complex data structure In-Reply-To: References: Message-ID: <4A64C1C6.8000709@gmail.com> Serdar Tumgoren wrote: > Hi everyone, > I'm working with a database of campaign finance filings, and I'm > trying to create a data structure that captures the fact that: > - there can be multiple races > - races can have multiple candidates > - candidates can have multiple campaign committees > - campaign committees can file multiple reports > > I'm trying to pull these records from a database and output them to an > HTML file in sorted order. I suggest using the ORDER BY SQL Clause rather than trying to sort it in Python. [snip] -- Bob Gailer Chapel Hill NC 919-636-4239 From msh at blisses.org Mon Jul 20 21:53:38 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 15:53:38 -0400 Subject: [Tutor] sftp get single file In-Reply-To: <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> Message-ID: <20090720195338.GA19671@chicago.blisses.org> On Fri, Jul 17, 2009 at 12:12:52PM -0400, Kent Johnson wrote: > On Fri, Jul 17, 2009 at 11:42 AM, Sander Sweers wrote: > > > import time > > > > today = time.localtime() > > datestr = time.strftime("%Y%m%d",today) > > ext = ".tab" > > > > print datestr + ext > > You can include literal characters in the format string: > > In [4]: time.strftime("%Y%m%d.tab",today) > Out[4]: '20090717.tab' That does work and is compact while being intelligible. I'm still not getting the file. I thought this would work: if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp(remotepath,localpath) t.close() . . . but obviously something is missing. Traceback (most recent call last): File "./scpgetter.py", line 20, in ? sftp(remotepath,localpath) TypeError: 'SFTPClient' object is not callable I tried using the paramiko.SFTP.get method too. Failed. -- Matt H > > Kent -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From sander.sweers at gmail.com Mon Jul 20 22:22:37 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 20 Jul 2009 22:22:37 +0200 Subject: [Tutor] sftp get single file In-Reply-To: <20090720195338.GA19671@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> Message-ID: I do not know paramiko but looking over the client documentations... 2009/7/20 Matt Herzog : > if __name__ == "__main__": > t = paramiko.Transport((hostname, port)) > t.connect(username=username, password=password) > sftp = paramiko.SFTPClient.from_transport(t) Up to here it looks fine. > sftp(remotepath,localpath) If I understand it correctly you need to use sftp.get(remotepath, localpath). Greets Sander From msh at blisses.org Mon Jul 20 22:26:24 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 16:26:24 -0400 Subject: [Tutor] sftp get single file In-Reply-To: References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> Message-ID: <20090720202624.GA19836@chicago.blisses.org> On Mon, Jul 20, 2009 at 10:22:37PM +0200, Sander Sweers wrote: > I do not know paramiko but looking over the client documentations... > > 2009/7/20 Matt Herzog : > > if __name__ == "__main__": > > t = paramiko.Transport((hostname, port)) > > t.connect(username=username, password=password) > > sftp = paramiko.SFTPClient.from_transport(t) > > Up to here it looks fine. > > > sftp(remotepath,localpath) > > If I understand it correctly you need to use sftp.get(remotepath, localpath). Yeah that's exactly what I have tried, and the error is: Traceback (most recent call last): File "./scpgetter.py", line 20, in ? sftp.get(remotepath, localpath) File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 584, in get File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 240, in open File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 609, in _request File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 656, in _read_response File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 682, in _convert_status IOError: (2, '') > > Greets > Sander > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From sander.sweers at gmail.com Mon Jul 20 23:02:52 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 20 Jul 2009 23:02:52 +0200 Subject: [Tutor] sftp get single file In-Reply-To: <20090720202624.GA19836@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> Message-ID: 2009/7/20 Matt Herzog : > Traceback (most recent call last): > ?File "./scpgetter.py", line 20, in ? > ? ? ?sftp.get(remotepath, localpath) > ? ? ? ?File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 584, in get > ? ? ? ? ?File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 240, in open > ? ? ? ? ? ?File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 609, in _request > ? ? ? ? ? ? ?File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 656, in _read_response > ? ? ? ? ? ? ? ?File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 682, in _convert_status > ? ? ? ? ? ? ? ?IOError: (2, '') Ah, now it get interesting. Genrally IOError means the file is not found. And looking at the source for _convert_status it is axactly that. The file you are trying to "get" is not found on the server so check your remotepath. Greets Sander From msh at blisses.org Mon Jul 20 23:08:03 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 17:08:03 -0400 Subject: [Tutor] sftp get single file In-Reply-To: References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> Message-ID: <20090720210803.GB19836@chicago.blisses.org> On Mon, Jul 20, 2009 at 11:02:52PM +0200, Sander Sweers wrote: > 2009/7/20 Matt Herzog : > > Traceback (most recent call last): > > ??File "./scpgetter.py", line 20, in ? > > ?? ?? ??sftp.get(remotepath, localpath) > > ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 584, in get > > ?? ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 240, in open > > ?? ?? ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 609, in _request > > ?? ?? ?? ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 656, in _read_response > > ?? ?? ?? ?? ?? ?? ?? ??File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 682, in _convert_status > > ?? ?? ?? ?? ?? ?? ?? ??IOError: (2, '') > > Ah, now it get interesting. Genrally IOError means the file is not > found. And looking at the source for _convert_status it is axactly > that. The file you are trying to "get" is not found on the server so > check your remotepath. The file is there. I can sftp it using fugu. The path is /20090720.tab since the file lives in a jail. From sander.sweers at gmail.com Mon Jul 20 23:14:53 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 20 Jul 2009 23:14:53 +0200 Subject: [Tutor] sftp get single file In-Reply-To: <20090720210803.GB19836@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> Message-ID: 2009/7/20 Matt Herzog : > The file is there. I can sftp it using fugu. I am sure it is but paramiko can't find it. > The path is /20090720.tab since the file lives in a jail. Issue a sftp.listdir() and see what paramiko sees on the remote server. Greets Sander From msh at blisses.org Mon Jul 20 23:16:59 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 17:16:59 -0400 Subject: [Tutor] sftp get single file In-Reply-To: <20090720210803.GB19836@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> Message-ID: <20090720211659.GC19836@chicago.blisses.org> If I change remotepath = 'datestr' to remotepath = datestr I get: sftp.get(remotepath, localpath) File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 587, in get IOError: [Errno 21] Is a directory: '/tmp/testor/' So remotepath is really more like a path + filname. So I need to do something like os.join the two? -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From msh at blisses.org Mon Jul 20 23:24:16 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 17:24:16 -0400 Subject: [Tutor] paramiko list user said, Message-ID: <20090720212416.GD19836@chicago.blisses.org> A user of the paramiko mailing list said, "Paramiko has an SFTPClient class and an SSHClient that can be used to transfer files, why complicate it by using a Transport directly. The easiest thing is to open an SSHClient: c=paramiko.SSHClient() c.connect(username=username_, password=password_, hostname=hostname_) s=c.open_sftp() s.get/put etc.. " He lost me on the s.get/put part. I suppose he means s.get(remotepath, localpath) . . . or something. -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From sander.sweers at gmail.com Mon Jul 20 23:32:36 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 20 Jul 2009 23:32:36 +0200 Subject: [Tutor] sftp get single file In-Reply-To: <20090720211659.GC19836@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> <20090720211659.GC19836@chicago.blisses.org> Message-ID: 2009/7/20 Matt Herzog : > remotepath = 'datestr' Ok, you are now making a string. > remotepath = datestr Like Kent wrote the datestr can include other characters. So I would try "/%Y%m%d.tab". > sftp.get(remotepath, localpath) > ?File "build/bdist.linux-x86_64/egg/paramiko/sftp_client.py", line 587, in get > ?IOError: [Errno 21] Is a directory: '/tmp/testor/' paramiko still can not find the file. > So remotepath is really more like a path + filname. Yes. > So I need to do something like os.join the two? You probably mean os.path.join(), you can use it but imho it is overkill in your case. Just make sure you get the full path to the file in your remotepath. Greets Sander From sander.sweers at gmail.com Mon Jul 20 23:57:57 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 20 Jul 2009 23:57:57 +0200 Subject: [Tutor] sftp get single file In-Reply-To: <20090720214125.GE19836@chicago.blisses.org> References: <20090717150843.GA20678@chicago.blisses.org> <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> <20090720211659.GC19836@chicago.blisses.org> <20090720214125.GE19836@chicago.blisses.org> Message-ID: Please reply to the list. 2009/7/20 Matt Herzog : > Yeah. I have no idea if I am able to do this. The jail makes it ambiguous. There is no difference, the jail just moves the root directory as seen by the client. Did you do as suggested earlier to use listdir()? This will tell you how paramiko sees the server. I get the feeling you are in on over your head on this. Maybe you need to read the paramiko docs and play around in idle or other interactive python interpreter. The SFTPClient has all the basic commands any ssh client has (listdir, chdir etc). See [1]. Also have a look at [2] which is a good example of what can be done. Greets Sander [1] http://www.lag.net/paramiko/docs/paramiko.SFTPClient-class.html [2] http://code.activestate.com/recipes/576810/ From amit.pureenergy at gmail.com Tue Jul 21 00:01:34 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Tue, 21 Jul 2009 03:31:34 +0530 Subject: [Tutor] how to monitor if their data in a variable/object Message-ID: Hi , I am writing a python gtk application in which I am required to fetch a large amount of data from web , now i want to create a wait dialog for the user to know that I am still fetching data .The question is how can i monitor that the required data has been fetched . I could have a variable that is given a particular value when data has been fetched . But how can I keep checking if the variable has got a value or not. -- A-M-I-T S|S From srilyk at gmail.com Tue Jul 21 00:09:54 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 20 Jul 2009 17:09:54 -0500 Subject: [Tutor] how to monitor if their data in a variable/object In-Reply-To: References: Message-ID: <333efb450907201509q3a71060chfcfe4b36c21df4bc@mail.gmail.com> On Mon, Jul 20, 2009 at 5:01 PM, Amit Sethi wrote: > Hi , I am writing a python gtk application in which I am required to > fetch a large amount of data from web , now i want to create a wait > dialog for the user to know that I am still fetching data .The > question is how can i monitor that the required data has been fetched > . I could have a variable that is given a particular value when data > has been fetched . But how can I keep checking if the variable has > got a value or not. It really depends on how you're fetching the data. If you write your own method to read a few kilobytes at a time, you can easily update a status bar. Otherwise if you know the file it's downloading to (i.e. not a temp file) you could continually call os.stat to update the status bar (especially if you know the size it's supposed to be in the end). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From msh at blisses.org Tue Jul 21 00:18:19 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 18:18:19 -0400 Subject: [Tutor] sftp get single file In-Reply-To: References: <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720195338.GA19671@chicago.blisses.org> <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> <20090720211659.GC19836@chicago.blisses.org> <20090720214125.GE19836@chicago.blisses.org> Message-ID: <20090720221819.GH19836@chicago.blisses.org> On Mon, Jul 20, 2009 at 11:57:57PM +0200, Sander Sweers wrote: > Please reply to the list. > > 2009/7/20 Matt Herzog : > > Yeah. I have no idea if I am able to do this. The jail makes it ambiguous. > > There is no difference, the jail just moves the root directory as seen > by the client. > > Did you do as suggested earlier to use listdir()? This will tell you > how paramiko sees the server. Yeah, I managed to get that to work like so: if __name__ == "__main__": t = paramiko.Transport((hostname, port)) t.connect(username=username, password=password) sftp = paramiko.SFTPClient.from_transport(t) print sftp.listdir() t.close() It displays the contents of the dir no problem. > > I get the feeling you are in on over your head on this. Yes, and I have a deadline. > Maybe you need > to read the paramiko docs and play around in idle or other interactive > python interpreter. The SFTPClient has all the basic commands any ssh > client has (listdir, chdir etc). See [1]. I should not need to chdir, right? In fact, the server's policy forbids it. Perhaps I need to chdir on the local host? > Also have a look at [2] which is a good example of what can be done. Yeah I saw that page. The code seemed bloated to me. > > Greets > Sander > > [1] http://www.lag.net/paramiko/docs/paramiko.SFTPClient-class.html > [2] http://code.activestate.com/recipes/576810/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From srilyk at gmail.com Tue Jul 21 00:26:09 2009 From: srilyk at gmail.com (Wayne) Date: Mon, 20 Jul 2009 17:26:09 -0500 Subject: [Tutor] sftp get single file In-Reply-To: <20090720221819.GH19836@chicago.blisses.org> References: <1c2a2c590907170912o4b7a80beq5867ce03d919054f@mail.gmail.com> <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> <20090720211659.GC19836@chicago.blisses.org> <20090720214125.GE19836@chicago.blisses.org> <20090720221819.GH19836@chicago.blisses.org> Message-ID: <333efb450907201526m232ed74o8c996773d5003afd@mail.gmail.com> On Mon, Jul 20, 2009 at 5:18 PM, Matt Herzog wrote: > On Mon, Jul 20, 2009 at 11:57:57PM +0200, Sander Sweers wrote: > > Please reply to the list. > > > > 2009/7/20 Matt Herzog : > > > Yeah. I have no idea if I am able to do this. The jail makes it > ambiguous. > > > > There is no difference, the jail just moves the root directory as seen > > by the client. > > > > Did you do as suggested earlier to use listdir()? This will tell you > > how paramiko sees the server. > > Yeah, I managed to get that to work like so: > > if __name__ == "__main__": > t = paramiko.Transport((hostname, port)) > t.connect(username=username, password=password) > sftp = paramiko.SFTPClient.from_transport(t) > print sftp.listdir() > t.close() > > It displays the contents of the dir no problem. Is the file present in the dir? What is it listed as? Is it just 07232009.tab (or similar) or is it /home/user/jail/07232009.tab? That may make a difference. > > > > > > I get the feeling you are in on over your head on this. > > Yes, and I have a deadline. > > > Maybe you need > > to read the paramiko docs and play around in idle or other interactive > > python interpreter. The SFTPClient has all the basic commands any ssh > > client has (listdir, chdir etc). See [1]. > > I should not need to chdir, right? In fact, the server's policy forbids it. > Perhaps I need to chdir on the local host? That shouldn't make a difference as far as getting the file is concerned - unless you're trying to put it in a file on your computer that doesn't exist! I'd really recommend playing around in the interpreter - especially if you have ipython. Good luck, HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jul 21 01:05:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Jul 2009 00:05:37 +0100 Subject: [Tutor] advice on creating and working with a complex datastructure References: Message-ID: "Serdar Tumgoren" wrote > Aha, okay, the multiple classes approach makes sense. But would these > be nested classes, No although they would probably have attributes containing the related lists. Thus Race might have a list of Candidates. And Candidate would have a list of Committees etc. > perhaps inheriting attributes from their parent > classes? E.g.: I do not think any of these meet the criteria for inheritance. None of them "is a" kind of any of the others. > class Race > > class Candidate > > class Committee > > class Filing I don;t like the use of Filing for a class name, it sounds like a collection and in Python we don;t usually need to crteate collection classes, we can just use a standard collection type. Maybe File would be better although it could be confused with a comuter file... Maybe Record would be best? HTH Alan G. From msh at blisses.org Tue Jul 21 04:16:49 2009 From: msh at blisses.org (Matt Herzog) Date: Mon, 20 Jul 2009 22:16:49 -0400 Subject: [Tutor] sftp get single file In-Reply-To: <333efb450907201526m232ed74o8c996773d5003afd@mail.gmail.com> References: <20090720202624.GA19836@chicago.blisses.org> <20090720210803.GB19836@chicago.blisses.org> <20090720211659.GC19836@chicago.blisses.org> <20090720214125.GE19836@chicago.blisses.org> <20090720221819.GH19836@chicago.blisses.org> <333efb450907201526m232ed74o8c996773d5003afd@mail.gmail.com> Message-ID: <20090721021649.GA23486@chicago.blisses.org> On Mon, Jul 20, 2009 at 05:26:09PM -0500, Wayne wrote: > On Mon, Jul 20, 2009 at 5:18 PM, Matt Herzog wrote: > > > On Mon, Jul 20, 2009 at 11:57:57PM +0200, Sander Sweers wrote: > > > Please reply to the list. > > > > > > 2009/7/20 Matt Herzog : > > > > Yeah. I have no idea if I am able to do this. The jail makes it > > ambiguous. > > > > > > There is no difference, the jail just moves the root directory as seen > > > by the client. > > > > > > Did you do as suggested earlier to use listdir()? This will tell you > > > how paramiko sees the server. > > > > Yeah, I managed to get that to work like so: > > > > if __name__ == "__main__": > > t = paramiko.Transport((hostname, port)) > > t.connect(username=username, password=password) > > sftp = paramiko.SFTPClient.from_transport(t) > > print sftp.listdir() > > t.close() > > > > It displays the contents of the dir no problem. > > > Is the file present in the dir? What is it listed as? Is it just > 07232009.tab (or similar) or is it /home/user/jail/07232009.tab? That may > make a difference. Yes, the file 20090720.tab (today's date dot tab) is present in the dir listing. The dir contents are printed out in a comma delimited list from left to right that wraps several times. There are probably 30 subdirs and a dozen files in that dir. If you use the sftp cli binary and type, 'pwd' it tells you, '/'. > > > > > > > > > > > > I get the feeling you are in on over your head on this. > > > > Yes, and I have a deadline. > > > > > Maybe you need > > > to read the paramiko docs and play around in idle or other interactive > > > python interpreter. The SFTPClient has all the basic commands any ssh > > > client has (listdir, chdir etc). See [1]. > > > > I should not need to chdir, right? In fact, the server's policy forbids it. > > Perhaps I need to chdir on the local host? > > > That shouldn't make a difference as far as getting the file is concerned - > unless you're trying to put it in a file on your computer that doesn't > exist! I'm trying to put a file in a dir called /tmp/testor. The user the script runs as owns the dir. > > I'd really recommend playing around in the interpreter - especially if you > have ipython. I have ipython. I like ipython. I just don't get enough opportunities to do python scripting. > > Good luck, HTH, > Wayne -- I fear you speak upon the rack, Where men enforced do speak anything. - William Shakespeare From srilyk at gmail.com Tue Jul 21 13:54:29 2009 From: srilyk at gmail.com (Wayne) Date: Tue, 21 Jul 2009 06:54:29 -0500 Subject: [Tutor] advice on creating and working with a complex datastructure In-Reply-To: References: Message-ID: <333efb450907210454p3099dbcbg521a44f57f3beab1@mail.gmail.com> On Mon, Jul 20, 2009 at 6:05 PM, Alan Gauld wrote: > "Serdar Tumgoren" wrote > >> Aha, okay, the multiple classes approach makes sense. But would these >> be nested classes, >> > > No although they would probably have attributes containing > the related lists. Thus Race might have a list of Candidates. > And Candidate would have a list of Committees etc. > > perhaps inheriting attributes from their parent >> classes? E.g.: >> > > I do not think any of these meet the criteria for inheritance. None of them > "is a" kind of any of the others. > > class Race >> >> class Candidate >> >> class Committee >> >> class Filing >> > > I don;t like the use of Filing for a class name, it sounds like a > collection and in Python we don;t usually need to crteate collection > classes, we can just use a standard collection type. Maybe File would be > better although it could be confused with a comuter file... Maybe Record > would be best? If the candidate can file reports, perhaps the candidate should have a member list (or some other appropriate container) called reports and a method/function called file_report? -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Tue Jul 21 14:04:18 2009 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Tue, 21 Jul 2009 08:04:18 -0400 Subject: [Tutor] advice on creating and working with a complex datastructure In-Reply-To: <333efb450907210454p3099dbcbg521a44f57f3beab1@mail.gmail.com> References: <333efb450907210454p3099dbcbg521a44f57f3beab1@mail.gmail.com> Message-ID: >> >> I do not think any of these meet the criteria for inheritance. None of >> them "is a" kind of any of the others. >> I refreshed on my OO terminology and I see your point -- that composition is a more appropriate fit here than inheritance. >> I don;t like the use of Filing for a class name, it sounds like a >> collection and in Python we don;t usually need to crteate collection >> classes, we can just use a standard collection type. Maybe File would be >> better although it could be confused with a comuter file... Maybe Record >> would be best? So the below are the classes names I've settled on: class Race(object) class Candidate(object) class Committee(object) class Report(object) I haven't quite thought through the attributes for all of the classes and how they'll interact, so I suppose that's the next phase. I'm sure I'll post back as I work through it. Meantime, many thanks to all for the help. As always, I'm wowed by speed and variety of responses. Regards, Serdar From SwiftStar at comcast.net Tue Jul 21 20:12:23 2009 From: SwiftStar at comcast.net (Deb) Date: Tue, 21 Jul 2009 11:12:23 -0700 (Pacific Daylight Time) Subject: [Tutor] Question from a newbie Message-ID: <4A660507.00000E.03852@FIBERFOLLY-PC> My son suggested I play around with Python. I was wondering if anybody has any real life applications? It appears to be able to do quite a lot, but is anybody really doing it with Python? I am very curious about this language. I used to be a Clipper programmer in another life (dBASE compiler), and got sick when I was just entering the OOP world via Visual Basic and had to quit I just recently got my brain back, thanks to medical science, and would like to learn all I can about what it out there these days. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1458 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 5769 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 1189 bytes Desc: not available URL: From kent37 at tds.net Wed Jul 22 00:08:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Jul 2009 18:08:08 -0400 Subject: [Tutor] Question from a newbie In-Reply-To: <4A660507.00000E.03852@FIBERFOLLY-PC> References: <4A660507.00000E.03852@FIBERFOLLY-PC> Message-ID: <1c2a2c590907211508y290dd025pc9a8baa89c93fad7@mail.gmail.com> On Tue, Jul 21, 2009 at 2:12 PM, Deb wrote: > My son suggested I play around with Python.? I was wondering if anybody has > any real life applications?? It appears to be able to do quite a lot, but is > anybody really doing it with Python? Yes, Python is used in a wide variety of real-life applications. For some examples, see http://python.org/about/success/ Is there a particular application area you are interested in? Kent From alan.gauld at btinternet.com Wed Jul 22 00:14:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Jul 2009 23:14:53 +0100 Subject: [Tutor] Question from a newbie References: <4A660507.00000E.03852@FIBERFOLLY-PC> Message-ID: "Deb" wrote > My son suggested I play around with Python. Hi, welcome to the tutor list. > I was wondering if anybody has any real life applications? There are several folks on the list who make a liiving writing Python. Others, like myself, use it in their day job but its not the main or end product (I use it for prototyping ideas that our Indian developers eventually turn into Java....) Some organisations - Google is the best known - use Python for writing their test harnesses and admin tools etc. Several Linux distruibutions have used Python to create their admin tools for adding users etc. HP did the same on Windows for a while. Blender is a well kinown open source graphics tool that uses embedded Python as its macro language, as do a few others. Check out the Python web site for more success stories to see how widespread it is. Look at the links top right on the home page... And of course it is also a great scripting language to replace DOS batch files, Unix shell scripts and awk/sed/perl/Tcl etc etc -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From pine508 at hotmail.com Wed Jul 22 02:05:01 2009 From: pine508 at hotmail.com (Che M) Date: Tue, 21 Jul 2009 20:05:01 -0400 Subject: [Tutor] code structure terminology and advice Message-ID: Hi, this is really more of a general programming question than a Python question, though perhaps there is a Python-relevant set of terms/answers to it... I'm trying to refactor some code to be more structurally "proper", more easily maintained, etc. Doing some "thinking out loud", and I have two questions: Q1) Generally, what is the best structure for when there are a number of steps/actions that need to be taken? Q2) Is there a term/some jargon in programming that refers to the difference between examples 1-3 below? Examples: Let's say I have some wish to perform four related sequential actions--steps, let's call them--in some part of the program. In terms of grouping those actions, there are 3 ways I can think to do this (pseudocode): 1. Do the steps all in one function: def Function(self): do step1 action do step2 action do step3 action do step4 action 2. Have each step be a function, and have each function call the next function in the chain: def StepOne(self): do step1 action self.StepTwo() def StepTwo(self): do step2 action self.StepThree() 3. Make each step a function, but call all of them in order in one master function: def MasterFunction(self): self.StepOne() self.StepTwo() self.StepThree() self.StepFour() (elsewhere these functions are defined) etc... It seems to me that example 3 is the most sensible. 1 is bad because the steps should be functions, because then they can be easily reused, seen from an IDE explorer, etc. (I guess if they are really minor things it isn't necessary). 2 is terrible because it introduces far too much dependence and might be hard to maintain. It is also possible to sort of mix aspects of all of these...that also seems jumbled. Maybe there are other and better ways to think about organizing a sequence of steps, and if so I'd love to hear them. I'd also like to know what I might look up to read up on managing this kind of thing. Thanks, Che _________________________________________________________________ Windows Live? Hotmail?: Search, add, and share the web?s latest sports videos. Check it out. http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_videos_072009&cat=sports -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jul 22 09:46:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Jul 2009 08:46:04 +0100 Subject: [Tutor] code structure terminology and advice References: Message-ID: "Che M" wrote You pretty much answered your own question. The ultimate answer depends on a few other contextual issues. > Q1) Generally, what is the best structure for when there are > a number of steps/actions that need to be taken? A sequence! :-) > Q2) Is there a term/some jargon in programming that > refers to the difference between examples 1-3 below? Not that I'm aware of. > wish to perform four related sequential actions--steps, > let's call them--in some part of the program. If the entire program consists of those 4 steps (as in a batch data processing program, say) then you might structure things differently than if the 4 steps are only part of a bigger program - one menu option out of several, say. In the former you would perform the steps in sequence and may or may not put them in functions.depending on whether they would ever be reused and how long the code was per step. In most cases the steps are likely to be reusable or of significant length so you would put each one in its own function. > 1. Do the steps all in one function: > > def Function(self): > do step1 action > do step2 action > do step3 action > do step4 action This would be sensible in the menu selection context. > 2. Have each step be a function, and have each function > call the next function in the chain: No, this is terrrible from every point of view. It removes any opportunity of reuise of individual steps and builds up a deep call stack which makes debugging harder and the coupling between functions makes maintenance harder (for example swapping two steps around in the sequence) > def StepOne(self): > do step1 action > StepTwo() > 3. Make each step a function, but call all of them in order in > one master function: > > def MasterFunction(self): > self.StepOne() > self.StepTwo() This is just a variation on option 1 and the same applies. The fourth option you do not consider but which could be the best solution for the batch program I discussed is just to perform each step from the top klevel of the program, ie no enclosing function StepOne() StepTwo() StepThree() StepFour() > It seems to me that example 3 is the most sensible. In general yes. > 1 is bad because the steps should be functions, because then they > can be easily reused, seen from an IDE explorer, etc. > (I guess if they are really minor things it isn't necessary). This depends on the size of the steps and the nature of the overall programme, but functions would usually be best. > 2 is terrible Yes. > Maybe there are other and better ways to think about organizing > a sequence of steps, and if so I'd love to hear them. For longer and more complex processes you could use a table or list of functions and step through them in a loop process = [StepOne, StepTwo,...., stepN] for step in process: step() Or for dynamically changing sequences you can create or hold a sequence list and use that to index a list of steps: steps = [StepOne, StepTwo,...., stepN] sequence = [1,2,3,4] def do Process(sequence) for step in sequence: steps[step]() This allows you to selectively peform some of the steps: sequence = [1,3,4,N] doProcess(sequence) Finally for very complex scenarios you might implement a state machine where the return value of each step controls the next step in the sequence. That can be done by building a set of state objects or using a data driven approach with a table You can read about state machines in several places, I'd start with Wikipedia. You might also find that reading about business process execution languages gives you some ideas about how to structure and represent complex processes. BEPL would be a good starting point, again try Wikipedia. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From digitalman66 at gmail.com Wed Jul 22 03:21:16 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Tue, 21 Jul 2009 20:21:16 -0500 Subject: [Tutor] Question from a newbie In-Reply-To: <4A660507.00000E.03852@FIBERFOLLY-PC> References: <4A660507.00000E.03852@FIBERFOLLY-PC> Message-ID: <24a9d1f30907211821i69636600l854bbda26f5e6622@mail.gmail.com> Deb, For starters most of the Google enterprise runs on python. Google App Engin e is for developers to develop web applications on Google There are many applications ranging from web frameworks to math modules. Web frameworks: Django , Repoze BFG, Pylons , Turbo Gears , CherryPy NumPy for math/physics. Plone is a content management system used by many schools and governments. Python website has lots of information to learn python. Documents, Python Enhancement Proposals , Communityand the Python Package Index . It is a beautiful language! Good Luck :) On Tue, Jul 21, 2009 at 1:12 PM, Deb wrote: > My son suggested I play around with Python. I was wondering if > anybody has any real life applications? It appears to be able to do quite a > lot, but is anybody really doing it with Python? I am very curious about > this language. I used to be a Clipper programmer in another life (dBASE > compiler), and got sick when I was just entering the OOP world via Visual > Basic and had to quit. I just recently got my brain back, thanks to medical > science, and would like to learn all I can about what it out there these > days. > > Thanks, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 1189 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 5769 bytes Desc: not available URL: From digitalman66 at gmail.com Wed Jul 22 03:26:34 2009 From: digitalman66 at gmail.com (Glen Zangirolami) Date: Tue, 21 Jul 2009 20:26:34 -0500 Subject: [Tutor] code structure terminology and advice In-Reply-To: References: Message-ID: <24a9d1f30907211826x7454a8b3jd2ccdc18cea1870b@mail.gmail.com> Che, You should check out the python styling guide here. It give examples about how to write python code. PEP 8 -- Style Guide for Python Code Hope this helps! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mknowles at fs.fed.us Wed Jul 22 12:03:27 2009 From: mknowles at fs.fed.us (Michael Knowles) Date: Wed, 22 Jul 2009 04:03:27 -0600 Subject: [Tutor] Michael Knowles/NONFS/USDAFS is out of the office. Message-ID: I will be out of the office starting 07/22/2009 and will not return until 07/27/2009. I am out of the office and will respond to your message when I return on Monday, 30 Sep. From jfabiani at yolo.com Wed Jul 22 16:12:38 2009 From: jfabiani at yolo.com (John) Date: Wed, 22 Jul 2009 07:12:38 -0700 Subject: [Tutor] Question from a newbie In-Reply-To: <4A660507.00000E.03852@FIBERFOLLY-PC> References: <4A660507.00000E.03852@FIBERFOLLY-PC> Message-ID: <200907220712.38553.jfabiani@yolo.com> On Tuesday 21 July 2009 11:12:23 am Deb wrote: > My son suggested I play around with Python. I was wondering if anybody has > any real life applications? It appears to be able to do quite a lot, but > is anybody really doing it with Python? I am very curious about this > language. I used to be a Clipper programmer in another life (dBASE > compiler), and got sick when I was just entering the OOP world via Visual > Basic and had to quit I just recently got my brain back, thanks to medical > science, and would like to learn all I can about what it out there these > days. > > Thanks, Then you'll love Dabo (www.dabodev.com) which is built on python, wxPython, and supports databases like Postgres, MsSQL, MySQL, Firebird, and SQLite. The thinking is very similar to Visual FoxPro. Classes are close and the coding is close. If you ever used any of the VFP (clipper) frameworks then it will be old hat. Johnf From roberto03 at gmail.com Wed Jul 22 16:38:36 2009 From: roberto03 at gmail.com (roberto) Date: Wed, 22 Jul 2009 16:38:36 +0200 Subject: [Tutor] demo/turtle Message-ID: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> hello i'd like to download the demo/turtle directory but i could not find the correct link; i need it to run the exampled cited in http://docs.python.org/library/turtle.html can you tell me where to find it ? my version is 2.6.2 thank you very much -- roberto From alan.gauld at btinternet.com Wed Jul 22 19:06:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Jul 2009 18:06:08 +0100 Subject: [Tutor] demo/turtle References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> Message-ID: "roberto" wrote > i'd like to download the demo/turtle directory but i could not find > the correct link; > > i need it to run the exampled cited in > http://docs.python.org/library/turtle.html > > can you tell me where to find it ? > my version is 2.6.2 I believe the new turtle module should be installed as standard on 2.6. So the example code should just work. Which OS are you on? Some Linux versions of Python don't have Tkinter loaded and that will probably prevent turtle from running... What happens when you try it? Do you get an error message? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From amrita at iisermohali.ac.in Wed Jul 22 20:03:39 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Wed, 22 Jul 2009 23:33:39 +0530 (IST) Subject: [Tutor] how to fill zero value and join two column Message-ID: <25661.210.212.36.65.1248285819.squirrel@www.iisermohali.ac.in> Hi, I have two text file, having entries as fileA 33 ALA H = 7.57 N = 121.52 CA = 55.58 HA = 3.89 C = 179.24 38 ALA H = 8.29 N = 120.62 CA = 54.33 HA = 4.04 C = 178.95 8 ALA H = 7.85 N = 123.95 CA = 54.67 HA = C = fileB 8 ALA helix (helix_alpha, helix1) 21 ALA helix (helix_alpha, helix2) 23 ALA helix (helix_alpha, helix2) now what i want that i will make another file in which the matching entries from the two file get printed together along with zero values for those atoms which doesnot have nay value in fileA. so the reult will be something like:- fileC 8 ALA H = 7.85 N = 123.95 CA = 54.67 HA =0.00 C =0.00|8 ALA helix (helix_alpha, helix1) I tried to merge these two files using commands like:- from collections import defaultdict >>> def merge(sources): ... if __name__ == "__main__": ... a = open("/home/amrita/alachems/chem100.txt") ... c = open("/home/amrita/secstr/secstr100.txt") ... def source(stream): ... return (line.strip() for line in stream) ... for m in merge([source(x) for x in [a,c]]): ... print "|".join(c.ljust(10) for c in m) ... but it is not giving any value. Thanks, Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From pine508 at hotmail.com Wed Jul 22 20:30:42 2009 From: pine508 at hotmail.com (Che M) Date: Wed, 22 Jul 2009 14:30:42 -0400 Subject: [Tutor] code structure terminology and advice In-Reply-To: References: Message-ID: > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Wed, 22 Jul 2009 08:46:04 +0100 > Subject: Re: [Tutor] code structure terminology and advice > > > "Che M" wrote > > You pretty much answered your own question. > > The ultimate answer depends on a few other contextual issues. > > > Q1) Generally, what is the best structure for when there are > > a number of steps/actions that need to be taken? > > A sequence! :-) > > > Q2) Is there a term/some jargon in programming that > > refers to the difference between examples 1-3 below? > > Not that I'm aware of. > > > wish to perform four related sequential actions--steps, > > let's call them--in some part of the program. > > If the entire program consists of those 4 steps (as in a batch > data processing program, say) then you might structure things > differently than if the 4 steps are only part of a bigger > program - one menu option out of several, say. > > In the former you would perform the steps in sequence and > may or may not put them in functions.depending on whether > they would ever be reused and how long the code was per step. > In most cases the steps are likely to be reusable or of significant > length so you would put each one in its own function. > > > 1. Do the steps all in one function: > > > > def Function(self): > > do step1 action > > do step2 action > > do step3 action > > do step4 action > > This would be sensible in the menu selection context. > > > 2. Have each step be a function, and have each function > > call the next function in the chain: > > No, this is terrrible from every point of view. It removes any > opportunity of reuise of individual steps and builds up a deep > call stack which makes debugging harder and the coupling > between functions makes maintenance harder (for example > swapping two steps around in the sequence) > > > def StepOne(self): > > do step1 action > > StepTwo() > > > 3. Make each step a function, but call all of them in order in > > one master function: > > > > def MasterFunction(self): > > self.StepOne() > > self.StepTwo() > > This is just a variation on option 1 and the same applies. > > The fourth option you do not consider but which could be the > best solution for the batch program I discussed is just to perform > each step from the top klevel of the program, ie no > enclosing function > > StepOne() > StepTwo() > StepThree() > StepFour() > > > > It seems to me that example 3 is the most sensible. > > In general yes. > > > 1 is bad because the steps should be functions, because then they > > can be easily reused, seen from an IDE explorer, etc. > > (I guess if they are really minor things it isn't necessary). > > This depends on the size of the steps and the nature of the overall > programme, but functions would usually be best. > > > 2 is terrible > > Yes. > > > Maybe there are other and better ways to think about organizing > > a sequence of steps, and if so I'd love to hear them. > > For longer and more complex processes you could use a table > or list of functions and step through them in a loop > > process = [StepOne, StepTwo,...., stepN] > > for step in process: > step() > > Or for dynamically changing sequences you can create or hold > a sequence list and use that to index a list of steps: > > steps = [StepOne, StepTwo,...., stepN] > sequence = [1,2,3,4] > > def do Process(sequence) > for step in sequence: > steps[step]() > > This allows you to selectively peform some of the steps: > > sequence = [1,3,4,N] > > doProcess(sequence) > > Finally for very complex scenarios you might implement a > state machine where the return value of each step controls > the next step in the sequence. That can be done by building > a set of state objects or using a data driven approach with > a table > > You can read about state machines in several places, > I'd start with Wikipedia. > > You might also find that reading about business process execution > languages gives you some ideas about how to structure and > represent complex processes. BEPL would be a good > starting point, again try Wikipedia. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ Thank you, Alan. It is sometimes helpful just to get corroboration, and I feel that sometimes the simplest things are the most important. I also thought that maybe the mistake in example 2 had a name; I don't know if it is a common mistake or not for beginning programmers, but I have found myself doing it sometimes and I am making a point to undo it now in any old code. The point about looping through a list of functions is also something that hadn't occurred to me. So this is all very helpful. Thanks, Che _________________________________________________________________ Windows Live? Hotmail?: Celebrate the moment with your favorite sports pics. Check it out. http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports -------------- next part -------------- An HTML attachment was scrubbed... URL: From roberto03 at gmail.com Wed Jul 22 20:41:22 2009 From: roberto03 at gmail.com (roberto) Date: Wed, 22 Jul 2009 20:41:22 +0200 Subject: [Tutor] demo/turtle In-Reply-To: References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> Message-ID: <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote: > > "roberto" wrote >> >> i'd like to download the demo/turtle directory but i could not find >> the correct link; >> >> i need it to run the exampled cited in >> http://docs.python.org/library/turtle.html >> >> can you tell me where to find it ? >> my version is 2.6.2 > > I believe the new turtle module should be installed as standard on 2.6. > So the example code should just work. > > Which OS are you on? Some Linux versions of Python don't have Tkinter loaded > and that ?will probably prevent turtle from running... > What happens when you try it? Do you get an error message? the os is Xp; the problem is simply i cannot find this directory in my current python installation folder ... > > > -- -- roberto From davea at ieee.org Wed Jul 22 21:08:34 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 22 Jul 2009 15:08:34 -0400 Subject: [Tutor] demo/turtle In-Reply-To: <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> Message-ID: <4A6763B2.3040905@ieee.org> roberto wrote: > On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote: > >> "roberto" wrote >> >>> i'd like to download the demo/turtle directory but i could not find >>> the correct link; >>> >>> i need it to run the exampled cited in >>> http://docs.python.org/library/turtle.html >>> >>> can you tell me where to find it ? >>> my version is 2.6.2 >>> >> I believe the new turtle module should be installed as standard on 2.6. >> So the example code should just work. >> >> Which OS are you on? Some Linux versions of Python don't have Tkinter loaded >> and that will probably prevent turtle from running... >> What happens when you try it? Do you get an error message? >> > the os is Xp; > the problem is simply i cannot find this directory in my current > python installation folder ... > > According to: http://docs.python.org/library/turtle.html#demo-scripts, the demo/turtle directory is in the *source* distribution. Many Windows users don't get the source distro, they just get the windows install package. Go to http://www.python.org/ and on the left side, find the link labeled "source distribution" Click on it, and you should be able to download Python-2.6.2.tar.bz2 It's 10.6MB in size. And inside that tar.bz2 file, you'll find a directory Python-2.6.2\Demo\turtle DaveA From davea at ieee.org Wed Jul 22 21:24:14 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 22 Jul 2009 15:24:14 -0400 Subject: [Tutor] Bouncing mail In-Reply-To: <200907221909.n6MJ98Tn013309@tlgmlp01.teamlog.com> References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> <4A6763B2.3040905@ieee.org> <200907221909.n6MJ98Tn013309@tlgmlp01.teamlog.com> Message-ID: <4A67675E.5010100@ieee.org> Genevi?ve DIAGORN wrote: > Bonjour, > Je suis absente jusqu'au 23/07 inclus. > Je prendrai connaissance de votre mail vendredi. > En cas d'urgence Soprane, contacter Beno?t Tottereau ou William Dibas. > Cordialement. > > Genevi?ve > > If you must use an "out of office" auto-reply, then unsubscribe to the mailing list(s) first. Getting all these French messages are pretty annoying, and I suspect it's going to anybody who posts to the list, not just to me. Anyone else seeing these? DaveA From fomcl at yahoo.com Wed Jul 22 21:42:36 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 22 Jul 2009 12:42:36 -0700 (PDT) Subject: [Tutor] xlwt & xlrd: can I refactor this code better? In-Reply-To: <4A67675E.5010100@ieee.org> Message-ID: <594157.27832.qm@web110708.mail.gq1.yahoo.com> Hi, A while ago I wrote a program to merge xls files. Now I refactored it because before, it was one big chunk of spaghetti code and I wanted to add some functionality. The code below works, but I have the feeling that it could still be simplified. Most functions have many arguments - isn't that called 'tight coupling'? Could somebody give me a few general pointers as to how to improve this program without loosing functionality? The first function is the main() function. Shouldn't a programmer strive for information hiding in such a function? Ideally, it should almost read like regular english, right? Or is that too textbook-ish? ;-) Thanks in advance! Albert-Jan """ Merge all xls files in a given directory into one multisheet xls file. The sheets get the orginal file name, without the extension. File names should not exceed 29 characters """ import glob, os.path, time import xlrd, xlwt def merge_xls(in_dir="d:/temp/", out_file="d:/temp/merged_output.xls"): """ Main function: merge xls sheets """ xls_files = glob.glob(in_dir + "*.xls") xls_files.sort() merged_book = xlwt.Workbook() osheet_names = [os.path.basename(xls_file)[:-4] for xls_file in xls_files] for xls_no, xls_file in enumerate(xls_files): print "---> Processing file %s" % (xls_file) book = xlrd.open_workbook(xls_file) isheet_names = xlrd.Book.sheet_names(book) check_xls(book, merged_book, isheet_names, osheet_names, xls_no, xls_files) stamped_outfile = out_file[:-4] + "_" + time.strftime("%Y-%m-%d") + ".xls" merged_book.save(stamped_outfile) print_msg(xls_files, osheet_names, stamped_outfile) def check_xls(book, merged_book, isheet_names, osheet_names, xls_no, xls_files): """ Check existence and file names of input xls files """ if xls_files and len(osheet_names[xls_no]) <= 29: write_sheets(book, merged_book, isheet_names, osheet_names, xls_no, xls_files) elif xls_files: print "WARNING *** File name too long: <%s.xls> (maximum is 31 chars) " % (osheet_names[xls_no]) print "WARNING *** File <%s.xls> was skipped." % (osheet_names[xls_no]) else: print "NOTE *** No xls files in %s. Nothing to do" % (in_dir) def write_sheets(book, merged_book, isheet_names, osheet_names, xls_no, xls_files): """ Write sheets, and add sheet numbering in case of multisheet xls input """ osheet_name = osheet_names[xls_no] xls_file = xls_files[xls_no] if book.nsheets == 1: ws = merged_book.add_sheet(osheet_name) isheet_name = isheet_names[0] sheet = book.sheet_by_index(0) write_cells(sheet, book, ws, isheet_name, osheet_name, xls_file) elif book.nsheets in range(1, 100): for sheetx in range(book.nsheets): isheet_name = isheet_names[sheetx] ws = merged_book.add_sheet(osheet_name+str(sheetx+1).zfill(2)) sheet = book.sheet_by_index(sheetx) write_cells(sheet, book, ws, isheet_name, osheet_name, xls_file) else: raise Exception ("ERROR *** File %s has %s sheets (maximum is 99)" % (xls_file, book.nsheets)) def write_cells(sheet, book, ws, isheet_name, osheet_name, xls_file, format_cell=True): """ Write cells, and apply formatting if needed """ MISSINGVALUES = ("#LEEG!", "#NULL!") rx = 0 # initialize to zero in case of empty input xls file. style = format_cells(ws) for rx in range(sheet.nrows): for cx in range(sheet.ncols): cell_value = sheet.cell_value(rx, cx) if format_cell and rx == 0: format_cells(ws) ws.write(rx, cx, cell_value, style) elif cell_value in MISSINGVALUES or xlrd.XL_CELL_EMPTY: ws.write(rx, cx, " ") else: ws.write(rx, cx, cell_value) footer = "source tab: " + isheet_name + " || source file: " + os.path.basename(xls_file) if format_cell: ws.write(rx+2, 0, footer.upper(), style) # print bold source tab & file name below the table else: ws.write(rx+2, 0, footer.upper()) def format_cells(ws, font='Arial', boldrow=True, panes_frozen=True): """ Add horizontal split pane and bold font at first row """ ws.panes_frozen = panes_frozen ws.horz_split_pos = 1 font0 = xlwt.Font() font0.name = font font0.struck_out = False font0.bold = boldrow style0 = xlwt.XFStyle() style0.font = font0 return style0 def print_msg(xls_files, osheet_names, stamped_outfile): """ Print status messages """ print "\n---> Merged xls file written to %s using the following source files: " % (stamped_outfile) MAXSHEETNAMELEN = 29 for n_sheet, osheet_name in enumerate(osheet_names): if len(osheet_name) <= MAXSHEETNAMELEN: print "\t", str(n_sheet+1).zfill(3), "%s.xls" % (osheet_name) excl_sheets = [os.path.basename(xls_file)[:-4] for xls_file in xls_files if \ len(os.path.basename(xls_file)[:-4]) > MAXSHEETNAMELEN] if excl_sheets: print "\n--> The following files were skipped because the file name exceeds 29 characters: " for n_sheet, excl_sheet in enumerate(excl_sheets): print "\t", str(n_sheet+1).zfill(3), excl_sheet if __name__ == "__main__": merge_xls() From sander.sweers at gmail.com Wed Jul 22 22:33:12 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 22 Jul 2009 22:33:12 +0200 Subject: [Tutor] Bouncing mail In-Reply-To: <4A67675E.5010100@ieee.org> References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> <4A6763B2.3040905@ieee.org> <200907221909.n6MJ98Tn013309@tlgmlp01.teamlog.com> <4A67675E.5010100@ieee.org> Message-ID: 2009/7/22 Dave Angel : > Anyone else seeing these? Unfortunately yes. Very annoying... :( Greets Sander From gregor.lingl at aon.at Wed Jul 22 23:34:12 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 22 Jul 2009 23:34:12 +0200 Subject: [Tutor] demo/turtle In-Reply-To: <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> Message-ID: <4A6785D4.8090207@aon.at> roberto schrieb: > On Wed, Jul 22, 2009 at 7:06 PM, Alan Gauld wrote: > >> "roberto" wrote >> >>> i'd like to download the demo/turtle directory but i could not find >>> the correct link; >>> >>> i need it to run the exampled cited in >>> http://docs.python.org/library/turtle.html >>> >>> can you tell me where to find it ? >>> my version is 2.6.2 >>> >> I believe the new turtle module should be installed as standard on 2.6. >> So the example code should just work. >> >> Which OS are you on? Some Linux versions of Python don't have Tkinter loaded >> and that will probably prevent turtle from running... >> What happens when you try it? Do you get an error message? >> > the os is Xp; > the problem is simply i cannot find this directory in my current > python installation folder ... > If you want only to download the demos (including the demoViewer) you can do it from here: http://svn.python.org/view/python/trunk/Demo/turtle/ or if you use Python 3.1 from here (with two additional examples): http://svn.python.org/view/python/branches/py3k/Demo/turtle/ The turtle module in Python 3.1 has a few enhancements (see docs) and also two bugfixes. Regards, Gregor > >> -- >> > > > > From srilyk at gmail.com Wed Jul 22 23:49:58 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 22 Jul 2009 16:49:58 -0500 Subject: [Tutor] Bouncing mail In-Reply-To: References: <4bcde3e10907220738j775d2784v7087b8e121ce0c63@mail.gmail.com> <4bcde3e10907221141w4e46a497n43fce1e412fccaa7@mail.gmail.com> <4A6763B2.3040905@ieee.org> <200907221909.n6MJ98Tn013309@tlgmlp01.teamlog.com> <4A67675E.5010100@ieee.org> Message-ID: <333efb450907221449n7e8b0dbcid056ab56159c487e@mail.gmail.com> On Wed, Jul 22, 2009 at 3:33 PM, Sander Sweers wrote: > 2009/7/22 Dave Angel : > > Anyone else seeing these? > > Unfortunately yes. Very annoying... :( Yep, and not the only ones I've seen -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jul 23 01:11:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jul 2009 00:11:57 +0100 Subject: [Tutor] xlwt & xlrd: can I refactor this code better? References: <4A67675E.5010100@ieee.org> <594157.27832.qm@web110708.mail.gq1.yahoo.com> Message-ID: "Albert-Jan Roskam" wrote > Most functions have many arguments - isn't that called 'tight coupling'? No. In fact too few parameters (arguments are what you pass in, parameters are what you specify in the definition) often wind up relying on global variables to share data - now THAT is tight coupling. > The first function is the main() function. Shouldn't a programmer strive > for information hiding in such a function? Yes but only in terms of the algorithm and local variables. If you genuinely need to pass in values then parameters are the correct mechaniasm. You can sometimes reduce the param count by building more complex data structures but that doesn't look to be the case here. But 6 or so parameters is not excessive. You can increase usability by providing default arguments, but again you have already done that... > it should almost read like regular english, right? > Or is that too textbook-ish? ;-) Its a good objective but don't become a slave to it. You can do a lot with naming, but again you seem to have tried there too. > def merge_xls(in_dir="d:/temp/", out_file="d:/temp/merged_output.xls"): > """ Main function: merge xls sheets """ The doc string should say more about how to use the function. What are each of the inputs and what is the output? What errors are raised under what circumstances? > xls_files = glob.glob(in_dir + "*.xls") > xls_files.sort() > merged_book = xlwt.Workbook() > osheet_names = [os.path.basename(xls_file)[:-4] for xls_file in > xls_files] > for xls_no, xls_file in enumerate(xls_files): > print "---> Processing file %s" % (xls_file) I'm not a fan of print statements inside functions, it reduces their reusability in Web/GUI applications. > def check_xls(book, merged_book, isheet_names, osheet_names, xls_no, > xls_files): > > def write_sheets(book, merged_book, isheet_names, osheet_names, xls_no, > xls_files): > > else: > raise Exception ("ERROR *** File %s has %s sheets (maximum is 99)" > % (xls_file, book.nsheets)) Don't do this! Create a new exception class specific to your functions. This way the client has no alternative but to use try:.... except:.... which will catch all exceptions. Then they must examine the exception data to see what kind they have caught, that's a lot of work for the client just to save you doing class XLSFileError(Exception): pass and raise XLSFileError(....) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jul 23 01:22:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jul 2009 00:22:37 +0100 Subject: [Tutor] how to fill zero value and join two column References: <25661.210.212.36.65.1248285819.squirrel@www.iisermohali.ac.in> Message-ID: wrote > I have two text file, having entries as > fileA > 38 ALA H = 8.29 N = 120.62 CA = 54.33 HA = 4.04 C = 178.95 > 8 ALA H = 7.85 N = 123.95 CA = 54.67 HA = C = > fileB > 8 ALA helix (helix_alpha, helix1) > 21 ALA helix (helix_alpha, helix2) > ... > those atoms which doesnot have nay value in fileA. so the reult will be > something like:- > > fileC > 8 ALA H = 7.85 N = 123.95 CA = 54.67 HA =0.00 C =0.00|8 ALA helix > (helix_alpha, helix1) There is a similar problem discussed a few days ago on tis list, try looking over the archive for this week to get some ideas. > I tried to merge these two files using commands like:- > > from collections import defaultdict >>>> def merge(sources): > ... if __name__ == "__main__": You should not use this inside a function, nor at the >>> prompt. This is used to determine wheher a file should be treated as a module or main program. As it stands the rest of your code will never be executed since the __name__ at the >>> prompt is never __main__ Looks like you need to go back to fundamentals for a spell. > ... a = open("/home/amrita/alachems/chem100.txt") > ... c = open("/home/amrita/secstr/secstr100.txt") > ... def source(stream): > ... return (line.strip() for line in stream) > ... for m in merge([source(x) for x in [a,c]]): > ... print "|".join(c.ljust(10) for c in m) I haven't quite got my head around the logic here but it looks to me like an overly elaborate solution. You could simplify the last for loop to just do for m in merge([source(a),source(c)]) But of course that is a recursive function call to merge() and I can't see any terminating condition so it should loop forever (or until it reaches the recursion limit)... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ldl08 at gmx.net Thu Jul 23 08:05:36 2009 From: ldl08 at gmx.net (David) Date: Thu, 23 Jul 2009 14:05:36 +0800 Subject: [Tutor] mnemonics to better learn Python Message-ID: <4A67FDB0.50502@gmx.net> Dear List, in order to memorize which Python sequences are mutable or immutable, I focused on the SHAPE of the brackets that are associated with each type of sequence. For instance, a *list* is characterised by square brackets, []. My mnemonic device to memorize that lists are mutable is this: "the brackets have sharp edges, they could be trimmed, taking their edges off". The same thing happens with *dictionaries* (which, okay, are not sequences). Anyway, their brackets, {}, have sharp edges, hence they are mutable. *Tuples*, in turn, have perfectly 'round' brackets, (), and these brackets obviously can't be improved upon by taking anything off them. Hence: tuples are immutable. That leaves us with *strings*, which are also not mutable. Here we have no brackets, and this particular mnemonic device breaks down. What I am interested in is finding out whether you use similar techniques, and if so, which ones? How, for examples, do you make sense of all those special characters that make regular expressions powerful? Do you rely on rote learning, or do you employ some other technique? I reckon that if we could come up with some tips and techniques as to how to uncloud the thick information fog that any beginning programmer has to wade through, the very first steps in learning Python could be made more easy. What insights can you share? Curious, David From tmatsumoto at gmx.net Thu Jul 23 08:11:11 2009 From: tmatsumoto at gmx.net (Todd Matsumoto) Date: Thu, 23 Jul 2009 08:11:11 +0200 Subject: [Tutor] Option parser tools Message-ID: <20090723061111.89890@gmx.net> Hello Tutors, I'm building a script that now needs a command line interface. I'm aware of optparse, but I'm wondering if there are any other tools that may be better for building the interface. Cheers, T -- GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 From ctcast at gmail.com Thu Jul 23 05:48:49 2009 From: ctcast at gmail.com (Chris Castillo) Date: Wed, 22 Jul 2009 22:48:49 -0500 Subject: [Tutor] File I/O help Message-ID: <50e459210907222048p18af2924w19361c8033452e7d@mail.gmail.com> *I'm supposed to be reading in names a grades from a text file like so: * Chris 100 89 76 0 Dave 56 45 30 23 10 0 Sara 55 76 78 60 0 *the 0 indicates that's the end of the student's grades and not an actual 0 number grade for the student. This is what my code looks like so far:* from myFunctions import * grades = [] names = [] gradeTotal = 0 numStudents = 0 inputFile = open("input.txt", "r" ) # Read in a file with student names a grades for line in open("input.txt", "r"): # iterate through txt file with names and grades if line.strip().isdigit(): grade = float(line) # convert score into float type gradeTotal += grade # adds score to running total if grade != 0: grade = grades.append(grade) else: name = line.strip() name = names.append(name) # Append name to names list studentTotal = str(len(names)) # Get student total grades.sort() # Sort the grades in ascending order --------------------------------------------------------------------------------------- *and then I need to output something that looks like this:* Name of student 76,89,100 - and then their letter grade average(A, B, C, etc..) Name of student 76,89,100 - and then their letter grade average(A, B, C, etc..) *How do I do this with the code I have so far ( if possible )* -------------- next part -------------- An HTML attachment was scrubbed... URL: From jiangzuoyan at gmail.com Thu Jul 23 09:15:42 2009 From: jiangzuoyan at gmail.com (Changsheng Jiang) Date: Thu, 23 Jul 2009 15:15:42 +0800 Subject: [Tutor] Option parser tools In-Reply-To: <20090723061111.89890@gmx.net> References: <20090723061111.89890@gmx.net> Message-ID: just FYI, A simple, not versatile way, kargs = dict([i.split('=', 1) for i in sys.argv[1:]]) Changsheng Jiang On Thu, Jul 23, 2009 at 14:11, Todd Matsumoto wrote: > Hello Tutors, > > I'm building a script that now needs a command line interface. > > I'm aware of optparse, but I'm wondering if there are any other tools that > may be better for building the interface. > > Cheers, > > T > -- > GRATIS f?r alle GMX-Mitglieder: Die maxdome Movie-FLAT! > Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Thu Jul 23 09:38:59 2009 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 23 Jul 2009 00:38:59 -0700 Subject: [Tutor] File I/O help In-Reply-To: <50e459210907222048p18af2924w19361c8033452e7d@mail.gmail.com> References: <50e459210907222048p18af2924w19361c8033452e7d@mail.gmail.com> Message-ID: <20090723073859.GA48332@dragon.alchemy.com> On Wed, Jul 22, 2009 at 10:48:49PM -0500, Chris Castillo wrote: > *I'm supposed to be reading in names a grades from a text file like so: > * > Chris > 100 > 89 > 76 > 0 My Spidey Senses are picking up "homework assignment", so I'll try to nudge you in a general direction without doing your work for you. > from myFunctions import * I'm curious about this... is this a way for you to organize your code into multiple modules? I'd suggest looking at dividing things up into classes or modules by topic, not just a "dumping ground for a bunch of functions I use often" (which is what I'm guessing here). > inputFile = open("input.txt", "r" ) # Read in a file with student names a > grades > > for line in open("input.txt", "r"): # iterate through txt file with names > and grades You're opening the file twice, which probably isn't what you wanted. > if line.strip().isdigit(): > grade = float(line) # convert score into float type > gradeTotal += grade # adds score to running total > if grade != 0: > grade = grades.append(grade) > else: > name = line.strip() > name = names.append(name) # Append name to names list > > studentTotal = str(len(names)) # Get student total Why do you want to turn the number of students into a string? While you're at it, look at the return value from the append method for lists. What are you accomplishing by assigning that back onto the variables grade and name above? > grades.sort() # Sort the grades in ascending order All the grades? Seems like you need a way to keep track of the grades for each individual student? Maybe some kind of collection object which can store things by name? -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From alan.gauld at btinternet.com Thu Jul 23 10:42:22 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 23 Jul 2009 08:42:22 +0000 (GMT) Subject: [Tutor] xlwt & xlrd: can I refactor this code better? In-Reply-To: <184505.14746.qm@web110710.mail.gq1.yahoo.com> References: <184505.14746.qm@web110710.mail.gq1.yahoo.com> Message-ID: <486909.14043.qm@web86712.mail.ird.yahoo.com> > Btw, I see that you're the author of a Python book. I am using Python for my > work as a researcher. Should, in your opinion, the learning strategy for > somebody like me vis-a-vis somebody who is becoming a professional programmer be > very much different? Not in the early days. The art of programming is basically the same and a good program is a good program. However a professional should study a lot more supplementary material, such as the math theory behind programming (predicate and lambda calculii for example, set theory, graph theory, statistics and geometry are all fundamental programming foundations). Also because professionals typically work on much bigger projects (eg the smallest professional project I've ever done had 6 people producing 50,000 lines of code in over 70 files, the largest was 450 people, 3.5million lines in 10,000 files) they need to better understand the use and value of automated build, test and configuration tools. Finally professionals need to understand how to design programs and systems, they need to learn the indistry standard notations such as UML, ERDs and DFDs etc. They need to know about coupling and cohesion (not just the concepts but how to measure them empirically) as well as things like deadlock, race conditions etc... They need a much deeper understanding of the OS and computer hardware, of networks and comms, and so on. In essence they need to really understand what they are doing rather than just finding something that works - or seems to... This is why professional software engineers have degrees in the subject! So in summary a casual programmer who just needs to build something for their own use (or maybe a few colleagues) doesn't need the breadth or depth of a professional who will be building mission critical (even safety critical - think Space Shuttle!) systems, often used by thousands or even millions of (often untrained) users. Regards, Alan G. From ali.jan at gmail.com Thu Jul 23 14:09:38 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Thu, 23 Jul 2009 18:09:38 +0600 Subject: [Tutor] Mapping of co-ordinates... pygame Message-ID: <8acb5ef80907230509ud2cb36cg99488838f4b7f1b9@mail.gmail.com> Hi, I have some x and y co-ordinates ranging from (-100, 100) for each x and y. Something like this: 100 | | | | -100------------------------------100 | | | | -100 I would like to plot them on a pygame surface. I have found that pygame surface is (0, 0) at top right to (width, height) at the bottom right corner, like this: (0,0) (width, 0) ------------------------------------ | | | | | | | | | | | | | | ------------------------------------ (0,height) (width, height) I need a way to map any value from my range to this surface so I could do stuff like this: pygame.draw.circle(screen, color, (x, y), size Also my range could vary from -5, 5 or -500 to 500 so I need something generic... It looks like a simple problem but I can't seem to be able to figure it out. Thanks, Ali -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jul 23 14:58:46 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 23 Jul 2009 07:58:46 -0500 Subject: [Tutor] Mapping of co-ordinates... pygame In-Reply-To: <8acb5ef80907230509ud2cb36cg99488838f4b7f1b9@mail.gmail.com> References: <8acb5ef80907230509ud2cb36cg99488838f4b7f1b9@mail.gmail.com> Message-ID: <333efb450907230558i41e4bc63x1433c546b00249c8@mail.gmail.com> On Thu, Jul 23, 2009 at 7:09 AM, Muhammad Ali wrote: > Hi, > > I have some x and y co-ordinates ranging from (-100, 100) for each x and y. > Something like this: > > 100 > | > | > | > | > -100------------------------------100 > | > | > | > | > -100 > > I would like to plot them on a pygame surface. > I have found that pygame surface is (0, 0) at top right to (width, height) > at the bottom right corner, like this: > > (0,0) (width, 0) > ------------------------------------ > | | > | | > | | > | | > | | > | | > | | > ------------------------------------ > (0,height) (width, height) > > > I need a way to map any value from my range to this surface so I could do > stuff like this: > pygame.draw.circle(screen, color, (x, y), size > > Also my range could vary from -5, 5 or -500 to 500 so I need something > generic... > > It looks like a simple problem but I can't seem to be able to figure it > out. Well, first off you'll need to know what your window size is. I presume you're defining the size and you're defining a 1:1 ratio (400x400, or 600x600 or some such)? If so, then all you need to do is scale your x, y down and then offset your imaginary grid to the middle. I don't know any of the pygame methods, but here's what it might look like: def draw_pixel(x, y): w = screen.get_width() h = screen.get_height() screen.draw_pixel(w/2+x, h/2+y) That should give you what you need. It starts right in the middle of the screen (w/2, h/2) then will add your values of x and y. If you have a screen of 400x400, and x, y of -20, 20 you'll have 200 + (-20) = 180 and 200 + 20 = 220. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From fiberfolly at gmail.com Thu Jul 23 17:44:17 2009 From: fiberfolly at gmail.com (fiberfolly) Date: Thu, 23 Jul 2009 08:44:17 -0700 (Pacific Daylight Time) Subject: [Tutor] Question from a newbie (thank you) References: <4A660507.00000E.03852@FIBERFOLLY-PC> <200907220712.38553.jfabiani@yolo.com> Message-ID: <4A688551.000003.03816@FIBERFOLLY-PC> WoW! You all have given me lots to look at, think about, and play with. Thank you one and all for your answers! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 1458 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 5769 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 1189 bytes Desc: not available URL: From ldl08 at gmx.net Thu Jul 23 17:49:27 2009 From: ldl08 at gmx.net (David) Date: Thu, 23 Jul 2009 23:49:27 +0800 Subject: [Tutor] Pygame In-Reply-To: References: Message-ID: <4A688687.7050407@gmx.net> Hi, there also is: "Invent Your Own Computer Games with Python", which apparently does not use pygame (like Dawson). http://pythonbook.coffeeghost.net/ I can't comment on the quality. David Mazhar Hussain wrote: > Hello All! My name is Mazhar Hussain, and I am new to python, in > fact, I am new to programming as a whole. I dont know if its the right > list to talk about this. > I am really interested in 2d games, especially 2d games. I am also > interested in making games. I searched for a lot of programming > languages but I didnt like anyone of them, either they were too hard > to learn or not suitable to make games. But then I found Python. I had > heard that it was very easy to learn and great for making games, it > also had a binding for SDL called pygame. But the main games I want to > create are: a pokemon clone, a megaman battle network clone and a > world of goo like game. I just want to know if I can make these type > of games with pygame(before learning python). If it can then I'll > start learning python right away but if it cant then I think I may > better find another language. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From davidwilson at Safe-mail.net Thu Jul 23 17:55:11 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Thu, 23 Jul 2009 11:55:11 -0400 Subject: [Tutor] dictionaries help Message-ID: hello, please excuse me, but i would like to understand how dictionaris work. for example: >>> my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', 'name': 'b name'}] >>> my_code = 'aaa' from the above i would like to compare my_code and return the dictionary which has code == my_code dave From vinces1979 at gmail.com Thu Jul 23 18:46:09 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 23 Jul 2009 10:46:09 -0600 Subject: [Tutor] dictionaries help In-Reply-To: References: Message-ID: <1e53c510907230946h211c0fedxd0ebe26e47ffe24f@mail.gmail.com> this should work def find_value(value, lst): for obj in lst: if value in obj.values(): return obj >> find_value("aaa", my_lst) Vince On Thu, Jul 23, 2009 at 9:55 AM, wrote: > hello, > please excuse me, but i would like to understand how dictionaris work. > > for example: > >>> my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', 'name': 'b > name'}] > >>> my_code = 'aaa' > > > from the above i would like to compare my_code and return the dictionary > which has code == my_code > > dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jul 23 18:51:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jul 2009 17:51:59 +0100 Subject: [Tutor] Mapping of co-ordinates... pygame References: <8acb5ef80907230509ud2cb36cg99488838f4b7f1b9@mail.gmail.com> <333efb450907230558i41e4bc63x1433c546b00249c8@mail.gmail.com> Message-ID: "Wayne" wrote > def draw_pixel(x, y): > w = screen.get_width() > h = screen.get_height() > screen.draw_pixel(w/2+x, h/2+y) I think that should be h/2-y for the coordinates given? Alan G. From alan.gauld at btinternet.com Thu Jul 23 19:01:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jul 2009 18:01:39 +0100 Subject: [Tutor] dictionaries help References: Message-ID: wrote > i would like to understand how dictionaries work. They work like a lookup table. You provide a key and lookup the corresponding value in the dictionary. So to implement a traditional language dictionary the keys would be words and the values would be a list of definitions. You read them by placing the key in square brackets, or by using the get() method: > for example: >>>> my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', 'name': >>>> 'b name'}] my_lst[0]['code'] -> 'aaa' my_lst[0].get('code', 0) -> 'aaa' or 0 if 'aaa' does not exist as a key You can write to them using the [] notation too: my_lst[0]['name'] = 'A new name' changes the value for name in the first dictionary. >>>> my_code = 'aaa' > from the above i would like to compare my_code and return the > dictionary which has code == my_code Vince has shown you one way, this is another way: def findDict(value, dictList): for dct in dictList: if dct.get('code', '') == my_code return dct HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Jul 23 19:04:23 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Jul 2009 18:04:23 +0100 Subject: [Tutor] dictionaries help Message-ID: "Alan Gauld" wrote Oops! Should be: > def findDict(value, dictList): > for dct in dictList: > if dct.get('code', '') == my_code if dct.get('code', '') == value > return dct > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > From rabidpoobear at gmail.com Thu Jul 23 19:11:36 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 23 Jul 2009 12:11:36 -0500 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: <4A67FDB0.50502@gmx.net> References: <4A67FDB0.50502@gmx.net> Message-ID: I approach these things more along the lines of objects rather than looking at the raw source code to remember what I'm doing.For example, I see (x, y, z) and I think "ah, it's a little pre-packaged goodie of delicious variables" and when I see [x, y, z] I think "ah, it's a box with some candy at the bottom, but there's plenty of room for me to put more. I'm guessing all the candy is interrelated somehow because people usually keep things that are similar in the same container" and for dictionaries I think "hey, it's just a list that's indexed with anything you want, instead of only integers." I wouldn't call it "rote learning" because that would be more along the lines of x = {"hello": 1} # dictionary with a string as key and an integer as valuex = {1: "hello"} # dictionary with an integer as key and a string as value x = {1: 1} # dictionary with an integer as key and value x = {"hello": "hello"} # dictionary with a string as key and value .... etc. I.E. I'm not forcing myself to learn every possibility. I learn what "mutability" is and then I learn what dictionaries are, and then I understand how to use them. I don't need mnemonics to remember them. I guess my point is that I see syntax more as a means for defining a specific behavior I want, rather than as an actual representation of the behavior. Like, I think "I need a dictionary here. Oh, that's the {} thing, right?" rather than "Oh, there needs to be {} here, I think. Oh yeah, that's called a dictionary" so it doesn't really help to relate syntax to actual behavior. I think of things on the conceptual level and translate down to Python when I need to tell the computer how to do it. And when I read Python code, I translate it up to conceptual level as well. I don't see "series = form.getvalue('series').strip()" and think "okay, there's an object called "form". it has a method called "getvalue" and it's getting passed "series". Then the return value is being stripped of whitespace on both ends." I see it and I think "okay, 'series' was passed to the program in a user-submitted form and now it's stored in a local variable so I can manipulate it." On Thu, Jul 23, 2009 at 1:05 AM, David wrote: > Dear List, > > in order to memorize which Python sequences are mutable or immutable, I > focused on the SHAPE of the brackets that are associated with each type > of sequence. > > For instance, a *list* is characterised by square brackets, []. > My mnemonic device to memorize that lists are mutable is this: "the > brackets have sharp edges, they could be trimmed, taking their edges off". > > The same thing happens with *dictionaries* (which, okay, are not > sequences). Anyway, their brackets, {}, have sharp edges, hence they are > mutable. > > *Tuples*, in turn, have perfectly 'round' brackets, (), and these > brackets obviously can't be improved upon by taking anything off them. > Hence: tuples are immutable. > > That leaves us with *strings*, which are also not mutable. Here we have > no brackets, and this particular mnemonic device breaks down. > > What I am interested in is finding out whether you use similar > techniques, and if so, which ones? How, for examples, do you make sense > of all those special characters that make regular expressions powerful? > Do you rely on rote learning, or do you employ some other technique? > > I reckon that if we could come up with some tips and techniques as to > how to uncloud the thick information fog that any beginning programmer > has to wade through, the very first steps in learning Python could be > made more easy. > > What insights can you share? > > Curious, > > David > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjhynes36 at hotmail.com Thu Jul 23 19:53:21 2009 From: cjhynes36 at hotmail.com (chris Hynes) Date: Thu, 23 Jul 2009 17:53:21 +0000 Subject: [Tutor] reading data In-Reply-To: References: Message-ID: I have a data file in which the first line is made up of words. Here is the original data file: #Column density-scaled with production rate 3.16227766016838e+25 -10.0000 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 -9.9000 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 I'd like to my program to skip any lines that begin with words and move on to lines that contain numbers. Right now I just cheat and delete the first line and resave the data file, but I was hoping that I could avoid these types of things in the future. Here is my code for reading the file and figuring out how many rows and columns to dimensionalize my array, then I read the data into the array: from numpy import * row=0 columnindex=0 x=open('halfmethanol.col','rt') for line in x.readlines(): data=line.split() columnindex=len(data) row=row+1 temp=ones((row,columnindex)) row=0 x=open('halfmethanol.col','rt') for line in x.readlines(): data=line.split() for column in range(columnindex): temp[row,column]=data[column] row=row+1 _________________________________________________________________ Windows Live? SkyDrive?: Store, access, and share your photos. See how. http://windowslive.com/Online/SkyDrive?ocid=TXT_TAGLM_WL_CS_SD_photos_072009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Thu Jul 23 21:24:28 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 23 Jul 2009 15:24:28 -0400 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: <4A67FDB0.50502@gmx.net> References: <4A67FDB0.50502@gmx.net> Message-ID: > Date: Thu, 23 Jul 2009 14:05:36 +0800 > From: ldl08 at gmx.net > To: Tutor at python.org > Subject: [Tutor] mnemonics to better learn Python > > Dear List, > > in order to memorize which Python sequences are mutable or immutable, I > focused on the SHAPE of the brackets that are associated with each type > of sequence. > > For instance, a *list* is characterised by square brackets, []. > My mnemonic device to memorize that lists are mutable is this: "the > brackets have sharp edges, they could be trimmed, taking their edges off". > > The same thing happens with *dictionaries* (which, okay, are not > sequences). Anyway, their brackets, {}, have sharp edges, hence they are > mutable. > > *Tuples*, in turn, have perfectly 'round' brackets, (), and these > brackets obviously can't be improved upon by taking anything off them. > Hence: tuples are immutable. > > That leaves us with *strings*, which are also not mutable. Here we have > no brackets, and this particular mnemonic device breaks down. > > What I am interested in is finding out whether you use similar > techniques, and if so, which ones? How, for examples, do you make sense > of all those special characters that make regular expressions powerful? > Do you rely on rote learning, or do you employ some other technique? > > I reckon that if we could come up with some tips and techniques as to > how to uncloud the thick information fog that any beginning programmer > has to wade through, the very first steps in learning Python could be > made more easy. > > What insights can you share? I am all for mnemonics and have used them to good effect in learning and teaching; students' abilities to memorize large lists of biological terms and such are greatly increased this way. But so far it hadn't occurred to me to apply mnemonics to learning Python. This is because I have seen learning Python as less about memorizing content and more about understanding concepts. Others may see it differently, but that is how it has seemed to me. Compared to biology, where words are based on Greek or Latin (e.g. "postzygopophysis"), and there may be many such odd terms per topic, Python is mostly based in simple English words like random, string, open, etc. What was harder, coming from a cold start, was how to use the language, "grokking" things like self, list comprehensions, namespaces, = vs ==, Boolean stuff, exceptions, lambdas, decorators, etc. Also, importantly, I tend to have ready access to the web to look things up if I forget them, like whether it is .split() or .join() that I want to use. But your idea to mnemonicize some of your learning could no doubt be helpful to speed you along, since looking things up does slow one down (and can derail one's thought stream as one is trying to figure out why the program is not working as expected). _________________________________________________________________ Windows Live? SkyDrive?: Store, access, and share your photos. See how. http://windowslive.com/Online/SkyDrive?ocid=TXT_TAGLM_WL_CS_SD_photos_072009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Thu Jul 23 22:59:01 2009 From: norman at khine.net (Norman Khine) Date: Thu, 23 Jul 2009 21:59:01 +0100 Subject: [Tutor] dictionaries help In-Reply-To: References: Message-ID: <9c2c8ffb0907231359p2216d009x885bc78a947d8c06@mail.gmail.com> Also you can use list comprehension In [1]: my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', 'name': 'b name'}] In [2]: my_code = 'aaa' In [3]: print [d for d in my_lst if d['code'] == my_code] ------> print([d for d in my_lst if d['code'] == my_code]) [{'code': 'aaa', 'name': 'a name'}] In [4]: On Thu, Jul 23, 2009 at 6:04 PM, Alan Gauld wrote: > > "Alan Gauld" wrote > Oops! > Should be: > >> def findDict(value, dictList): >> ?for dct in dictList: >> ? ? ?if dct.get('code', '') == my_code > > ? ? ? ?if dct.get('code', '') == value > >> ? ? ? ? return dct > > >> HTH, >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From davidwilson at Safe-mail.net Fri Jul 24 00:14:01 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Thu, 23 Jul 2009 18:14:01 -0400 Subject: [Tutor] dictionaries help Message-ID: thank you for all your answers -------- Original Message -------- From: Norman Khine Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org To: tutor at python.org Subject: Re: [Tutor] dictionaries help Date: Thu, 23 Jul 2009 21:59:01 +0100 > Also you can use list comprehension > > In [1]: my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', > 'name': 'b name'}] > > In [2]: my_code = 'aaa' > > In [3]: print [d for d in my_lst if d['code'] == my_code] > ------> print([d for d in my_lst if d['code'] == my_code]) > [{'code': 'aaa', 'name': 'a name'}] > > In [4]: > > > On Thu, Jul 23, 2009 at 6:04 PM, Alan Gauld wrote: > > > > "Alan Gauld" wrote > > Oops! > > Should be: > > > >> def findDict(value, dictList): > >> ?for dct in dictList: > >> ? ? ?if dct.get('code', '') == my_code > > > > ? ? ? ?if dct.get('code', '') == value > > > >> ? ? ? ? return dct > > > > > >> HTH, > >> > >> > >> -- > >> Alan Gauld > >> Author of the Learn to Program web site > >> http://www.alan-g.me.uk/ > > > > _______________________________________________ > > Tutor maillist ?- ?Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From Joel.Levine at Dartmouth.EDU Fri Jul 24 00:50:57 2009 From: Joel.Levine at Dartmouth.EDU (Joel Levine) Date: 23 Jul 2009 18:50:57 -0400 Subject: [Tutor] Mapping of co-ordinates... pygame Message-ID: <129465344@newdancer.Dartmouth.EDU> A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 601 bytes Desc: not available URL: From davidwilson at Safe-mail.net Fri Jul 24 01:09:55 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Thu, 23 Jul 2009 19:09:55 -0400 Subject: [Tutor] dictionaries help Message-ID: Hello again, Here is my full attempt, can you please tell me if it is OK and if there should be any improvements >>> ws_industry = ('it', 'science') >>> code = ws_industry[0] >>> active = [] >>> industries = [{'code': 'it', 'name': 'Information Technology'}, {'code': 'science', 'name': 'Science'}, {'code': 'biology', 'name': 'Biology'}] >>> for industry in industries: if industry['code'] in ws_industry: active.append({ 'code': industry['code'], 'name': industry['name'], 'isdefault': code == industry['code']}) >>># Not active industry >>> not_active = [x for x in industries if x['code'] not in ws_industry ] >>>not_active.sort(lambda x, y: cmp(x['name'], y['name'])) >>> return [active, non-active] Line [6] i was not too sure if it could be written better or more efficient. Basically I have a big list of industries and I want to verify for each member whether they are active or not active. The industry list of dictionaries will stay fixed at about 25 items, whereas the ws_industry tuple will change depending. I have to go through about 20,000 items. -------- Original Message -------- From: davidwilson at Safe-mail.net Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org To: tutor at python.org Subject: Re: [Tutor] dictionaries help Date: Thu, 23 Jul 2009 18:14:01 -0400 > thank you for all your answers > > > -------- Original Message -------- > From: Norman Khine > Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org > To: tutor at python.org > Subject: Re: [Tutor] dictionaries help > Date: Thu, 23 Jul 2009 21:59:01 +0100 > > > Also you can use list comprehension > > > > In [1]: my_lst = [{'code': 'aaa', 'name': 'a name'}, {'code': 'bbb', > > 'name': 'b name'}] > > > > In [2]: my_code = 'aaa' > > > > In [3]: print [d for d in my_lst if d['code'] == my_code] > > ------> print([d for d in my_lst if d['code'] == my_code]) > > [{'code': 'aaa', 'name': 'a name'}] > > > > In [4]: > > > > > > On Thu, Jul 23, 2009 at 6:04 PM, Alan Gauld wrote: > > > > > > "Alan Gauld" wrote > > > Oops! > > > Should be: > > > > > >> def findDict(value, dictList): > > >> ?for dct in dictList: > > >> ? ? ?if dct.get('code', '') == my_code > > > > > > ? ? ? ?if dct.get('code', '') == value > > > > > >> ? ? ? ? return dct > > > > > > > > >> HTH, > > >> > > >> > > >> -- > > >> Alan Gauld > > >> Author of the Learn to Program web site > > >> http://www.alan-g.me.uk/ > > > > > > _______________________________________________ > > > Tutor maillist ?- ?Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Fri Jul 24 01:13:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Jul 2009 00:13:13 +0100 Subject: [Tutor] reading data References: Message-ID: "chris Hynes" wrote Its not a good idea to start a new thread by replying to an existing one. Threaded newsreaders or mailing tools will still see it as part of the old thread and bored readers may not notice the new subject... However.... > have a data file in which the first line is made up of words. Here is the > original data file: > > #Column density-scaled with production rate 3.16227766016838e+25 > -10.0000 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 0.000e+00 > ... > I'd like to my program to skip any lines that begin with words > and move on to lines that contain numbers. We've had a few requests very similar to this over the last couple of weeks. the isdigit() method of strings may well help here. ---------------------- from numpy import * row=0 columnindex=0 x=open('halfmethanol.col','rt') for line in x.readlines(): data=line.split() columnindex=len(data) row=row+1 The row line does nothing and can be deleted. But it looks like a hard wayto find the length of the last line. Is that really what you want? If so you could gather the data wjile you are at it: data = [line.split() for line in x.readlines()] columnindex = len(x[-1]) Then the next loop can be over x rather than rereading the file and splitting the lines again. And if you use enumerate you can miss out the incrementing here too: temp=ones((row,columnindex)) for row, line in enumerate(x): for column in range(columnindex): temp[row,column]=data[column] However I'm still not totally clear what you are achieving with this? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From asweigart at gmail.com Fri Jul 24 02:25:41 2009 From: asweigart at gmail.com (Albert Sweigart) Date: Thu, 23 Jul 2009 17:25:41 -0700 Subject: [Tutor] Pygame Message-ID: <716dd5b60907231725k20f15c40l53b300dc2a81232f@mail.gmail.com> Hi, I'm Al, the author of Invent Your Own Computer Games with Python. The book does indeed cover Pygame. The last four chapters covers the Pygame library, and the final one has the source code for a complete game. I still recommend learning Python first though, it will make it much easier to understand the code. The book can do this for you and is freely available at http://pythonbook.coffeeghost.net -Al From kent37 at tds.net Fri Jul 24 03:44:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Jul 2009 21:44:33 -0400 Subject: [Tutor] dictionaries help In-Reply-To: References: Message-ID: <1c2a2c590907231844i6eba2589k58f1373292c91939@mail.gmail.com> On Thu, Jul 23, 2009 at 7:09 PM, wrote: > Hello again, > Here is my full attempt, can you please tell me if it is OK and if there should be any improvements > >>>> ? ? ws_industry = ('it', 'science') >>>> code = ws_industry[0] >>>> active = [] >>>> industries = [{'code': 'it', 'name': 'Information Technology'}, {'code': 'science', 'name': 'Science'}, {'code': 'biology', 'name': 'Biology'}] >>>> for industry in industries: > ? ? ? ? ? ?if industry['code'] in ws_industry: > ? ? ? ? ? ? ? ?active.append({ > ? ? ? ? ? ? ? ? ? ?'code': industry['code'], > ? ? ? ? ? ? ? ? ? ?'name': industry['name'], > ? ? ? ? ? ? ? ? ? ?'isdefault': code == industry['code']}) > >>>># Not active industry >>>> not_active = [x for x in industries if x['code'] not in ws_industry ] >>>>not_active.sort(lambda x, y: cmp(x['name'], y['name'])) >>>> return [active, non-active] > > Line [6] i was not too sure if it could be written better or more efficient. > > Basically I have a big list of industries and I want to verify for each member whether they are active or not active. > > The industry list of dictionaries will stay fixed at about 25 items, whereas the ws_industry tuple will change depending. I have to go through about 20,000 items. If ws_industry contains 25 items, it will probably be faster to search it if it is a set rather than a list. Just use ws_industry = set(('it', 'science')) Which part of the problem has 20,000 items? Kent From ali.jan at gmail.com Fri Jul 24 07:08:50 2009 From: ali.jan at gmail.com (Muhammad Ali) Date: Fri, 24 Jul 2009 11:08:50 +0600 Subject: [Tutor] Mapping of co-ordinates... pygame In-Reply-To: <129465344@newdancer.Dartmouth.EDU> References: <129465344@newdancer.Dartmouth.EDU> Message-ID: <8acb5ef80907232208p2e5e49dfya1d1bb47303012ec@mail.gmail.com> Thanks Wayne and Alan, Here is what I finally ended up with: def newCoord(x, y, oldWidth, oldHeight, newWidth, newHeight): return( newWidth/2 + newWidth/oldWidth * x), (newHeight/2 - newHeight/oldHeight * y) for my earlier example, the old width and height would be 200, 200 respectively. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From amrita at iisermohali.ac.in Fri Jul 24 07:49:31 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Fri, 24 Jul 2009 11:19:31 +0530 (IST) Subject: [Tutor] how to get blank value Message-ID: <2111.210.212.36.65.1248414571.squirrel@www.iisermohali.ac.in> Hi, I have a file having lines:- 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 104 ALA H = 7.70 N = CA = HA = 4.21 C = 85 ALA H = 8.60 N = CA = HA = 4.65 C = Now i want to make two another file in which i want to put those lines for which C is missing and another one for which N,CA and C all are missing, I tried in this way: import re expr = re.compile("C = None") f = open("helix.dat") for line in f: if expr.search(line): print line but i am not getting the desired output. Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From davidwilson at Safe-mail.net Fri Jul 24 09:01:43 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Fri, 24 Jul 2009 03:01:43 -0400 Subject: [Tutor] dictionaries help Message-ID: Hello -------- Original Message -------- From: Kent Johnson Apparently from: kent3737 at gmail.com To: davidwilson at safe-mail.net Cc: tutor at python.org Subject: Re: [Tutor] dictionaries help Date: Thu, 23 Jul 2009 21:44:33 -0400 > On Thu, Jul 23, 2009 at 7:09 PM, wrote: > > Hello again, > > Here is my full attempt, can you please tell me if it is OK and if there should be any improvements > > > >>>> ? ? ws_industry = ('it', 'science') > >>>> code = ws_industry[0] > >>>> active = [] > >>>> industries = [{'code': 'it', 'name': 'Information Technology'}, {'code': 'science', 'name': 'Science'}, {'code': 'biology', 'name': 'Biology'}] > >>>> for industry in industries: > > ? ? ? ? ? ?if industry['code'] in ws_industry: > > ? ? ? ? ? ? ? ?active.append({ > > ? ? ? ? ? ? ? ? ? ?'code': industry['code'], > > ? ? ? ? ? ? ? ? ? ?'name': industry['name'], > > ? ? ? ? ? ? ? ? ? ?'isdefault': code == industry['code']}) > > > >>>># Not active industry > >>>> not_active = [x for x in industries if x['code'] not in ws_industry ] > >>>>not_active.sort(lambda x, y: cmp(x['name'], y['name'])) > >>>> return [active, non-active] > > > > Line [6] i was not too sure if it could be written better or more efficient. > > > > Basically I have a big list of industries and I want to verify for each member whether they are active or not active. > > > > The industry list of dictionaries will stay fixed at about 25 items, whereas the ws_industry tuple will change depending. I have to go through about 20,000 items. > > If ws_industry contains 25 items, it will probably be faster to search > it if it is a set rather than a list. Just use > ws_industry = set(('it', 'science')) ws_industry contains only unique values > > Which part of the problem has 20,000 items? the 20,000 items are the number of times the programme will have to loop to extract this information. so i have 25 industries, i also have 20,000 text files which contain the ws_industry values therefore i would like to extract from each file the number of active industries and number of inactive industries. i suppose in a relational db i will have something like: [file] 1 - n [ws-industry] n - n [industry] hope this make sense ;) > > Kent From alan.gauld at btinternet.com Fri Jul 24 10:26:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Jul 2009 09:26:51 +0100 Subject: [Tutor] how to get blank value References: <2111.210.212.36.65.1248414571.squirrel@www.iisermohali.ac.in> Message-ID: wrote > 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > 104 ALA H = 7.70 N = CA = HA = 4.21 C = > > Now i want to make two another file in which i want to put those lines > for > which C is missing and another one for which N,CA and C all are missing, > > I tried in this way: > import re > expr = re.compile("C = None") This will search for the literal string 'C = None' which does not exist in your sdata. You need to search for 'C = 'at the end of the line (assuming it is always there. Otherwise you need to search for 'C = ' followed by a non number.) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jul 24 11:08:54 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 24 Jul 2009 09:08:54 +0000 (GMT) Subject: [Tutor] how to get blank value In-Reply-To: <13468.210.212.36.65.1248425845.squirrel@www.iisermohali.ac.in> References: <2111.210.212.36.65.1248414571.squirrel@www.iisermohali.ac.in> <13468.210.212.36.65.1248425845.squirrel@www.iisermohali.ac.in> Message-ID: <557522.50433.qm@web86701.mail.ird.yahoo.com> Please use Reply All to send it to the list as well. > I am trying it in this way also:--- > > import re > expr = re.compile("C") This will find all lines with the letter C in them. Which from your data is all of them. Look at the regex documentation to see how to represent the end of a line (or, slightly more complex, a non digit). > f = open('chem.txt') > for line in f: > expr.search(line) > if 'C = ' This is invalid Python, the second level of indentation should produce an error! Also you are not doing anything with the result of your search, you just throw it away. You need something like for line in open('chem.txt'): if expr.search(line): print line HTH, Alan g. > > wrote > > > >> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > >> 104 ALA H = 7.70 N = CA = HA = 4.21 C = > >> > >> Now i want to make two another file in which i want to put those lines > >> for > >> which C is missing and another one for which N,CA and C all are missing, > >> > >> I tried in this way: > >> import re > >> expr = re.compile("C = None") > > > > This will search for the literal string 'C = None' which does not exist in > > your sdata. > > You need to search for 'C = 'at the end of the line (assuming it is always > > there. > > Otherwise you need to search for 'C = ' followed by a non number.) > > > > HTH, > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA From amrita at iisermohali.ac.in Fri Jul 24 11:18:19 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Fri, 24 Jul 2009 14:48:19 +0530 (IST) Subject: [Tutor] how to get blank value In-Reply-To: <557522.50433.qm@web86701.mail.ird.yahoo.com> References: <2111.210.212.36.65.1248414571.squirrel@www.iisermohali.ac.in> <13468.210.212.36.65.1248425845.squirrel@www.iisermohali.ac.in> <557522.50433.qm@web86701.mail.ird.yahoo.com> Message-ID: <17095.210.212.36.65.1248427099.squirrel@www.iisermohali.ac.in> > What is the python command for searching blank value of a parameter? > Please use Reply All to send it to the list as well. > > >> I am trying it in this way also:--- >> >> import re >> expr = re.compile("C") > > This will find all lines with the letter C in them. > Which from your data is all of them. Look at the regex documentation > to see how to represent the end of a line (or, slightly more complex, a > non digit). > >> f = open('chem.txt') >> for line in f: >> expr.search(line) >> if 'C = ' > > > This is invalid Python, the second level of indentation should produce an > error! > Also you are not doing anything with the result of your search, you just > throw > it away. > > You need something like > > for line in open('chem.txt'): > if expr.search(line): > print line > > > HTH, > > Alan g. > >> > wrote >> > >> >> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 >> >> 104 ALA H = 7.70 N = CA = HA = 4.21 C = >> >> >> >> Now i want to make two another file in which i want to put those >> lines >> >> for >> >> which C is missing and another one for which N,CA and C all are >> missing, >> >> >> >> I tried in this way: >> >> import re >> >> expr = re.compile("C = None") >> > >> > This will search for the literal string 'C = None' which does not >> exist in >> > your sdata. >> > You need to search for 'C = 'at the end of the line (assuming it is >> always >> > there. >> > Otherwise you need to search for 'C = ' followed by a non number.) >> > >> > HTH, >> > >> > -- >> > Alan Gauld >> > Author of the Learn to Program web site >> > http://www.alan-g.me.uk/ >> > >> > >> > _______________________________________________ >> > Tutor maillist - Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> >> >> Amrita Kumari >> Research Fellow >> IISER Mohali >> Chandigarh >> INDIA > > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From rabidpoobear at gmail.com Fri Jul 24 12:41:41 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 24 Jul 2009 05:41:41 -0500 Subject: [Tutor] how to get blank value In-Reply-To: <17095.210.212.36.65.1248427099.squirrel@www.iisermohali.ac.in> References: <2111.210.212.36.65.1248414571.squirrel@www.iisermohali.ac.in> <13468.210.212.36.65.1248425845.squirrel@www.iisermohali.ac.in> <557522.50433.qm@web86701.mail.ird.yahoo.com> <17095.210.212.36.65.1248427099.squirrel@www.iisermohali.ac.in> Message-ID: You will probably continue to get unsatisfactory responses if you continue to ask unsatisfactory questions.Python won't automatically parse this document in exactly the way you want it to. You're on the right track but you need to do as Alan said and actually read the regex articles to understand how they work. On Fri, Jul 24, 2009 at 4:18 AM, wrote: > > > What is the python command for searching blank value of a parameter? > > > Please use Reply All to send it to the list as well. > > > > > >> I am trying it in this way also:--- > >> > >> import re > >> expr = re.compile("C") > > > > This will find all lines with the letter C in them. > > Which from your data is all of them. Look at the regex documentation > > to see how to represent the end of a line (or, slightly more complex, a > > non digit). > > > >> f = open('chem.txt') > >> for line in f: > >> expr.search(line) > >> if 'C = ' > > > > > > This is invalid Python, the second level of indentation should produce an > > error! > > Also you are not doing anything with the result of your search, you just > > throw > > it away. > > > > You need something like > > > > for line in open('chem.txt'): > > if expr.search(line): > > print line > > > > > > HTH, > > > > Alan g. > > > >> > wrote > >> > > >> >> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > >> >> 104 ALA H = 7.70 N = CA = HA = 4.21 C = > >> >> > >> >> Now i want to make two another file in which i want to put those > >> lines > >> >> for > >> >> which C is missing and another one for which N,CA and C all are > >> missing, > >> >> > >> >> I tried in this way: > >> >> import re > >> >> expr = re.compile("C = None") > >> > > >> > This will search for the literal string 'C = None' which does not > >> exist in > >> > your sdata. > >> > You need to search for 'C = 'at the end of the line (assuming it is > >> always > >> > there. > >> > Otherwise you need to search for 'C = ' followed by a non number.) > >> > > >> > HTH, > >> > > >> > -- > >> > Alan Gauld > >> > Author of the Learn to Program web site > >> > http://www.alan-g.me.uk/ > >> > > >> > > >> > _______________________________________________ > >> > Tutor maillist - Tutor at python.org > >> > http://mail.python.org/mailman/listinfo/tutor > >> > > >> > >> > >> Amrita Kumari > >> Research Fellow > >> IISER Mohali > >> Chandigarh > >> INDIA > > > > > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Jul 24 14:25:50 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 24 Jul 2009 05:25:50 -0700 (PDT) Subject: [Tutor] how to get blank value In-Reply-To: Message-ID: <507684.83082.qm@web110703.mail.gq1.yahoo.com> Mark Summerfield recently wrote a book called Programming in Python 3 (http://www.qtrac.eu/py3book.html) The chapter on regexes happens to be freely downloadable as a sample chapter: http://ptgmedia.pearsoncmg.com/images/9780137129294/samplepages/0137129297_Sample.pdf I found that chapter (in fact, the entire book!) very helpful. It's on Python 3, but that doesn't matter too much, esp. not in the regex chapter. Cheers!! Albert-Jan From davidwilson at Safe-mail.net Fri Jul 24 16:48:45 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Fri, 24 Jul 2009 10:48:45 -0400 Subject: [Tutor] traversing page and then following the link Message-ID: Hello, I would like to download all the flags from the http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags so that I can create a flags sprite from this. The flags seem to follow some order in that all the svg files are in the following pattern: http://en.wikipedia.org/wiki/File:Flag_of_*.svg and then on this page there is the link of the file. I have looked at using Twill to follow each link and record the actual url, but can somone point me at a simpler solution. Dave From vinces1979 at gmail.com Fri Jul 24 17:23:06 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 24 Jul 2009 09:23:06 -0600 Subject: [Tutor] traversing page and then following the link In-Reply-To: References: Message-ID: <1e53c510907240823g28b0af8ei225b406afb7a5ac1@mail.gmail.com> there are many ways to parse html pages and retrieve data, I tend to use lxml and xpath to simplify things and urllib to pull down the data lxml is not a core library but can be installed via easy_install, the main benefit is the xpath support ===================================================================================== import urllib2 from lxml import html as HTML useragent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.1) Gecko/20090716 Ubuntu/9.04 (jaunty) Shiretoko/3.5.1" opener = urllib2.build_opener() main_page = urllib2.Request(" http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags") main_page.headers["User-Agent"] = useragent #: wikipedia will return a 403 otherwise html = HTML.fromstring(opener.open(main_page).read()) images = html.xpath("//a[@class='image']/img") #: parse all image tags for img in images: url = img.attrib["src"].split("/") url.pop(url.index("thumb")) #: remove reference to thumb folder local = open(url[-2], "wb") #: open local file url = "/".join(url[:-1]) #: cleanup the .png reference print "Downloading %s" % url imgreq = urllib2.Request(url) imgreq.headers["User-Agent"] = useragent local.write(opener.open(imgreq).read()) #: read the remote svg file into local file local.close() ============================================================================================ On Fri, Jul 24, 2009 at 8:48 AM, wrote: > Hello, > I would like to download all the flags from the > http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags so that I > can create a flags sprite from this. > > The flags seem to follow some order in that all the svg files are in the > following pattern: > > http://en.wikipedia.org/wiki/File:Flag_of_*.svg and then on this page > there is the link of the file. > > I have looked at using Twill to follow each link and record the actual url, > but can somone point me at a simpler solution. > > Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sailakshman9 at hotmail.com Fri Jul 24 17:22:15 2009 From: sailakshman9 at hotmail.com (vankayala sailakshman) Date: Fri, 24 Jul 2009 20:52:15 +0530 Subject: [Tutor] Help with multiple substitution Message-ID: Hi All, Help needed to write a python script!!! Iam a python newbie and my problem is doing multiple substitution in a text file using Python regular expressions. Here is my following data, I need to chop of all the extensions that are given in the following list and replace with empty string in their position. I have tried to solve for the past two days but couldn't succeed. Any help would be appreciated. Thanks in advance.Sai.... for example, for ?abc22035.pr.1? i need to get ?abc22035? chopset = ['.p', '.pr', '.prp', '.prpp', '.ps', '.psp', '.pspp', '.s', '.p.1','.pr.1', '.prp.1', '.prpp.1', '.ps.1', '.psp.1','.pspp.1', '.s.1'] abc22035.pr abc22035.pr.1 abc21409 .ps.1 abc21409.pr.1 abc21154 abc21154.pr.1 abc07584_EAOEA abc07584_EAOEA.ps.1 abc20991.pr abc20991.ps. abc21156 abc21156.ps.1 abc21409 abc21409.ps. abc21156 abc21156.pr.1 abc21408 abc21408.ps.1 abc21370.psp abc21370.pr.1 abc21370 abc21370.ps.1 abc22036 abc22036.pr.1 abc21154 abc21154.ps.1 abc22036.prpp abc22036.ps.1 abc20991 abc20991.pr.1 abc21772 abc21772.pr.1 abc21408 abc21408.pr.1 abc07584_EAOEA abc07584_EAOEA.pr.1 abc21065 _________________________________________________________________ Missed any of the IPL matches ? Catch a recap of all the action on MSN Videos http://msnvideos.in/iplt20/msnvideoplayer.aspx -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Jul 24 17:29:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 24 Jul 2009 08:29:27 -0700 Subject: [Tutor] traversing page and then following the link In-Reply-To: References: Message-ID: On 7/24/2009 7:48 AM davidwilson at Safe-mail.net said... > Hello, > I would like to download all the flags from the http://en.wikipedia.org/wiki/Gallery_of_sovereign-state_flags so that I can create a flags sprite from this. > You did -- most of the time when you look at a page the files were copied onto your machine. > The flags seem to follow some order in that all the svg files are in the following pattern: > > http://en.wikipedia.org/wiki/File:Flag_of_*.svg and then on this page there is the link of the file. > > I have looked at using Twill to follow each link and record the actual url, but can somone point me at a simpler solution. Use 'Save As' from the file menu. Select complete web page. Et voila! In python you'd spend a a lot more time getting up to speed on urllib or httplib or Beautiful Soup... Emile From stefan at lsd.co.za Fri Jul 24 17:39:44 2009 From: stefan at lsd.co.za (Stefan Lesicnik) Date: Fri, 24 Jul 2009 17:39:44 +0200 Subject: [Tutor] Reading text until a certain point Message-ID: <5cb309e70907240839q6d87ba0eh757123259b3efaad@mail.gmail.com> Hi Guys, It seems like this keeps coming up (for me anyways), and i'm never sure how to do it. I'm very new to programming... I have a file that has text in a certain format. Lets assume ''' name: stefan id: 12345 color: blue name: joe id: 54321 color: red ''' The format is predictable. I understand for non predictable text, you would have to use pyparser or the like to build a match. For predictable format, I am never sure how to handle this. I normally use something like for line in file: line.split('\n') The problem being i dont really do something per line? I would like to say something like, for line until the next 'name', make that 1 element. So i would like to then have a list or dict (this probably makes sense for a dict) with that group. I would then probably split it into various elements. So essentially im asking, how do i say the for line until next 'match'. Would this be something for the re module? Or is there an inbuilt core way? I hope this makes sense Thanks! Stefan -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Fri Jul 24 17:41:16 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 24 Jul 2009 09:41:16 -0600 Subject: [Tutor] Help with multiple substitution In-Reply-To: References: Message-ID: <1e53c510907240841s874585o23f69fb0d9be354a@mail.gmail.com> not perfect or tested but import re chopset.reverse() #: put the longer extensions first exts = "|".join([re.escape(x) fro x in chopset)]) for line in file: print exts.sub("", line) On Fri, Jul 24, 2009 at 9:22 AM, vankayala sailakshman < sailakshman9 at hotmail.com> wrote: > > Hi All, > > Help needed to write a python script!!! > > Iam a python newbie and my problem is doing multiple substitution in a text > file using Python regular expressions. Here is my following data, I need to > chop of all the extensions that are given in the following list and replace > with empty string in their position. I have tried to solve for the past two > days but couldn't succeed. Any help would be appreciated. Thanks in advance. > > Sai.... > > > for example, for ?abc22035.pr.1? i need to get ?abc22035? > > > chopset = ['.p', '.pr', '.prp', '.prpp', '.ps', '.psp', '.pspp', '.s', > '.p.1','.pr.1', '.prp.1', '.prpp.1', '.ps.1', '.psp.1','.pspp.1', '.s.1'] > > > abc22035.pr > > abc22035.pr.1 abc21409 .ps.1 > > abc21409.pr.1 abc21154 > > abc21154.pr.1 abc07584_EAOEA > > abc07584_EAOEA.ps.1 abc20991.pr > > abc20991.ps. abc21156 > > abc21156.ps.1 abc21409 > > abc21409.ps. abc21156 > > abc21156.pr.1 abc21408 > > abc21408.ps.1 abc21370.psp > > abc21370.pr.1 abc21370 > > abc21370.ps.1 abc22036 > > abc22036.pr.1 abc21154 > > abc21154.ps.1 abc22036.prpp > > abc22036.ps.1 abc20991 > > abc20991.pr.1 abc21772 > > abc21772.pr.1 abc21408 > > abc21408.pr.1 abc07584_EAOEA > > abc07584_EAOEA.pr.1 abc21065 > > > > ------------------------------ > Videos Get the latest video streams on movies, Try it! > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Fri Jul 24 17:51:30 2009 From: vinces1979 at gmail.com (vince spicer) Date: Fri, 24 Jul 2009 09:51:30 -0600 Subject: [Tutor] Reading text until a certain point In-Reply-To: <5cb309e70907240839q6d87ba0eh757123259b3efaad@mail.gmail.com> References: <5cb309e70907240839q6d87ba0eh757123259b3efaad@mail.gmail.com> Message-ID: <1e53c510907240851i6740cf3bw74c7d96e018ec254@mail.gmail.com> you can build a dictionary and keep the active key, again this would only work in predictable data users = {} name = None for line in file: key, value = [x.strip() for x in line.split(":")] if key == "name": name = data[1] users[name] = {} else: users[name][data[0]] >> users {"stefan": { "id":12345 "color":blue }) Vince On Fri, Jul 24, 2009 at 9:39 AM, Stefan Lesicnik wrote: > Hi Guys, > > It seems like this keeps coming up (for me anyways), and i'm never sure how > to do it. I'm very new to programming... > > I have a file that has text in a certain format. Lets assume > > ''' > name: stefan > id: 12345 > color: blue > name: joe > id: 54321 > color: red > ''' > > The format is predictable. I understand for non predictable text, you > would have to use pyparser or the like to build a match. > > For predictable format, I am never sure how to handle this. I normally use > something like > > for line in file: > line.split('\n') > > The problem being i dont really do something per line? I would like to say > something like, for line until the next 'name', make that 1 element. > So i would like to then have a list or dict (this probably makes sense for > a dict) with that group. I would then probably split it into various > elements. > > So essentially im asking, how do i say the for line until next 'match'. > Would this be something for the re module? Or is there an inbuilt core way? > > I hope this makes sense > > Thanks! > > Stefan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Fri Jul 24 17:54:13 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Fri, 24 Jul 2009 11:54:13 -0400 Subject: [Tutor] What kind of number is this Message-ID: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com> Hi Tutors, I have a bunch of text files that have many occurrences like the following which I believe, given the context, are numbers: ١٨٧٢ ٥٧ ٢٠٠٨ etc. So, can somebody please explain what kind of numbers these are, and how I can get the original numbers back. The files are in Arabic and were downloaded from an Arabic website. I'm running python2.6 on Ubuntu 9.04 -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsseabold at gmail.com Fri Jul 24 18:00:27 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Fri, 24 Jul 2009 12:00:27 -0400 Subject: [Tutor] What kind of number is this In-Reply-To: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com> References: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com> Message-ID: 2009/7/24 Emad Nawfal (???? ????) : > Hi Tutors, > I have a bunch of text files that have many occurrences like the following > which I believe, given the context,? are numbers: > > ١٨٧٢ > > ٥٧ > > ?٢٠٠٨ > > etc. > > So, can somebody please explain what kind of numbers these are, and how I > can get the original numbers back. The files are in Arabic and were > downloaded from an Arabic website. > I'm running python2.6 on Ubuntu 9.04 > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > -------------------------------------------------------- > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Googling the first number, they appear to be the HTML encoding of (literally) Arabic numerals (?) ١ http://en.wiktionary.org/wiki/%D9%A1 -Skipper From davea at ieee.org Fri Jul 24 18:20:50 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 24 Jul 2009 12:20:50 -0400 Subject: [Tutor] Reading text until a certain point In-Reply-To: <1e53c510907240851i6740cf3bw74c7d96e018ec254@mail.gmail.com> References: <5cb309e70907240839q6d87ba0eh757123259b3efaad@mail.gmail.com> <1e53c510907240851i6740cf3bw74c7d96e018ec254@mail.gmail.com> Message-ID: <4A69DF62.4090804@ieee.org> vince spicer wrote: > you can build a dictionary and keep the active key, again this would only > work in predictable data > > users = {} > name = None > > for line in file: > key, value = [x.strip() for x in line.split(":")] > if key == "name": > name = data[1] > users[name] = {} > else: > users[name][data[0]] > > >>> users >>> > {"stefan": { > "id":12345 > "color":blue > }) > > Vince > > On Fri, Jul 24, 2009 at 9:39 AM, Stefan Lesicnik wrote: > > >> Hi Guys, >> >> It seems like this keeps coming up (for me anyways), and i'm never sure how >> to do it. I'm very new to programming... >> >> I have a file that has text in a certain format. Lets assume >> >> ''' >> name: stefan >> id: 12345 >> color: blue >> name: joe >> id: 54321 >> color: red >> ''' >> >> The format is predictable. I understand for non predictable text, you >> would have to use pyparser or the like to build a match. >> >> For predictable format, I am never sure how to handle this. I normally use >> something like >> >> for line in file: >> line.split('\n') >> >> The problem being i dont really do something per line? I would like to say >> something like, for line until the next 'name', make that 1 element. >> So i would like to then have a list or dict (this probably makes sense for >> a dict) with that group. I would then probably split it into various >> elements. >> >> So essentially im asking, how do i say the for line until next 'match'. >> Would this be something for the re module? Or is there an inbuilt core way? >> >> I hope this makes sense >> >> Thanks! >> >> Stefan >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > (Don't top-post. It makes it difficult to see the sequence of responses) (untested) users = {} name = None for line in file: key, value = [x.strip() for x in line.split(":")] if key == "name": name = value users[name] = {} else: users[name][key] = value At this point, users is a dictionary keyed by names, and each value is a dictionary, keyed by 'id' and 'color' From bhaaluu at gmail.com Fri Jul 24 19:30:57 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 24 Jul 2009 13:30:57 -0400 Subject: [Tutor] Pygame In-Reply-To: <4A688687.7050407@gmx.net> References: <4A688687.7050407@gmx.net> Message-ID: On Thu, Jul 23, 2009 at 11:49 AM, David wrote: > Hi, > > there also is: > "Invent Your Own Computer Games with Python", which apparently does not > use pygame (like Dawson). > http://pythonbook.coffeeghost.net/ > > I can't comment on the quality. > > David > I have looked through almost half of the PDF version of the book and it is well written with original content. I think that a beginner programmer could use this book as a Python tutorial, especially if they are interested in learning about Python game programming. The online HTML version of the book seems to be more updated, with chapters 12-15 about PyGame. I typed in several of the programs from the PDF book, and they all worked nicely after I fixed MY typos. I made some typical beginner mistakes, such as forgetting punctuation, miss-spelling variable names, and improper indentation. It is always nice to find a programming book that has working source code, especially if the source code is used for the examples. The ZIP archive of source code for the examples can be downloaded, and works very well. The ZIP archive doesn't include the PyGame examples yet, but I was able to copy/paste those from the online book and run them. They work fine. I've already learned several useful new things about Python by reading this book. Many thanks to Albert Sweigart for making it available for free, online at http://pythonbook.coffeeghost.net -- b h a a l u u at g m a i l dot c o m Gnu/Linux IS user-friendly. It's NOT ignorant-friendly or idiot-friendly. From kent37 at tds.net Fri Jul 24 20:40:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jul 2009 14:40:49 -0400 Subject: [Tutor] dictionaries help In-Reply-To: References: Message-ID: <1c2a2c590907241140q53caed59v6ba22c8a53031453@mail.gmail.com> On Fri, Jul 24, 2009 at 3:01 AM, wrote: >> If ws_industry contains 25 items, it will probably be faster to search >> it if it is a set rather than a list. Just use >> ws_industry = set(('it', 'science')) > > ws_industry contains only unique values OK. It will still be faster to check membership if it is a set rather than a list. Checking membership in a list has to search the whole list in order. The time will vary depending on where, and if, the target value is found in the list: kent $ python -m timeit -s "m=map(str, range(25))" "'x' in m" 1000000 loops, best of 3: 0.902 usec per loop kent $ python -m timeit -s "m=map(str, range(25))" "'12' in m" 1000000 loops, best of 3: 0.649 usec per loop kent $ python -m timeit -s "m=map(str, range(25))" "'0' in m" 10000000 loops, best of 3: 0.0801 usec per loop Searching a set takes approximately the same amount of time regardless of the size of the set and whether the target is in the set or not: kent $ python -m timeit -s "m=set(map(str, range(25)))" "'x' in m" 10000000 loops, best of 3: 0.0854 usec per loop kent $ python -m timeit -s "m=set(map(str, range(25)))" "'12' in m" 10000000 loops, best of 3: 0.117 usec per loop kent $ python -m timeit -s "m=set(map(str, range(25)))" "'0' in m" 10000000 loops, best of 3: 0.0867 usec per loop Notice that the first two tests are significantly faster than searching the list; the last one is slightly slower but this is the best case for the list search (finding the first element). Kent From mrjesseh at yahoo.com Fri Jul 24 23:34:09 2009 From: mrjesseh at yahoo.com (Jesse Harris) Date: Fri, 24 Jul 2009 14:34:09 -0700 (PDT) Subject: [Tutor] Syntax Problem Message-ID: <424472.18191.qm@web53602.mail.re2.yahoo.com> for d in Decks.all(): #loop thru all available decks ????????? self.response.out.write('
') self.response.out.write('
') : invalid syntax (main.py, line 206) ??????args?= ('invalid syntax', (r'C:\Program Files\Google\google_appengine\bangagears2\main.py', 206, 78, " \t\tself.response.out.write(''+d.description)\n")) ??????filename?= r'C:\Program Files\Google\google_appengine\bangagears2\main.py' ??????lineno?= 206 ??????message?= '' ??????msg?= 'invalid syntax' ??????offset?= 78 ??????print_file_and_line?= None ??????text?= " \t\tself.response.out.write(''+d.description)\n" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jul 25 00:11:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Jul 2009 23:11:42 +0100 Subject: [Tutor] Reading text until a certain point References: <5cb309e70907240839q6d87ba0eh757123259b3efaad@mail.gmail.com> Message-ID: "Stefan Lesicnik" wrote > I have a file that has text in a certain format. Lets assume > > ''' > name: stefan > id: 12345 > color: blue > name: joe > id: 54321 > color: red > ''' > > The format is predictable. I understand for non predictable text, you > would > have to use pyparser or the like to build a match. There are lots of ways to do this, I might use a class which takes an open file and reads the three lines and extracts the data as part of the contructor... Untested pseudo code: class Item(object): def __init__(self, aFile): data = aFile.readline().strip().split(:) setattr(self, data[0], data[1]) items = [] f = open('myfile.txt') while f: items.append(Item(f)) This of course breaks my own rule about not having objects for data only but the intelligent constructor makes it worth it. :-) Also there might well be other things you want to do to these elements having collected them... > The problem being i dont really do something per line? I would like to > say > something like, for line until the next 'name', make that 1 element. > So i would like to then have a list or dict (this probably makes sense > for a > dict) with that group. I would then probably split it into various > elements. Just one alternative... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wescpy at gmail.com Sat Jul 25 00:25:30 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 24 Jul 2009 15:25:30 -0700 Subject: [Tutor] Syntax Problem In-Reply-To: <424472.18191.qm@web53602.mail.re2.yahoo.com> References: <424472.18191.qm@web53602.mail.re2.yahoo.com> Message-ID: <78b3a9580907241525g3e5d75e0lcd42320eda7c852@mail.gmail.com> On Fri, Jul 24, 2009 at 2:34 PM, Jesse Harris wrote: > for d in Decks.all(): #loop thru all available decks > ????????? self.response.out.write('
') > self.response.out.write('
') > > : invalid syntax (main.py, line 206) > ??????args?= ('invalid syntax', (r'C:\Program > Files\Google\google_appengine\bangagears2\main.py', 206, 78, " > \t\tself.response.out.write(''+d.description)\n")) > ??????filename?= r'C:\Program > Files\Google\google_appengine\bangagears2\main.py' > ??????lineno?= 206 > ??????message?= '' > ??????msg?= 'invalid syntax' > ??????offset?= 78 > ??????print_file_and_line?= None > ??????text?= " > \t\tself.response.out.write(''+d.description)\n" can't really tell from the TB what the problem is, but perhaps changing the leading tabs to spaces may help, and make sure there is a clean linebreak between pair of lines in the for-loop (and also have leading spaces in front of the 2nd line). -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Sat Jul 25 00:42:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Jul 2009 23:42:10 +0100 Subject: [Tutor] Reading text until a certain point References: <5cb309e70907240839q6d87ba0eh757123259b3efaad@mail.gmail.com> Message-ID: "Alan Gauld" wrote > class Item(object): > def __init__(self, aFile): > data = aFile.readline().strip().split(:) > setattr(self, data[0], data[1]) The last two lines should of course be repeated 3 times... Either in a loop or - for just 3 items - maybe hard coded... > items = [] > f = open('myfile.txt') > while f: # stop when file is empty > items.append( Item(f) ) # process 3 lines I also should have added that you need some exception handling in case the dta doesn't fit cleanly... but I did say it was pseudo code :-) Alan G From quasipedia at gmail.com Sat Jul 25 02:06:17 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 25 Jul 2009 02:06:17 +0200 Subject: [Tutor] Need to be pointed in the right direction for file organisation. Message-ID: <1248480377.15998.29.camel@jabbar> Hello everybody, I am new to python programming, but - thanks to "dive into python" - I had no difficulties in picking up the basics of the language and experimenting on my own with PyGTK and STORM. While I am working my way up to a more pythonic and cleaner style in the code, one thing that I have very confused ideas about is how I should organise my code, in terms of classes and files. I read and understood the basic definitions of module and packages (as explained in the abovementioned book) but yet now that I am developing a GUI application with PyGTK I found myself very confused on how I should best organise my code across various files. I would be very grateful if some of the fellow subscribers would take the time to point me out in the right direction. Don't hold back those answers that you might think are too obvious: I am very new to the topic so it might well be that what I miss is some broad concept, rather than some advanced very specific "trick" in the domain of PyGTK apps. Thanks in advance for your time and support, Mac. From amit.pureenergy at gmail.com Sat Jul 25 02:27:42 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Sat, 25 Jul 2009 01:27:42 +0100 Subject: [Tutor] How to force stop a thread Message-ID: Hi , I am trying to implement python threads in a gtk based app . Now the thing is that in the application I have to fetch a lot of data from various sources from web. During this time I wish to show a dialog that indicates it to the user . During the same time I want to fetch data as well . Now to implement this I have done: a=Wait_dialog() gtk.gdk.threads_init() lock=thread.allocate_lock() thread.start_new_thread(show_dialog,(lock,a)) thread.start_new_thread(fetch,(lock,a)) Now I wish to stop the thread that shows the dialog so I can destroy the dialog and continue with normal app I am not able to understand how to do that ... Also is this the best way to do this kind of thing??? -- A-M-I-T S|S From cynicalairrick at gmail.com Sat Jul 25 05:34:12 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Fri, 24 Jul 2009 20:34:12 -0700 Subject: [Tutor] Reading and Manipulating XML Data Message-ID: <5cd723fd0907242034y39e20c2ane64e9acfd7abddae@mail.gmail.com> Being new to Python and programming, I'm having a very difficult time studying and finding helpful (beginner) documentation on XML. I'm at the point where I have learned the syntax and am just starting to get my feet wet with learning how to utilize it. (and by "utilizing it" I mean making useful programs) I've tackled a couple simple challenges by reading Mr. Wesley Chun's fantastic book, Core Python Programming, but now I want to move on to something a bit more ambitious where I don't necessarily have a helping hand along the way. A challenge I'm giving myself to further develop my programming skills is to make a script that can read an XML file from a specific game that has its own defined tags, etc and will allow you to manipulate the tags and their child contents. I've read about XML Parsing before and I'm hoping it can help me achieve this goal, however, the definition of XML Parsing seams a little foggy to me, which is where I need help. The 'net always gives me an exaggerated technical answer that is simply way over my head, so I'm asking, does parsing mean to read and manipulate data? If not, can someone provide an answer in lay man's terms? The last part of my question brings me back to the first part of this message. I can't seem to find any documentation on the internet that is ideal to the beginning programmer regarding XML parsing. There is either scarce documentation on modules such as minidom or just too little of a single article. For example, I was looking at a small article the other day teaching a little bit about parsing, but it was just so brief that it left me wanting more. You can't learn to bake a cake by forgetting the eggs, milk, and flour! Sorry for that horrible analogy, but I was hoping it would compliment my rant nicely. To make a long question short, what exactly is the complete definition of parsing in lay man's terms (I'm pretty sure I get the idea anyway, I just want to be sure) and what are some decent python xml parsing guides out there? Any help is much appreciated! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ctcast at gmail.com Sat Jul 25 08:40:00 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sat, 25 Jul 2009 01:40:00 -0500 Subject: [Tutor] Reading Data From File Message-ID: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> Okay I really need help with the program I am writing. I've can't seem to figure out what I need to do and have tried several different methods. I need to read in a text file in python that contains the following: Student Name ( could be unknown amount in file ) Numeric Grade ( could be unknown amount in file also ) Numeric Grade Numeric Grade 0 (zero value to terminate and move on to next student and their grades) I need to print the following to the screen: Student Name Numeric Grade, Numeric Grade, Numeric grade, etc.. - ( then A, B C, D, or F average ) PLEASE HELP ME. I need to put the grades into a list and process each student's grades before processing the next student's grades so that I can print each Name, their grades, and average on the same line ( like above ). Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sat Jul 25 08:52:40 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 24 Jul 2009 23:52:40 -0700 Subject: [Tutor] Reading Data From File In-Reply-To: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> References: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> Message-ID: <78b3a9580907242352y52da053aqe2621b17c5b5edb4@mail.gmail.com> On Fri, Jul 24, 2009 at 11:40 PM, Chris Castillo wrote: > Okay I really need help with the program I am writing. I've can't seem to > figure out what I need to do and have tried several different methods. hi chris, and welcome to Python! the tutors here are very helpful to those who are new to programming and/or new to Python. the best thing to do with regards to your issue is to show us some of those "different methods" that you used, and tell us what are the problems that you're encountering with each of them. cut-n-paste the exact errors if possible too. also keep in mind that we cannot just come up with a solution for you, especially if it is for a class assignment, project, or homework. we can help you work through a problem however. best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Sat Jul 25 10:16:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jul 2009 09:16:50 +0100 Subject: [Tutor] Reading and Manipulating XML Data References: <5cd723fd0907242034y39e20c2ane64e9acfd7abddae@mail.gmail.com> Message-ID: "Luis Galvan" wrote > little foggy to me, which is where I need help. The 'net always gives me > an > exaggerated technical answer that is simply way over my head, so I'm > asking, > does parsing mean to read and manipulate data? If not, can someone > provide > an answer in lay man's terms? Others are better qualified than me to answer this but I'll have a go anyway... Parsing is about taking raw datya and making sense of it.. To try to turn a stream of data into meaningful tokens or values. The stream needs to be in a clearly defined structure (such as XML or a programming language grammar). The parser reads the stream and breaks it into meaningful values, such as tags etc for XML. It will usually build these up as a tree structure so that you can navigate the tree to locate sopecific bits of information. Thats as simple as I can describe it. If that's too basic come back with more specific questions. > The last part of my question brings me back to the first part of this > message. I can't seem to find any documentation on the internet that is > ideal to the beginning programmer regarding XML parsing. Have you read the ElementTree tutorial by Fred Lundh? Its fairly comprehensive and etree comes as opart of the standard Python library. I'd certainly recommend etree over minidom! http://effbot.org/zone/element-index.htm > ...what are some decent python xml parsing guides out > there? Any help is much appreciated! You could try reading Text Processing in Python which is a book but also available online at: http://gnosis.cx/TPiP/ HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jul 25 10:23:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jul 2009 09:23:41 +0100 Subject: [Tutor] Need to be pointed in the right direction for fileorganisation. References: <1248480377.15998.29.camel@jabbar> Message-ID: "Mac Ryan" wrote > While I am working my way up to a more pythonic and cleaner style in > the code, one thing that I have very confused ideas about is how I > should organise my code, in terms of classes and files. I don't think there is any definitive answer. - Put reusable components into modules. - Don't necessarily create a module per class, but rather gather related classes into a single module. - Build modules "bottom up" so that depenedencies tend to go one way, with higher level modules importing lower level ones. Beyond that there are many different approaches to organisation. They all have strengths and weaknesses. The good news is that Python is such a high level language that you rarely have projects with so many modules that you need to create sophisticated directory structures. Usually everything can fit in one project folder. (Zope, Django etc being good examples of exceptions! :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Sat Jul 25 11:33:13 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 25 Jul 2009 05:33:13 -0400 Subject: [Tutor] What kind of number is this In-Reply-To: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com> References: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com> Message-ID: <4A6AD159.8090404@ieee.org> Emad Nawfal (9E'/ FHAD) wrote: > Hi Tutors, > I have a bunch of text files that have many occurrences like the following > which I believe, given the context, are numbers: > > ١٨٧٢ > > ٥٧ > > ٢٠٠٨ > > etc. > > So, can somebody please explain what kind of numbers these are, and how I > can get the original numbers back. The files are in Arabic and were > downloaded from an Arabic website. > I'm running python2.6 on Ubuntu 9.04 > > Those are standard html encodings for some Unicode characters. Skipper has identified one of them as the digit '1' written in Arabic. I presume the others will also be recognizable to you, since you apparently know Arabic. The following text should be copied to a flie with extension .html Then you run that in a browser, to see the characters. DaveA Test Arabic Characters

Table of characters
1632 - ٠
1633 - ١
1634 - ٢
1635 - ٣
1636 - ٤
1637 - ٥
1638 - ٦
1639 - ٧
1640 - ٨
1641 - ٩

From davea at ieee.org Sat Jul 25 12:10:53 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 25 Jul 2009 06:10:53 -0400 Subject: [Tutor] Syntax Problem In-Reply-To: <424472.18191.qm@web53602.mail.re2.yahoo.com> References: <424472.18191.qm@web53602.mail.re2.yahoo.com> Message-ID: <4A6ADA2D.2050900@ieee.org> Jesse Harris wrote: > for d in Decks.all(): #loop thru all available decks > self.response.out.write('
') > self.response.out.write('
') > > : invalid syntax (main.py, line 206) > > args = > ('invalid syntax', (r'C:\Program Files\Google\google_appengine\bangagears2\main.py', 206, 78, " \t\tself.response.out.write(''+d.description)\n")) > > filename = > r'C:\Program Files\Google\google_appengine\bangagears2\main.py' > > lineno = > 206 > > message = > '' > > msg = > 'invalid syntax' > > offset = > 78 > > print_file_and_line = > None > > text = > " \t\tself.response.out.write(''+d.description)\n" > > > > There are so many things wrong I'm not sure where to begin. This excerpt of code isn't nearly enough to compile, since it references lots of symbols not defined. And it's not formatted the same as your original. Your original definitely had tabs in it, as well as the normal spaces for indenting, which is asking for trouble. You shouldn't use the name 'self' when you're not inside a method definition (it's not an error, but it is sure confusing). If I take my best guess at some class and method definitions, and paste this fragment into a method of a class, and fix the indenting to what I might guess you were planning, it compiles and runs without problems. But I expected that, since the error is supposed to be in column 78, and you didn't have that many columns in your posting. Even if I add back in the two tabs you omitted, and count them as eight characters each, we're still ten characters short. Finally the error line displayed is not included in your excerpt. Since the error message used ellipses in its quoting of the line, we can't see it all. But if I had to guess, I'd say it was a case of mismatched quotation marks. Or two lines combined together (note the two occurrences of self.response.out.write() ) DaveA From davea at ieee.org Sat Jul 25 12:26:45 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 25 Jul 2009 06:26:45 -0400 Subject: [Tutor] Reading Data From File In-Reply-To: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> References: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> Message-ID: <4A6ADDE5.80709@ieee.org> Chris Castillo wrote: > Okay I really need help with the program I am writing. I've can't seem to > figure out what I need to do and have tried several different methods. > > I need to read in a text file in python that contains the following: > > Student Name ( could be unknown amount in file ) > Numeric Grade ( could be unknown amount in file also ) > Numeric Grade > Numeric Grade > 0 (zero value to terminate and move on to next student and their grades) > > I need to print the following to the screen: > Student Name Numeric Grade, Numeric Grade, Numeric grade, etc.. - ( then > A, B C, D, or F average ) > > PLEASE HELP ME. I need to put the grades into a list and process each > student's grades before processing the next student's grades so that I can > print each Name, their grades, and average on the same line ( like above ). > Thanks > > Generally, when I help someone with his homework, I expect him to have put some visible effort into solving the problem. So you've tried several different methods. Post the code from the most likely one of them, with a description of why it isn't doing what you needed, and one of us will probably be able to give you a hint to get past the trouble spot. Don't post generalities, but actual code. The whole thing should be less than a dozen lines. DaveA From emadnawfal at gmail.com Sat Jul 25 14:14:38 2009 From: emadnawfal at gmail.com (=?UTF-8?B?RW1hZCBOYXdmYWwgKNi52YXYp9ivINmG2YjZgdmEKQ==?=) Date: Sat, 25 Jul 2009 08:14:38 -0400 Subject: [Tutor] What kind of number is this In-Reply-To: <4A6AD159.8090404@ieee.org> References: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com> <4A6AD159.8090404@ieee.org> Message-ID: <652641e90907250514m1566287aq75f675fd6336057f@mail.gmail.com> On 7/25/09, Dave Angel wrote: > Emad Nawfal (9E'/ FHAD) wrote: >> Hi Tutors, >> I have a bunch of text files that have many occurrences like the following >> which I believe, given the context, are numbers: >> >> ١٨٧٢ >> >> ٥٧ >> >> ٢٠٠٨ >> >> etc. >> >> So, can somebody please explain what kind of numbers these are, and how I >> can get the original numbers back. The files are in Arabic and were >> downloaded from an Arabic website. >> I'm running python2.6 on Ubuntu 9.04 >> >> > Those are standard html encodings for some Unicode characters. Skipper > has identified one of them as the digit '1' written in Arabic. I > presume the others will also be recognizable to you, since you > apparently know Arabic. The following text should be copied to a flie > with extension .html Then you run that in a browser, to see the > characters. > > DaveA > > > > > > Test Arabic Characters > > >

> Table of characters
> 1632 - ٠
> 1633 - ١
> 1634 - ٢
> 1635 - ٣
> 1636 - ٤
> 1637 - ٥
> 1638 - ٦
> 1639 - ٧
> 1640 - ٨
> 1641 - ٩
>

> > > > Thank you very much Skipper and Dave. Your replies have been very useful. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- From davidwilson at Safe-mail.net Sat Jul 25 14:36:42 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Sat, 25 Jul 2009 08:36:42 -0400 Subject: [Tutor] import rsvg Message-ID: Hello, I have searched high and low but for the life of me I am unable to locate this module. >>> import cairo >>> import rsvg Traceback (most recent call last): File "", line 1, in ImportError: No module named rsvg >>> Basically from my previous post I would like to now manipulate the SVG files and export them as PNG. I am following the http://guillaume.segu.in/blog/code/43/svg-to-png/ post. Is there an up to date method of doing this? Dave From norman at khine.net Sat Jul 25 14:46:33 2009 From: norman at khine.net (Norman Khine) Date: Sat, 25 Jul 2009 13:46:33 +0100 Subject: [Tutor] import rsvg In-Reply-To: References: Message-ID: <9c2c8ffb0907250546g24556efbj6ae5699a16afa35e@mail.gmail.com> maybe because you need to install Gnome-Python On Sat, Jul 25, 2009 at 1:36 PM, wrote: > Hello, > I have searched high and low but for the life of me I am unable to locate this module. > >>>> import cairo >>>> import rsvg > Traceback (most recent call last): > ?File "", line 1, in > ImportError: No module named rsvg >>>> > > > Basically from my previous post I would like to now manipulate the SVG files and export them as PNG. I am following the http://guillaume.segu.in/blog/code/43/svg-to-png/ post. > > Is there an up to date method of doing this? > > Dave > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at gmail.com Sat Jul 25 15:34:06 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 25 Jul 2009 09:34:06 -0400 Subject: [Tutor] Reading Data From File In-Reply-To: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> References: <50e459210907242340u356bd09fjd7e85aa0068c9f6c@mail.gmail.com> Message-ID: <4A6B09CE.7080807@gmail.com> I concur with wesley and dave re homework. Some questions to consider: do you know how to open a file? do you know how to read a line from an opened file? do you know how to incorporate reading lines in a loop? do you know how to determine whether a character is "numeric"? do you know how to print a line? what is the criteria for determining A, B C, D, or F average? -- Bob Gailer Chapel Hill NC 919-636-4239 From amrita at iisermohali.ac.in Sat Jul 25 16:41:47 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Sat, 25 Jul 2009 20:11:47 +0530 (IST) Subject: [Tutor] how to get blank value Message-ID: <13706.210.212.36.65.1248532907.squirrel@www.iisermohali.ac.in> Hi, I have a file having lines:- 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = 85 ALA H = 8.60 N = CA = HA = 4.65 C = Now i want to make two another file in which i want to put those lines for which C is missing and another one for which N,CA and C all are missing, With these commands:- import re f = open('chem.txt') for line in f: if re.search('C = ',line): print line I am getting those lines for which C value is there but how to get those one for which it doesn't have any value, i did google search but still i am not getting. Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From alan.gauld at btinternet.com Sat Jul 25 17:48:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jul 2009 16:48:21 +0100 Subject: [Tutor] how to get blank value References: <13706.210.212.36.65.1248532907.squirrel@www.iisermohali.ac.in> Message-ID: wrote > With these commands:- > > import re > f = open('chem.txt') > for line in f: > if re.search('C = ',line): > print line > > I am getting those lines for which C value is there but how to get those > one for which it doesn't have any value, i did google search but still i > am not getting. Don;t do a Google search, just read the re documentation, including the HowTo, looking for how to detect the end of a line. Alan G. From metolone+gmane at gmail.com Sat Jul 25 18:09:33 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 25 Jul 2009 09:09:33 -0700 Subject: [Tutor] What kind of number is this References: <652641e90907240854j56b2d078rc6424f95c8aef941@mail.gmail.com><4A6AD159.8090404@ieee.org> <652641e90907250514m1566287aq75f675fd6336057f@mail.gmail.com> Message-ID: "Emad Nawfal (???? ????)" wrote in message news:652641e90907250514m1566287aq75f675fd6336057f at mail.gmail.com... > On 7/25/09, Dave Angel wrote: >> Emad Nawfal (9E'/ FHAD) wrote: >>> Hi Tutors, >>> I have a bunch of text files that have many occurrences like the >>> following >>> which I believe, given the context, are numbers: >>> >>> ١٨٧٢ >>> >>> ٥٧ >>> >>> ٢٠٠٨ >>> >>> etc. >>> >>> So, can somebody please explain what kind of numbers these are, and how >>> I >>> can get the original numbers back. The files are in Arabic and were >>> downloaded from an Arabic website. >>> I'm running python2.6 on Ubuntu 9.04 >> Those are standard html encodings for some Unicode characters. [snip] You might find re.sub() useful to process your text files. It will replace the HTML encodings with the actual Unicode character. >>> import re >>> data = >>> u"١٨٧٢٥٧٢٠٠٨" >>> s = re.sub(r'&#(\d+);',lambda m: unichr(int(m.group(1))),data) >>> s u'\u0661\u0668\u0667\u0662\u0665\u0667\u0662\u0660\u0660\u0668' >>> print s 1872572008 And this can be helpful for identifying Unicode characters: >>> import unicodedata >>> for c in s: ... print unicodedata.name(c) ... ARABIC-INDIC DIGIT ONE ARABIC-INDIC DIGIT EIGHT ARABIC-INDIC DIGIT SEVEN ARABIC-INDIC DIGIT TWO ARABIC-INDIC DIGIT FIVE ARABIC-INDIC DIGIT SEVEN ARABIC-INDIC DIGIT TWO ARABIC-INDIC DIGIT ZERO ARABIC-INDIC DIGIT ZERO ARABIC-INDIC DIGIT EIGHT -Mark From ldl08 at gmx.net Sat Jul 25 19:17:41 2009 From: ldl08 at gmx.net (David) Date: Sun, 26 Jul 2009 01:17:41 +0800 Subject: [Tutor] sqlite: don't understand a code snippet Message-ID: <4A6B3E35.3020304@gmx.net> Dear tutors, I am trying to teach myself the way Python's works with databases. I decided to start with SQLite, and am looking at Summerfield's 'Programming in Python 3'. I got a code snippet that I don't fully understand (the comments are mine): def get_and_set_director(db, director): # try to fetch existing director ID from db director_id = get_director_id(db, director) # if director ID was found in db, return ID if director_id is not None: return director_id cursor = db.cursor() # insert new director record cursor.execute("INSERT INTO directors (name) VALUES (?)", (director,)) db.commit() # retrieve and return new director ID from db return get_director_id(db, director) Here is what I think is going on: The function get_and_set_director() gets the director ID from the db by calling the function get_director-id() and returns its value. If the director ID is not in the db then, from outside the get_and_set_director() function, the ID gets inserted to the db via the commit() method. Finally, the director ID is returned (from the db) by once again calling the get_director_id() function. Question: where does a new the director ID come from? Thanks for your directions! David From quasipedia at gmail.com Sat Jul 25 20:44:36 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 25 Jul 2009 20:44:36 +0200 Subject: [Tutor] Need to be pointed in the right direction for file organisation. Message-ID: <1248547476.26716.28.camel@jabbar> Thank you Alan for the prompt reply, > - Put reusable components into modules. OK: the use of files as "libraries" is quite clear to me and indeed I am already doing that. What is not clear is if I should _only_ put in modules stuff that is reusable, or if there are other widely accepted ways to user files. For example, in the GTK application I am currently developing I have a notebook widget (sort of tabbed windows which are visible only one at a time). I was therefore thinking about separating the classes for each "tabbed window" in different files, under the impression that this would make the program faster / with a smaller memory footprint, as only the needed file will be loaded into memory [In PHP you can reach quite a gain in terms of speed if yo do so]. Would this be considered a proper way to code in python? Another concern of mine was the readability of the source code, and I was wondering indeed if there was a "pythonic style" that was commonly understood as "the right one" [I'm thinking to those kind of guidelines like "put the import directive at the top of the file", but for file organisation] > - Build modules "bottom up" so that depenedencies tend to > go one way, with higher level modules importing lower level ones. I'm not sure I got it completely, does this mean that the file structure should be a hint of how dependency works, with ancestors nested in the subfolders of the children classes or something similar? Anyhow, thanks a lot for having answered so promptly! :) Mac. > > While I am working my way up to a more pythonic and cleaner style in > > the code, one thing that I have very confused ideas about is how I > > should organise my code, in terms of classes and files. > > I don't think there is any definitive answer. > > - Put reusable components into modules. > > - Don't necessarily create a module per class, but rather gather > related classes into a single module. > > - Build modules "bottom up" so that depenedencies tend to > go one way, with higher level modules importing lower level ones. > From ctcast at gmail.com Sat Jul 25 20:44:29 2009 From: ctcast at gmail.com (ctcast at gmail.com) Date: Sat, 25 Jul 2009 18:44:29 +0000 Subject: [Tutor] Reading Data From File In-Reply-To: <4A6B09CE.7080807@gmail.com> Message-ID: <00163630f5c96d364f046f8c1ca7@google.com> grades = [] names = [] gradeTotal = 0 numStudents = 0 inputFile = open("input.txt", "r" for line in inputFile: if line.strip().isdigit(): grade = float(line) if grade != 0.0: gradeTotal += grade grade = grades.append(grade) else: name = line.strip() name = names.append(name) This just loops over the entire file basically and just continually adds the grades to the grades list and names to the names list. How do I just process each student's set of grades before moving on to the next one (since there is a zero terminating value telling the loop that a new student and his or her grades are about to follow) By the way I'm not worrying about determining the letter grade average right now, i'm importing a module I wrote after I figure this part out. On Jul 25, 2009 8:34am, bob gailer wrote: > I concur with wesley and dave re homework. > Some questions to consider: > do you know how to open a file? > do you know how to read a line from an opened file? > do you know how to incorporate reading lines in a loop? > do you know how to determine whether a character is "numeric"? > do you know how to print a line? > what is the criteria for determining A, BC, D, or F average? > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: From roadierich at googlemail.com Sat Jul 25 21:26:07 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sat, 25 Jul 2009 20:26:07 +0100 Subject: [Tutor] sqlite: don't understand a code snippet In-Reply-To: <4A6B3E35.3020304@gmx.net> References: <4A6B3E35.3020304@gmx.net> Message-ID: 2009/7/25 David : > Dear tutors, > > I am trying to teach myself the way Python's works with databases. > I decided to start with SQLite, and am looking at Summerfield's > 'Programming in Python 3'. > I got a code snippet that I don't fully understand (the comments are mine): > > > def get_and_set_director(db, director): > ? ?# try to fetch existing director ID from db > ? ?director_id = get_director_id(db, director) > ? ?# if director ID was found in db, return ID > ? ?if director_id is not None: > ? ?return director_id > cursor = db.cursor() > # insert new director record > cursor.execute("INSERT INTO directors (name) VALUES (?)", > ? ? ? ? ? ? ? (director,)) > db.commit() > # retrieve and return new director ID from db > return get_director_id(db, director) > > Here is what I think is going on: > > The function get_and_set_director() gets the director ID from the db > by calling the function get_director-id() and returns its value. > > If the director ID is not in the db then, from outside the > get_and_set_director() function, the ID gets inserted to the db via > the commit() method. Finally, the director ID is returned (from the db) > by once again calling the get_director_id() function. > > Question: where does a new the director ID come from? > > Thanks for your directions! > > David > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > It sounds as if the directors table has an AUTO_INCREMENT column, which will automatically assign itself the next value sequentially when you insert an entry into the table. i.e. The first inserted entry gets an ID of 1, the next 2, and so on. This is stored in a column in the table. The get_director_id(...) function will do something like the following query: cursor.execute("SELECT id FROM directors WHERE name == \"%s\"", (name,)) I don't know how well I've explained it, but this is the normal technique for generating unique ids for rows in a database. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From alan.gauld at btinternet.com Sat Jul 25 21:50:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jul 2009 20:50:27 +0100 Subject: [Tutor] Need to be pointed in the right direction for file organisation. References: <1248547476.26716.28.camel@jabbar> Message-ID: "Mac Ryan" wrote > time). I was therefore thinking about separating the classes for each > "tabbed window" in different files, under the impression that this would > make the program faster / with a smaller memory footprint, as only the > needed file will be loaded into memory The gains would be minimal, and its dcertainly not common practice. In fact having more modules loaded might even make performance worse! I'd certainly categorize that as premature optimisation! > Another concern of mine was the readability of the source code, and I > was wondering indeed if there was a "pythonic style" that was commonly > understood as "the right one" Not for file organisation. There is the package concept so if you have a lot of related modules you could create a package structure, but most of Python's organisation guidelines tend to focus on maximising reuse rather than organizing the current project, in my experience at least. >> - Build modules "bottom up" so that depenedencies tend to >> go one way, with higher level modules importing lower level ones. > > I'm not sure I got it completely, does this mean that the file structure > should be a hint of how dependency works, No, just that you should try to keep low level functuions etc in separate files and have the higher level, more abstract modules import them. Rather than mixing low level, implementation dependant coded with more abstract - and therefore more portable module code. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From keithabt at beyondbb.com Sat Jul 25 21:53:19 2009 From: keithabt at beyondbb.com (keithabt at beyondbb.com) Date: Sat, 25 Jul 2009 15:53:19 -0400 Subject: [Tutor] reading into a text file Message-ID: Hi I am trying to read a html document into a text file to looks at it for the purpose of spliting the data. I am not sure I am doing this right. I have my html document, my text file and a python script I called convt.py on the desktop in a folder. I opened up IDLE (python GUI) opened the folder on my desk top and then went to run module. I keep getting an error saying "No such file or directory: 'source.txt' I am new to python so I really don't know if I am doing this right. Any suggestions? #!/usr/bin/python u=open("source.txt").read() lines = u.split("

") print lines[1] From alan.gauld at btinternet.com Sun Jul 26 00:07:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Jul 2009 23:07:50 +0100 Subject: [Tutor] reading into a text file References: Message-ID: wrote > Hi I am trying to read a html document into a text file Hi, welcome to the tutor list. First thing to point out is that HTML files are just text files with a particular structure. But so far as reading them in Python goes they are no different to any other text file. > purpose of spliting the data. Now this is where it gets interesting, it depends what exactly you are trying to "split". What do you mean by the "data"? If its the HTML elements there are specialised Python tools that will make this a lot easier. But if it is simply splitting into separate lines, read on... > I am not sure I am doing this right. I have my html > document, my text file and a python script I called > convt.py on the desktop Its usually a bad idea in Windows to do anythiong on the Desktop, keep that as a place for putting icons to launch programs. Put working files into separate project folders. > in a folder. I assume this means a folder on your Desktop? That's slightly better but still leaves problems because the true path to your folder is: C:\Documents and Settings\YourName\Desktop\YourFolder Which Windows tries to hide most of the time! Personally I'd recommend creating a "Projects" or "Work" folder at the top level of one of your drives (if you have more than one) and moving your folder under that. Then the full path becomes D:\Work\MyFolder Which is a lot easier to deal with and less likely to run into Windows "cleverness" issues. > I opened up IDLE (python GUI) opened the folder on my desk top and then > went to run module. OK, I'm still not 100% clear on what you are doing here but this is probably a good time to get to know the Windows command prompt. (Take a look at the box on the Getting Started topic in my tutorial for a brief intro.) Thats a better way to run your programs on real data IMHO. > I keep getting an error saying "No such file or directory: 'source.txt' If you start a command prompt Start->Run Type CMD, Hit OK At the prompt C:\WINDOWS> or similar type python myscript.py It should now find it. > I am new to python so I really don't know if I am doing this right. > > #!/usr/bin/python > u=open("source.txt").read() > lines = u.split("

") > print lines[1] You are splitting by the sequence of

. That is each "line" starts with a paragraph tag followed immediately by a bold tag, is that really what you want? If so it looks fine. You could modify your program so that it takes the filename at the command line, so you can process more than one file: python myscript foo.html or python myscript.py bar.html for example HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From darthkaboda at msn.com Sun Jul 26 02:15:36 2009 From: darthkaboda at msn.com (Darth Kaboda) Date: Sat, 25 Jul 2009 17:15:36 -0700 Subject: [Tutor] First code snipet Message-ID: I'm starting to learn Python as it seems to be adopted by many companies that I've been looking to apply to. I used the book Learning Phython to get the basics of the language and many of the gotcha's. I think I know enough of the basic features of the language to start playing around and can understand most code I've seen so far by looking at some of the posts here. The one worry I have is not coding things the Phython way as I've been a Visual Basic programmer for so long and a C++ programmer before that. So would like to have people look at a simplistic class (shuffles lists of objects wrote it for shuffling cards but with Phython could be used for any "list" type object) I wrote to give me some feedback on the style of it. Any feedback is appreciated. Thanks, Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: shuffler.py URL: From davea at dejaviewphoto.com Sat Jul 25 23:37:55 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Sat, 25 Jul 2009 17:37:55 -0400 Subject: [Tutor] Reading Data From File In-Reply-To: <00163630f5c96d364f046f8c1ca7@google.com> References: <00163630f5c96d364f046f8c1ca7@google.com> Message-ID: <4A6B7B33.9020702@dejaviewphoto.com> ctcast at gmail.com wrote: > grades = [] > names = [] > gradeTotal = 0 > numStudents = 0 > > inputFile = open("input.txt", "r" > > for line in inputFile: > if line.strip().isdigit(): > grade = float(line) > if grade != 0.0: > gradeTotal += grade > grade = grades.append(grade) > else: > name = line.strip() > name = names.append(name) > > This just loops over the entire file basically and just continually > adds the grades to the grades list and names to the names list. How do > I just process each student's set of grades before moving on to the > next one (since there is a zero terminating value telling the loop > that a new student and his or her grades are about to follow) > > By the way I'm not worrying about determining the letter grade average > right now, i'm importing a module I wrote after I figure this part out. > > On Jul 25, 2009 8:34am, bob gailer wrote: >> I concur with wesley and dave re homework. > > There are syntax errors of at least two kinds here. The first is you're missing a trailing parenthesis. And the second is you lost all your indentation when you retyped the code. It'd really be better if you pasted the actual code instead. Not much of a problem in this case, at least if I guess the same as you had, but in many cases the indentation *is* the problem. Next problem is that you're assuming that list.append() returns something useful. It doesn't return anything, which is to say it returns "None." So it's not useful to do: grade = grades.append(grade) just leave off the left half of that. And likewise leave off the name= from the other call to append(). The next problem is that you have two independent lists, but no way to correlate which elements of one correspond to which elements of the other. So you have a choice to make. Do you need all the data for post-processing, or is it enough that you print it out, and discard it afterwards? I'll assume that you'd answer that it's enough to just be able to print it out. In that case, you just need some well placed print statements. Each time you come to a line with a zero in it, you have enough information to print out one student's information. And in this case, you don't need a list of students, just the name of the current one. Do you expect any numbers to be non-integers? I'd assume so because you used the float() function instead of int(). But isdigit() is going to be a problem if there's a decimal in there. DaveA From fredp101 at mac.com Sun Jul 26 01:24:13 2009 From: fredp101 at mac.com (Fred @ Mac) Date: Sat, 25 Jul 2009 16:24:13 -0700 Subject: [Tutor] Need to start learning again Message-ID: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> I started learning python, but then life got busy... I need some help finding good resources to start learning again. My main need for python at first would be to write small programs to perform system commands. Like moving files around, copying or deleting files, and perhaps some simple interface construction so I can create a window to show the status of the little programs i plan to write. Any help would be appreciated. From cynicalairrick at gmail.com Sun Jul 26 02:51:57 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Sat, 25 Jul 2009 17:51:57 -0700 Subject: [Tutor] Need to start learning again In-Reply-To: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> References: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> Message-ID: <5cd723fd0907251751m7ef802b6j37c80be85a043b8e@mail.gmail.com> Check out thenewboston's video tutorials at Youtube: http://www.youtube.com/view_play_list?p=EA1FEF17E1E5C0DA They're fairly recent and they definitely got me started with learning the syntax. After you're through with those, he also has a series on wxPython. A couple ebooks you'd be interested in would be Dive into Python or A Byte of Python, both very thorough and descriptive, the latter being a bit easier to newer programmers. A great book might consider purchasing would be Wesley Chun's Core Python Programming. This is only a slice of the cake though, try Googling around for more resources. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Sun Jul 26 03:02:27 2009 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Sun, 26 Jul 2009 03:02:27 +0200 Subject: [Tutor] First code snipet In-Reply-To: References: Message-ID: <1248570147.28544.249.camel@andi-lap> Some things: 1) It's Python, not Phython. 2) Slightly shorter solution to your problem: import random input = range(53) random.shuffle(input) print input 3) The important part here is that reimplementing something that is in the standard library does not make sense usually. 4) A more sensible implementation of shuffle comes directly out of random.py: def shuffle(self, x, random=None, int=int): """x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random. """ if random is None: random = self.random for i in reversed(xrange(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] Notice that it is not exactly optimal, one could easily replace the reversed(xrange()) expression with a 3 parameter version of xrange: for i in xrange(len(x) - 1, 0, -1): Andreas Am Samstag, den 25.07.2009, 17:15 -0700 schrieb Darth Kaboda: > I'm starting to learn Python as it seems to be adopted by many > companies that I've been looking to apply to. I used the book Learning > Phython to get the basics of the language and many of the gotcha's. I > think I know enough of the basic features of the language to start > playing around and can understand most code I've seen so far by > looking at some of the posts here. > > The one worry I have is not coding things the Phython way as I've been > a Visual Basic programmer for so long and a C++ programmer before > that. So would like to have people look at a simplistic class > (shuffles lists of objects wrote it for shuffling cards but > with Phython could be used for any "list" type object) I wrote to give > me some feedback on the style of it. > > Any feedback is appreciated. > > Thanks, > Brian > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 197 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From darthkaboda at msn.com Sun Jul 26 04:02:30 2009 From: darthkaboda at msn.com (Darth Kaboda) Date: Sat, 25 Jul 2009 19:02:30 -0700 Subject: [Tutor] First code snipet In-Reply-To: <1248570147.28544.249.camel@andi-lap> References: <1248570147.28544.249.camel@andi-lap> Message-ID: > Subject: Re: [Tutor] First code snipet > From: andreas at kostyrka.org > To: darthkaboda at msn.com > CC: tutor at python.org > Date: Sun, 26 Jul 2009 03:02:27 +0200 > > Some things: > > 1) It's Python, not Phython. > 2) Slightly shorter solution to your problem: > > import random > > input = range(53) > random.shuffle(input) > print input > > 3) The important part here is that reimplementing something that is in > the standard library does not make sense usually. > > 4) A more sensible implementation of shuffle comes directly out of > random.py: > > def shuffle(self, x, random=None, int=int): > """x, random=random.random -> shuffle list x in place; return > None. > > Optional arg random is a 0-argument function returning a random > float in [0.0, 1.0); by default, the standard random.random. > """ > > if random is None: > random = self.random > for i in reversed(xrange(1, len(x))): > # pick an element in x[:i+1] with which to exchange x[i] > j = int(random() * (i+1)) > x[i], x[j] = x[j], x[i] > > Notice that it is not exactly optimal, one could easily replace the > reversed(xrange()) expression with a 3 parameter version of xrange: > for i in xrange(len(x) - 1, 0, -1): > > Andreas > > > > Am Samstag, den 25.07.2009, 17:15 -0700 schrieb Darth Kaboda: > > I'm starting to learn Python as it seems to be adopted by many > > companies that I've been looking to apply to. I used the book Learning > > Phython to get the basics of the language and many of the gotcha's. I > > think I know enough of the basic features of the language to start > > playing around and can understand most code I've seen so far by > > looking at some of the posts here. > > > > The one worry I have is not coding things the Phython way as I've been > > a Visual Basic programmer for so long and a C++ programmer before > > that. So would like to have people look at a simplistic class > > (shuffles lists of objects wrote it for shuffling cards but > > with Phython could be used for any "list" type object) I wrote to give > > me some feedback on the style of it. > > > > Any feedback is appreciated. > > > > Thanks, > > Brian > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor Thanks for the correction not sure why I typed it that way after typing it correctly in the first sentence, must have wondered off somewhere in my mind I guess. Oops I guess I should have also mentioned what I was trying to accomplish with this class. I wanted to mimic how a deck of cards get's shuffled in the real world. i.e. split the deck and shuffle the two halves together. Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Jul 26 05:38:26 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 25 Jul 2009 22:38:26 -0500 Subject: [Tutor] Need to start learning again In-Reply-To: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> References: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> Message-ID: <333efb450907252038s52be1b2dp70ea7b8469153ccf@mail.gmail.com> On Sat, Jul 25, 2009 at 6:24 PM, Fred @ Mac wrote: > I started learning python, but then life got busy... I need some help > finding good resources to start learning again. > I learned everything I know from Google ;) or at least sources provided by Google. I'd also recommend Python for System Administrators by Noah Gift and Jeremy Jones. If it's available at your local public library, I'd check it out (and well worth the $15 price used). > > My main need for python at first would be to write small programs to > perform system commands. Like moving files around, copying or deleting > files, and perhaps some simple interface construction so I can create a > window to show the status of the little programs i plan to write. Python for Sys admins covers all of the above. If you want a very simple interface, I'd go with Tkinter. It's a lot easier to use than some of the bigger GUIs, like GTK, but it also sacrifices a lot of features to go with that simplicity. A couple of folks on this mailing list have python tutorials that are certainly worth a read. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Jul 26 05:52:04 2009 From: srilyk at gmail.com (Wayne) Date: Sat, 25 Jul 2009 22:52:04 -0500 Subject: [Tutor] First code snipet In-Reply-To: References: Message-ID: <333efb450907252052o6474d745t77d44f99cab7cd68@mail.gmail.com> On Sat, Jul 25, 2009 at 7:15 PM, Darth Kaboda wrote: > I'm starting to learn Python as it seems to be adopted by many companies > that I've been looking to apply to. I used the book Learning Phython to get > the basics of the language and many of the gotcha's. I think I know enough > of the basic features of the language to start playing around and can > understand most code I've seen so far by looking at some of the posts here. > > The one worry I have is not coding things the Phython way as I've been a > Visual Basic programmer for so long and a C++ programmer before that. So > would like to have people look at a simplistic class (shuffles lists of > objects wrote it for shuffling cards but with Phython could be used for any > "list" type object) I wrote to give me some feedback on the style of it. > > Any feedback is appreciated. > There's a spot in your code that could be turned into a function. I'm not sure what you'd call it, but where you "lay down" 1-4 cards. Since you're doing the same thing for each stack, you may as well turn it into a function and just call it for each stack. Pretty cool idea for something to do, though. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Sun Jul 26 05:58:05 2009 From: pine508 at hotmail.com (Che M) Date: Sat, 25 Jul 2009 23:58:05 -0400 Subject: [Tutor] Need to start learning again In-Reply-To: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> References: <775C659F-B21F-47FC-B831-7C810A14E15D@mac.com> Message-ID: > From: fredp101 at mac.com > To: tutor at python.org > Date: Sat, 25 Jul 2009 16:24:13 -0700 > Subject: [Tutor] Need to start learning again > > I started learning python, but then life got busy... I need some help > finding good resources to start learning again. > > My main need for python at first would be to write small programs to > perform system commands. Like moving files around, copying or > deleting files, and perhaps some simple interface construction so I > can create a window to show the status of the little programs i plan > to write. > > Any help would be appreciated. For file manipulation, take a look at this: http://effbot.org/librarybook/os.htm And yes, Tkinter probably would make things easier for a simple GUI. _________________________________________________________________ Windows Live? Hotmail?: Celebrate the moment with your favorite sports pics. Check it out. http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jul 26 09:39:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Jul 2009 08:39:31 +0100 Subject: [Tutor] First code snipet References: Message-ID: "Darth Kaboda" wrote > The one worry I have is not coding things the Phython way > ...So would like to have people look at a simplistic class > rpile = pile1[0:0] #get blank copy of the passed in object types. This will return an empty list regardless of the type of passed in object. The only possible difference is a subclassed list but if its been well implemented you shouldn't care! I'd just go with: rpile = [] > for x in range(0,i): Its usual in Python to omit the first 0 for x in range(i): is all that's needed. Otherwise it looks OK to me. You might be able to leverage the stdlib more effectively, for example there is a shuffle type menthod for randomising a single list. And zip() to merge two lists... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ctcast at gmail.com Sun Jul 26 11:57:35 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sun, 26 Jul 2009 04:57:35 -0500 Subject: [Tutor] Reading Data From File In-Reply-To: <4A6B7B33.9020702@dejaviewphoto.com> References: <00163630f5c96d364f046f8c1ca7@google.com> <4A6B7B33.9020702@dejaviewphoto.com> Message-ID: <50e459210907260257v59540abblbefd4b79b01bba48@mail.gmail.com> ya i was kind of in a hurry composing the email earlier. sorry for the typos and misunderstanding. This is what I actually have. grades = [] names = [] gradeTotal = 0 numStudents = 0 inputFile = open("input.txt", "r") for line in inputFile: if line.strip().isdigit(): grade = float(line) if grade != 0.0: gradeTotal += grade grade = grades.append(grade) else: name = line.strip() name = names.append(name) So even If I take the stuff out that you said, My structure still wouldn't be right because I'm processing everything all at once with no way to reference any of the grades with the student. How do I structure this differently to do that? That's what I'm having trouble with. On 7/25/09, Dave Angel wrote: > ctcast at gmail.com wrote: >> grades = [] >> names = [] >> gradeTotal = 0 >> numStudents = 0 >> >> inputFile = open("input.txt", "r" >> >> for line in inputFile: >> if line.strip().isdigit(): >> grade = float(line) >> if grade != 0.0: >> gradeTotal += grade >> grade = grades.append(grade) >> else: >> name = line.strip() >> name = names.append(name) >> >> This just loops over the entire file basically and just continually >> adds the grades to the grades list and names to the names list. How do >> I just process each student's set of grades before moving on to the >> next one (since there is a zero terminating value telling the loop >> that a new student and his or her grades are about to follow) >> >> By the way I'm not worrying about determining the letter grade average >> right now, i'm importing a module I wrote after I figure this part out. >> >> On Jul 25, 2009 8:34am, bob gailer wrote: >>> I concur with wesley and dave re homework. >> >> > There are syntax errors of at least two kinds here. The first is you're > missing a trailing parenthesis. And the second is you lost all your > indentation when you retyped the code. It'd really be better if you > pasted the actual code instead. Not much of a problem in this case, at > least if I guess the same as you had, but in many cases the indentation > *is* the problem. > > Next problem is that you're assuming that list.append() returns > something useful. It doesn't return anything, which is to say it returns > "None." So it's not useful to do: > grade = grades.append(grade) > > just leave off the left half of that. And likewise leave off the name= > from the other call to append(). > > The next problem is that you have two independent lists, but no way to > correlate which elements of one correspond to which elements of the > other. So you have a choice to make. Do you need all the data for > post-processing, or is it enough that you print it out, and discard it > afterwards? > > I'll assume that you'd answer that it's enough to just be able to print > it out. In that case, you just need some well placed print statements. > Each time you come to a line with a zero in it, you have enough > information to print out one student's information. And in this case, > you don't need a list of students, just the name of the current one. > > Do you expect any numbers to be non-integers? I'd assume so because you > used the float() function instead of int(). But isdigit() is going to > be a problem if there's a decimal in there. > > DaveA > > From davea at ieee.org Sun Jul 26 12:57:19 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 26 Jul 2009 06:57:19 -0400 Subject: [Tutor] Reading Data From File In-Reply-To: <50e459210907260257v59540abblbefd4b79b01bba48@mail.gmail.com> References: <00163630f5c96d364f046f8c1ca7@google.com> <4A6B7B33.9020702@dejaviewphoto.com> <50e459210907260257v59540abblbefd4b79b01bba48@mail.gmail.com> Message-ID: <4A6C368F.7070505@ieee.org> Chris Castillo wrote: > ya i was kind of in a hurry composing the email earlier. sorry for the > typos and misunderstanding. This is what I actually have. > > grades = [] > names = [] > gradeTotal = 0 > numStudents = 0 > > inputFile = open("input.txt", "r") > > for line in inputFile: > if line.strip().isdigit(): > grade = float(line) > if grade != 0.0: > gradeTotal += grade > grade = grades.append(grade) > else: > name = line.strip() > name = names.append(name) > > > So even If I take the stuff out that you said, My structure still > wouldn't be right because I'm processing everything all at once with > no way to reference any of the grades with the student. How do I > structure this differently to do that? That's what I'm having trouble > with. > > On 7/25/09, Dave Angel wrote: > >> ctcast at gmail.com wrote: >> >>> grades = [] >>> names = [] >>> gradeTotal = 0 >>> numStudents = 0 >>> >>> inputFile = open("input.txt", "r" >>> >>> for line in inputFile: >>> if line.strip().isdigit(): >>> grade = float(line) >>> if grade != 0.0: >>> gradeTotal += grade >>> grade = grades.append(grade) >>> else: >>> name = line.strip() >>> name = names.append(name) >>> >>> This just loops over the entire file basically and just continually >>> adds the grades to the grades list and names to the names list. How do >>> I just process each student's set of grades before moving on to the >>> next one (since there is a zero terminating value telling the loop >>> that a new student and his or her grades are about to follow) >>> >>> By the way I'm not worrying about determining the letter grade average >>> right now, i'm importing a module I wrote after I figure this part out. >>> >>> On Jul 25, 2009 8:34am, bob gailer wrote: >>> >>>> I concur with wesley and dave re homework. >>>> >>> >>> >>> >> There are syntax errors of at least two kinds here. The first is you're >> missing a trailing parenthesis. And the second is you lost all your >> indentation when you retyped the code. It'd really be better if you >> pasted the actual code instead. Not much of a problem in this case, at >> least if I guess the same as you had, but in many cases the indentation >> *is* the problem. >> >> Next problem is that you're assuming that list.append() returns >> something useful. It doesn't return anything, which is to say it returns >> "None." So it's not useful to do: >> grade = grades.append(grade) >> >> just leave off the left half of that. And likewise leave off the name= >> from the other call to append(). >> >> The next problem is that you have two independent lists, but no way to >> correlate which elements of one correspond to which elements of the >> other. So you have a choice to make. Do you need all the data for >> post-processing, or is it enough that you print it out, and discard it >> afterwards? >> >> I'll assume that you'd answer that it's enough to just be able to print >> it out. In that case, you just need some well placed print statements. >> Each time you come to a line with a zero in it, you have enough >> information to print out one student's information. And in this case, >> you don't need a list of students, just the name of the current one. >> >> Do you expect any numbers to be non-integers? I'd assume so because you >> used the float() function instead of int(). But isdigit() is going to >> be a problem if there's a decimal in there. >> >> DaveA >> >> >> (In a mailing list like this one, putting a response at the top of your message is called top-posting, and makes it harder for the next person to see the sequence of messages.) As I said before: *So you have a choice to make. Do you need all the data for post-processing, or is it enough that you print it out, and discard it afterwards?* I tried to assume an answer, but it looks like you stopped reading before that point. So I'll try again, with a little more detail. Each time you come to a line with a zero in it, you have enough information to print out one student's information. You know the current student, you know all his scores. So you could print it out at that point in the loop, rather than waiting till the entire program is past. If you're not sure what I'm talking about, first put in a test for the 0 line. Add in a single print that prints out name and grades at that point. You do know that you can print a list, just the same as any other variable? Once you see you have enough data at that point, you'll have to make a minor change to eliminate this student's data from getting printed again for the next one. Then it's just a question of formatting the print nicely. So you replace the single print with a function call, passing it the name and grades, and format the information in that function. And if you won't try what I said, then at least answer the question. DaveA From ceasar102 at yahoo.com Sun Jul 26 13:23:19 2009 From: ceasar102 at yahoo.com (ammar azif) Date: Sun, 26 Jul 2009 04:23:19 -0700 (PDT) Subject: [Tutor] Need help in making this code more pythonic Message-ID: <505096.28381.qm@web56807.mail.re3.yahoo.com> Hello, I need some suggestions on how to make this code pythonic. The program basically runs a simulation of an object that moves on a 2D plane. The object keeps on moving from its current coordinate to? randomly picked adjacent coordinates with the object is not allowed to move move to a previously covered coordinate point as the rule. If the object is unable to move the program will terminate. Some of the concerns I have in mind is the code in the move method in Person class. I am sure there are some built-in methods or features in python that I could use to improve the implementation of that method. Hope you guys can enlighten me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ceasar102 at yahoo.com Sun Jul 26 13:35:18 2009 From: ceasar102 at yahoo.com (ammar azif) Date: Sun, 26 Jul 2009 04:35:18 -0700 (PDT) Subject: [Tutor] Need help in making this code more pythonic Message-ID: <302638.67834.qm@web56802.mail.re3.yahoo.com> Sorry I forgot to attach the code file. Here it is. --- On Sun, 7/26/09, ammar azif wrote: From: ammar azif Subject: [Tutor] Need help in making this code more pythonic To: tutor at python.org Date: Sunday, July 26, 2009, 6:23 AM Hello, I need some suggestions on how to make this code pythonic. The program basically runs a simulation of an object that moves on a 2D plane. The object keeps on moving from its current coordinate to? randomly picked adjacent coordinates with the object is not allowed to move move to a previously covered coordinate point as the rule. If the object is unable to move the program will terminate. Some of the concerns I have in mind is the code in the move method in Person class. I am sure there are some built-in methods or features in python that I could use to improve the implementation of that method. Hope you guys can enlighten me. -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: personmoving.py Type: text/x-python Size: 2493 bytes Desc: not available URL: From ldl08 at gmx.net Sun Jul 26 13:35:45 2009 From: ldl08 at gmx.net (David) Date: Sun, 26 Jul 2009 19:35:45 +0800 Subject: [Tutor] sqlite: don't understand a code snippet In-Reply-To: References: <4A6B3E35.3020304@gmx.net> Message-ID: <4A6C3F91.5050602@gmx.net> Rich, thanks a lot -- that was the problem. David Rich Lovely wrote: > 2009/7/25 David : > >> Dear tutors, >> >> I am trying to teach myself the way Python's works with databases. >> I decided to start with SQLite, and am looking at Summerfield's >> 'Programming in Python 3'. >> I got a code snippet that I don't fully understand (the comments are mine): >> >> >> def get_and_set_director(db, director): >> # try to fetch existing director ID from db >> director_id = get_director_id(db, director) >> # if director ID was found in db, return ID >> if director_id is not None: >> return director_id >> cursor = db.cursor() >> # insert new director record >> cursor.execute("INSERT INTO directors (name) VALUES (?)", >> (director,)) >> db.commit() >> # retrieve and return new director ID from db >> return get_director_id(db, director) >> >> Here is what I think is going on: >> >> The function get_and_set_director() gets the director ID from the db >> by calling the function get_director-id() and returns its value. >> >> If the director ID is not in the db then, from outside the >> get_and_set_director() function, the ID gets inserted to the db via >> the commit() method. Finally, the director ID is returned (from the db) >> by once again calling the get_director_id() function. >> >> Question: where does a new the director ID come from? >> >> Thanks for your directions! >> >> David >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > It sounds as if the directors table has an AUTO_INCREMENT column, > which will automatically assign itself the next value sequentially > when you insert an entry into the table. i.e. The first inserted > entry gets an ID of 1, the next 2, and so on. This is stored in a > column in the table. The get_director_id(...) function will do > something like the following query: > > cursor.execute("SELECT id FROM directors WHERE name == \"%s\"", (name,)) > > I don't know how well I've explained it, but this is the normal > technique for generating unique ids for rows in a database. > > From davea at ieee.org Sun Jul 26 13:49:36 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 26 Jul 2009 07:49:36 -0400 Subject: [Tutor] First code snipet In-Reply-To: References: <1248570147.28544.249.camel@andi-lap> Message-ID: <4A6C42D0.7000900@ieee.org> Darth Kaboda wrote: > > > >> Subject: Re: [Tutor] First code snipet >> From: andreas at kostyrka.org >> To: darthkaboda at msn.com >> CC: tutor at python.org >> Date: Sun, 26 Jul 2009 03:02:27 +0200 >> >> Some things: >> >> 1) It's Python, not Phython. >> 2) Slightly shorter solution to your problem: >> >> import random >> >> input = range(53) >> random.shuffle(input) >> print input >> >> 3) The important part here is that reimplementing something that is in >> the standard library does not make sense usually. >> >> 4) A more sensible implementation of shuffle comes directly out of >> random.py: >> >> def shuffle(self, x, random=None, int=int): >> """x, random=random.random -> shuffle list x in place; return >> None. >> >> Optional arg random is a 0-argument function returning a random >> float in [0.0, 1.0); by default, the standard random.random. >> """ >> >> if random is None: >> random = self.random >> for i in reversed(xrange(1, len(x))): >> # pick an element in x[:i+1] with which to exchange x[i] >> j = int(random() * (i+1)) >> x[i], x[j] = x[j], x[i] >> >> Notice that it is not exactly optimal, one could easily replace the >> reversed(xrange()) expression with a 3 parameter version of xrange: >> for i in xrange(len(x) - 1, 0, -1): >> >> Andreas >> >> >> >> Am Samstag, den 25.07.2009, 17:15 -0700 schrieb Darth Kaboda: >> >>> I'm starting to learn Python as it seems to be adopted by many >>> companies that I've been looking to apply to. I used the book Learning >>> Phython to get the basics of the language and many of the gotcha's. I >>> think I know enough of the basic features of the language to start >>> playing around and can understand most code I've seen so far by >>> looking at some of the posts here. >>> >>> The one worry I have is not coding things the Phython way as I've been >>> a Visual Basic programmer for so long and a C++ programmer before >>> that. So would like to have people look at a simplistic class >>> (shuffles lists of objects wrote it for shuffling cards but >>> with Phython could be used for any "list" type object) I wrote to give >>> me some feedback on the style of it. >>> >>> Any feedback is appreciated. >>> >>> Thanks, >>> Brian >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> > > > > Thanks for the correction not sure why I typed it that way after typing it correctly in the first sentence, must have wondered off somewhere in my mind I guess. > > > > Oops I guess I should have also mentioned what I was trying to accomplish with this class. I wanted to mimic how a deck of cards get's shuffled in the real world. i.e. split the deck and shuffle the two halves together. > > > > Brian > > > > > Good point. It is important to state your goal for the code, preferably in comments in your code, as well as in the message asking us the question. Suggest you include a doc-string for each class and method declaration. But it's important to tell us how you expect to use it, as well. If it's for your own learning, then it's pretty good as it is. But if you intend to show it to prospective employers, there are a lot of ways to clean it up. So... Unlike Java, not everything needs to be in a class. This shuffler class accomplishes nothing that the module doesn't already do. The only instance attribute you use is rgen, and that could just as readily have been a global (visible within the entire module). Naming is important. I think I would have factored it into three functions cut() and ripple(). shuffle() simply calls cut(), then ripple(). You need to know the library better. Andreas already mentioned the std library random.shuffle(), and you correctly explained why you didn't use it. But there are other library functions that would make your code more concise, more readable, and maybe faster. Starting with shuffle() (which I'd call ripple()) Because Python makes it easy to swap two variables in-place, it's common to swap arguments directly, rather than copy them to local attributes. So I'd replace the first 4 lines with: if self.rgen.randint(0,1): #randomly decide which pile is shuffled down first inpile2, inpile1 = inpile1, inpile2 len() is very fast, so there's no need for a separate variable to keep track of the lengths of inpile1 and inpile2. So eliminate all refs to pile1c and pile2. In the while, just use while len(inpile1) and len(inpile2): Lists have no type associated with them. Each object in a list has its own type. So there's no meaning to constructing an empty list out of another one. rpile = [] pop(0) is slow, compared with pop(-1). If you used the latter, you would have to do a reverse on the list when you were done to keep the realism. And that would make the code less readable. So I think this is an unnecessary optimization. But keep it in mind if you're ever dealing with thousands of items in a list. Peeling them off from the front one at a time will be slow. The logic of popping a random number of cards from one list, and appending them to the result could be done the same way you do the cut(), using slices. I think it would be worth it if you made a separate function out of it, to call from whichever deck was being operated on. Where you do the if i < pile1c you could instead use the min() function. i = min(len(inpile1), self.rgen.randint(1,4)) At the end of the function, the if pile1c: elif ... logic could be replaced by rpile.extend(inpile1).extend(inpile2) as there's no harm in extending with an empty list. HTH, DaveA From alan.gauld at btinternet.com Sun Jul 26 14:53:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Jul 2009 13:53:15 +0100 Subject: [Tutor] First code snipet References: <1248570147.28544.249.camel@andi-lap> <4A6C42D0.7000900@ieee.org> Message-ID: "Dave Angel" wrote > len() is very fast, so there's no need for a separate variable to keep > track of the lengths of inpile1 and inpile2. So eliminate all refs to > pile1c and pile2. In the while, just use > while len(inpile1) and len(inpile2): Or even simpler: while inpile1 and inpile2: An empty list is false too. > pop(0) is slow, compared with pop(-1). I didn't know that, but timing seems to suggest about 50% slower. Interesting. Alan G. From roadierich at googlemail.com Sun Jul 26 16:38:52 2009 From: roadierich at googlemail.com (Rich Lovely) Date: Sun, 26 Jul 2009 15:38:52 +0100 Subject: [Tutor] Need help in making this code more pythonic In-Reply-To: <302638.67834.qm@web56802.mail.re3.yahoo.com> References: <302638.67834.qm@web56802.mail.re3.yahoo.com> Message-ID: > --- On Sun, 7/26/09, ammar azif wrote: > > From: ammar azif > Subject: [Tutor] Need help in making this code more pythonic > To: tutor at python.org > Date: Sunday, July 26, 2009, 6:23 AM > > Hello, > > I need some suggestions on how to make this code pythonic. The program > basically runs a simulation of an object that moves on a 2D plane. The > object keeps on moving from its current coordinate to? randomly picked > adjacent coordinates with the object is not allowed to move move to a > previously covered coordinate point as the rule. If the object is unable to > move the program will terminate. Some of the concerns I have in mind is the > code in the move method in Person class. I am sure there are some built-in > methods or features in python that I could use to improve the implementation > of that method. Hope you guys can enlighten me. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > A Couple of pointers: Rather than having a dict with all values == None, you can use a set (which is effectively the same thing, but looks cleaner and is easier to read). Us the "k in d" operator rather than d.has_key(k) x = position[0] y = position[1] is more pythonically written x,y = position using tuple unpacking. rather than using cannot_move = True and then if cannot_move: You'd be more pythonic to use if not potential_positions: An empty list is false in a boolean context, a list with one or more items is true. Rather than using random.rand_int(len(...)) to generate an index, you can go straight to the result by using random.choice(...) You might also want to add some docstrings to your class and its move method, so that you can tell at a glance what the class does. A docstring is simple a string on the first (non-blank) line after the definition: def move(self): "Moves person one space in a random direction. It is not permitted to move to a previous occupied position" Finally, you might want to put the code doing the actual work into a "if __name__ == "__main__": block, so that you can import the script as a module, and not get extra output. Take a look at some of the files in the standard library to see what I mean. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. From davidwilson at Safe-mail.net Sun Jul 26 16:33:31 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Sun, 26 Jul 2009 10:33:31 -0400 Subject: [Tutor] renaming files within a directory Message-ID: Hello, I have a directory containing svg/Flag_of_United_States.svg etc... Flag_of_the_Seychelles.svg Flag_of_the_Solomon_Islands.svg Flag_of_the_United_Arab_Emirates.svg Flag_of_the_United_Kingdom.svg Flag_of_the_United_States.svg Flag_of_the_Vatican_City.svg Also I have a CSV file like "us", "United States" "es", "Spain" .... How can I rename the svg files so that they become: flag-us.svg flag-es.svg etc.. David From mail at timgolden.me.uk Sun Jul 26 17:13:38 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 26 Jul 2009 16:13:38 +0100 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6C72A2.1030309@timgolden.me.uk> davidwilson at Safe-mail.net wrote: > Hello, > I have a directory containing svg/Flag_of_United_States.svg etc... > > > Flag_of_the_Seychelles.svg > Flag_of_the_Solomon_Islands.svg > Flag_of_the_United_Arab_Emirates.svg > Flag_of_the_United_Kingdom.svg > Flag_of_the_United_States.svg > Flag_of_the_Vatican_City.svg > > > Also I have a CSV file like > > "us", "United States" > "es", "Spain" > > .... > > How can I rename the svg files so that they become: > > flag-us.svg > flag-es.svg This is one of those ones where it helps if you have a go first and tell us how far you got, or where the problem lies. Otherwise you're likely to get a lot of sarcastically helpful replies along the lines of: move Flag_of_the_Seychelles.svg flag-sc.svg To get you started if you're nowhere at the moment, you want to create a dictionary from your csv which maps the long name to the short name so that can then parse the file name to find the long name, use the dictionary to find the short name, and then issue a rename command to the new name. TJG From davidwilson at Safe-mail.net Sun Jul 26 18:08:50 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Sun, 26 Jul 2009 12:08:50 -0400 Subject: [Tutor] renaming files within a directory Message-ID: OK, I know that. Here is what I have so far, but I get stuck on the mapping of the filename with the csv file. >>> import os >>> files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')] >>> files ['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 'Flag_of_Armenia.svg', 'Flag_of_Australia.svg'] >>> import csv >>> reader = csv.reader(open("country.csv")) >>> for row in reader: ... print row ['"km";"Comoros"'] ['"dj";"Djibouti"'] ['"er";"Eritrea"'] ['"et";"Ethiopia"'] .... Here is where I am at. Not sure how to map the two. Dave -------- Original Message -------- From: Tim Golden Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org To: Cc: tutor at python.org Subject: Re: [Tutor] renaming files within a directory Date: Sun, 26 Jul 2009 16:13:38 +0100 > davidwilson at Safe-mail.net wrote: > > Hello, > > I have a directory containing svg/Flag_of_United_States.svg etc... > > > > > > Flag_of_the_Seychelles.svg > > Flag_of_the_Solomon_Islands.svg > > Flag_of_the_United_Arab_Emirates.svg > > Flag_of_the_United_Kingdom.svg > > Flag_of_the_United_States.svg > > Flag_of_the_Vatican_City.svg > > > > > > Also I have a CSV file like > > > > "us", "United States" > > "es", "Spain" > > > > .... > > > > How can I rename the svg files so that they become: > > > > flag-us.svg > > flag-es.svg > > > This is one of those ones where it helps if you have > a go first and tell us how far you got, or where > the problem lies. Otherwise you're likely to get > a lot of sarcastically helpful replies along the lines > of: > > move Flag_of_the_Seychelles.svg flag-sc.svg > > > To get you started if you're nowhere at the moment, > you want to create a dictionary from your csv which maps > the long name to the short name so that can then > parse the file name to find the long name, use the > dictionary to find the short name, and then issue > a rename command to the new name. > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Sun Jul 26 19:32:43 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 26 Jul 2009 18:32:43 +0100 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6C933B.4080207@timgolden.me.uk> davidwilson at Safe-mail.net wrote: > Here is what I have so far, but I get stuck on the mapping of the filename with the csv file. > >>>> import os >>>> files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')] >>>> files > ['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 'Flag_of_Armenia.svg', 'Flag_of_Australia.svg'] > >>>> import csv >>>> reader = csv.reader(open("country.csv")) >>>> for row in reader: > ... print row > > ['"km";"Comoros"'] > ['"dj";"Djibouti"'] > ['"er";"Eritrea"'] > ['"et";"Ethiopia"'] > .... > > Here is where I am at. > Not sure how to map the two. OK. Good stuff so far. You may not actually need that auxiliary list of files, but no problem really. Are you familiar with a dictionary in Python? It maps a key to a value. Here, you want the long names to be the keys and the short names to be values. If you were putting them together by hand (as a constant) it would look something like this: countries = { "Comoros" : "km", "Ethiopia" : "et", } and you could look up like this: ethiopia_tld = countries['Ethiopia'] So what you have to do is to use one of the dictionary constructors (hint: help (dict)) to create a dictionary out of the list of lists which you csv reader produced. You'll need to swap the elements round as the csv has the code first, but you want the country first. Does that take you any further forward? TJG From ctcast at gmail.com Sun Jul 26 21:27:18 2009 From: ctcast at gmail.com (Chris Castillo) Date: Sun, 26 Jul 2009 14:27:18 -0500 Subject: [Tutor] Reading Data From File In-Reply-To: <4A6C368F.7070505@ieee.org> References: <00163630f5c96d364f046f8c1ca7@google.com> <4A6B7B33.9020702@dejaviewphoto.com> <50e459210907260257v59540abblbefd4b79b01bba48@mail.gmail.com> <4A6C368F.7070505@ieee.org> Message-ID: <50e459210907261227x75abac4aq1f317279ab34d944@mail.gmail.com> On 7/26/09, Dave Angel wrote: > Chris Castillo wrote: >> ya i was kind of in a hurry composing the email earlier. sorry for the >> typos and misunderstanding. This is what I actually have. >> >> grades = [] >> names = [] >> gradeTotal = 0 >> numStudents = 0 >> >> inputFile = open("input.txt", "r") >> >> for line in inputFile: >> if line.strip().isdigit(): >> grade = float(line) >> if grade != 0.0: >> gradeTotal += grade >> grade = grades.append(grade) >> else: >> name = line.strip() >> name = names.append(name) >> >> >> So even If I take the stuff out that you said, My structure still >> wouldn't be right because I'm processing everything all at once with >> no way to reference any of the grades with the student. How do I >> structure this differently to do that? That's what I'm having trouble >> with. >> >> On 7/25/09, Dave Angel wrote: >> >>> ctcast at gmail.com wrote: >>> >>>> grades = [] >>>> names = [] >>>> gradeTotal = 0 >>>> numStudents = 0 >>>> >>>> inputFile = open("input.txt", "r" >>>> >>>> for line in inputFile: >>>> if line.strip().isdigit(): >>>> grade = float(line) >>>> if grade != 0.0: >>>> gradeTotal += grade >>>> grade = grades.append(grade) >>>> else: >>>> name = line.strip() >>>> name = names.append(name) >>>> >>>> This just loops over the entire file basically and just continually >>>> adds the grades to the grades list and names to the names list. How do >>>> I just process each student's set of grades before moving on to the >>>> next one (since there is a zero terminating value telling the loop >>>> that a new student and his or her grades are about to follow) >>>> >>>> By the way I'm not worrying about determining the letter grade average >>>> right now, i'm importing a module I wrote after I figure this part out. >>>> >>>> On Jul 25, 2009 8:34am, bob gailer wrote: >>>> >>>>> I concur with wesley and dave re homework. >>>>> >>>> >>>> >>>> >>> There are syntax errors of at least two kinds here. The first is you're >>> missing a trailing parenthesis. And the second is you lost all your >>> indentation when you retyped the code. It'd really be better if you >>> pasted the actual code instead. Not much of a problem in this case, at >>> least if I guess the same as you had, but in many cases the indentation >>> *is* the problem. >>> >>> Next problem is that you're assuming that list.append() returns >>> something useful. It doesn't return anything, which is to say it returns >>> "None." So it's not useful to do: >>> grade = grades.append(grade) >>> >>> just leave off the left half of that. And likewise leave off the name= >>> from the other call to append(). >>> >>> The next problem is that you have two independent lists, but no way to >>> correlate which elements of one correspond to which elements of the >>> other. So you have a choice to make. Do you need all the data for >>> post-processing, or is it enough that you print it out, and discard it >>> afterwards? >>> >>> I'll assume that you'd answer that it's enough to just be able to print >>> it out. In that case, you just need some well placed print statements. >>> Each time you come to a line with a zero in it, you have enough >>> information to print out one student's information. And in this case, >>> you don't need a list of students, just the name of the current one. >>> >>> Do you expect any numbers to be non-integers? I'd assume so because you >>> used the float() function instead of int(). But isdigit() is going to >>> be a problem if there's a decimal in there. >>> >>> DaveA >>> >>> >>> > (In a mailing list like this one, putting a response at the top of your > message is called top-posting, and makes it harder for the next person > to see the sequence of messages.) > > As I said before: > *So you have a choice to make. Do you need all the data for > post-processing, or is it enough that you print it out, and discard it > afterwards?* > > I tried to assume an answer, but it looks like you stopped reading > before that point. So I'll try again, with a little more detail. > > Each time you come to a line with a zero in it, you have enough > information to print out one student's information. You know the > current student, you know all his scores. So you could print it out at > that point in the loop, rather than waiting till the entire program is past. > > If you're not sure what I'm talking about, first put in a test for the 0 > line. Add in a single print that prints out name and grades at that > point. You do know that you can print a list, just the same as any > other variable? > > > Once you see you have enough data at that point, you'll have to make a > minor change to eliminate this student's data from getting printed again > for the next one. > > Then it's just a question of formatting the print nicely. So you > replace the single print with a function call, passing it the name and > grades, and format the information in that function. > > And if you won't try what I said, then at least answer the question. > > DaveA > > No I didn't stop reading your reply. I just figured since I said in my original post of my problem that I needed to process the information for one student before moving on to the next that you wouldn't disregard that information. From davidwilson at Safe-mail.net Sun Jul 26 21:34:09 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Sun, 26 Jul 2009 15:34:09 -0400 Subject: [Tutor] renaming files within a directory Message-ID: OK I am lost ;( I changed the code to: >>> reader = csv.reader(open("countries.csv"), delimiter=";") >>> for row in reader: ... print row ... ['bi', 'Burundi'] ['km', 'Comoros'] ['dj', 'Djibouti'] ['er', 'Eritrea'] ... Now each row is a list with two items each. But when I do this: >>> dic = [] >>> for row in reader: ... newdic.append({row[0]: row[1]}) ... >>> dic [] I get an empty dictionary -------- Original Message -------- From: Tim Golden Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org To: Cc: tutor at python.org Subject: Re: [Tutor] renaming files within a directory Date: Sun, 26 Jul 2009 18:32:43 +0100 > davidwilson at Safe-mail.net wrote: > > Here is what I have so far, but I get stuck on the mapping of the filename with the csv file. > > > >>>> import os > >>>> files = [file for file in os.listdir(os.getcwd()) if file.endswith('svg')] > >>>> files > > ['Flag_of_Abkhazia.svg', 'Flag_of_Afghanistan.svg', 'Flag_of_Albania.svg', 'Flag_of_Algeria.svg', 'Flag_of_Andorra.svg', 'Flag_of_Angola.svg', 'Flag_of_Antigua_and_Barbuda.svg', 'Flag_of_Argentina.svg', 'Flag_of_Armenia.svg', 'Flag_of_Australia.svg'] > > > >>>> import csv > >>>> reader = csv.reader(open("country.csv")) > >>>> for row in reader: > > ... print row > > > > ['"km";"Comoros"'] > > ['"dj";"Djibouti"'] > > ['"er";"Eritrea"'] > > ['"et";"Ethiopia"'] > > .... > > > > Here is where I am at. > > Not sure how to map the two. > > > OK. Good stuff so far. You may not actually need > that auxiliary list of files, but no problem really. > > Are you familiar with a dictionary in Python? It maps > a key to a value. Here, you want the long names to > be the keys and the short names to be values. If you > were putting them together by hand (as a constant) > it would look something like this: > > countries = { > "Comoros" : "km", > "Ethiopia" : "et", > } > > and you could look up like this: > > ethiopia_tld = countries['Ethiopia'] > > So what you have to do is to use one of the dictionary > constructors (hint: help (dict)) to create a dictionary > out of the list of lists which you csv reader produced. > You'll need to swap the elements round as the csv has > the code first, but you want the country first. > > Does that take you any further forward? > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Sun Jul 26 21:41:10 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 26 Jul 2009 20:41:10 +0100 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6CB156.6090606@timgolden.me.uk> davidwilson at Safe-mail.net wrote: > OK I am lost ;( > > I changed the code to: > >>>> reader = csv.reader(open("countries.csv"), delimiter=";") >>>> for row in reader: > ... print row > ... > ['bi', 'Burundi'] > ['km', 'Comoros'] > ['dj', 'Djibouti'] > ['er', 'Eritrea'] > > ... > > Now each row is a list with two items each. > > But when I do this: > >>>> dic = [] >>>> for row in reader: > ... newdic.append({row[0]: row[1]}) > ... >>>> dic > [] > > I get an empty dictionary Well, you actually get an empty list :) To instantiate an empty dictionary, you use curly brackets: d = {} To add something to a dictionary, you use: d[] = Try something like this: import csv reader = csv.reader(open("countries.csv"), delimiter=";") countries = {} # note the curly brackets for row in reader: code, name = row # handy Python tuple unpacking countries[name] = code Once you're used to the idea, you can get reasonably slick with dictionary initialisers and generator expressions: import csv reader = csv.reader(open("countries.csv"), delimiter=";") countries = dict ((row[1], row[0]) for row in reader) And once you're really confident (and if you're a fan of one-liners) you can get away with this: import csv countries = dict ( (name, code) for \ (code, name) in \ csv.reader (open ("countries.csv"), delimiter=";") ) BTW, I tend to open csv files with "rb" as it seems to avoid line-ending issues with the csv module. YMMV. TJG From j8ooth at gmail.com Sun Jul 26 22:33:19 2009 From: j8ooth at gmail.com (j booth) Date: Sun, 26 Jul 2009 16:33:19 -0400 Subject: [Tutor] simple text replace Message-ID: <1afd95d30907261333s20387fd8p3d8cb42f0d1dc49a@mail.gmail.com> Hello, I am scanning a text file and replacing words with alternatives. My difficulty is that all occurrences are replaced (even if they are part of another word!).. This is an example of what I have been using: for line in fileinput.FileInput("test_file.txt",inplace=1): > line = line.replace(original, new) > print line, > fileinput.close() original and new are variables that have string values from functions.. original finds each word in a text file and old is a manipulated replacement. Essentially, I would like to replace only the occurrence that is currently selected-- not the rest. for example: python is great, but my python knowledge is limited! regardless, I enjoy > pythonprogramming returns something like: snake is great, but my snake knowledge is limited! regardless, I enjoy > snakeprogramming thanks so much! -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Mon Jul 27 00:05:33 2009 From: pine508 at hotmail.com (Che M) Date: Sun, 26 Jul 2009 18:05:33 -0400 Subject: [Tutor] simple text replace In-Reply-To: <1afd95d30907261333s20387fd8p3d8cb42f0d1dc49a@mail.gmail.com> References: <1afd95d30907261333s20387fd8p3d8cb42f0d1dc49a@mail.gmail.com> Message-ID: > I am scanning a text file and replacing words with alternatives. My difficulty > is that all occurrences are replaced (even if they are part of another word!).. Could you search for the string ' word ' with the white spaces around it? Shouldn't that only replace words that are not part of another word? > Essentially, I would like to replace only the occurrence that is currently > selected-- not the rest. for example: What do you mean by a word being "currently selected"? That phrase and "scanning a text file" don't make sense to me together. How is the user reading the text to select the word that is to be replaced? (Or maybe I am not understanding something?) CM _________________________________________________________________ Bing? brings you maps, menus, and reviews organized in one place. Try it now. http://www.bing.com/search?q=restaurants&form=MLOGEN&publ=WLHMTAG&crea=TXT_MLOGEN_Local_Local_Restaurants_1x1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From j8ooth at gmail.com Mon Jul 27 00:23:01 2009 From: j8ooth at gmail.com (j booth) Date: Sun, 26 Jul 2009 18:23:01 -0400 Subject: [Tutor] simple text replace In-Reply-To: References: <1afd95d30907261333s20387fd8p3d8cb42f0d1dc49a@mail.gmail.com> Message-ID: <1afd95d30907261523j53799604k5385bca52fd7d008@mail.gmail.com> oops, I mean that the script opens a file and splits it into words; Then it takes each word and searches for an alternative online; with the alternative now stored in a variable, it simply needs to be written back over the original word in the same file. at the moment this might solve the problem, but I need to make sure: for line in fileinput.FileInput("test_file.txt",inplace=1): > line = line.replace(original, new, 1) > > does this make more sense? On Sun, Jul 26, 2009 at 6:05 PM, Che M wrote: > > > I am scanning a text file and replacing words with alternatives. My > difficulty > > is that all occurrences are replaced (even if they are part of another > word!).. > > Could you search for the string ' word ' with the white spaces around it? > Shouldn't > that only replace words that are not part of another word? > > > Essentially, I would like to replace only the occurrence that is > currently > > selected-- not the rest. for example: > > What do you mean by a word being "currently selected"? That phrase and > "scanning a text file" don't make sense to me together. How is the user > reading the text to select the word that is to be replaced? (Or maybe I am > not understanding something?) > > CM > > ------------------------------ > Bing? brings you maps, menus, and reviews organized in one place. Try it > now. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Jul 27 00:41:35 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 26 Jul 2009 18:41:35 -0400 Subject: [Tutor] simple text replace In-Reply-To: <1afd95d30907261333s20387fd8p3d8cb42f0d1dc49a@mail.gmail.com> References: <1afd95d30907261333s20387fd8p3d8cb42f0d1dc49a@mail.gmail.com> Message-ID: <4A6CDB9F.6080006@ieee.org> j booth wrote: > Hello, > > I am scanning a text file and replacing words with alternatives. My > difficulty is that all occurrences are replaced (even if they are part of > another word!).. > > This is an example of what I have been using: > > for line in fileinput.FileInput("test_file.txt",inplace=1): > >> line = line.replace(original, new) >> print line, >> fileinput.close() >> > > > original and new are variables that have string values from functions.. > original finds each word in a text file and old is a manipulated > replacement. Essentially, I would like to replace only the occurrence that > is currently selected-- not the rest. for example: > > python is great, but my python knowledge is limited! regardless, I enjoy > >> pythonprogramming >> > > > returns something like: > > snake is great, but my snake knowledge is limited! regardless, I enjoy > >> snakeprogramming >> > > > thanks so much! > > Not sure what you mean by "currently selected," you're processing a line at a time, and there are multiple legitimate occurrences of the word in the line. The trick is to define what you mean by "word." replace() has no such notion. So we want to write a function such as: given three strings, line, inword, and outword. Find all occurrences of inword in the line, and replace all of them with outword. The definition of word is a group of alphabetic characters (a-z perhaps) that is surrounded by non-alphabetic characters. The approach that I'd use is to prepare a translated copy of the line as follows: Replace each non-alphabetic character with a space. Also insert a space at the beginning and one at the end. Now, take the inword, and similarly add spaces at begin and end. Now search this modified line for all occurrences of this modified inword, and make a list of the indices where it is found. In your example line, there would be 2 items in the list. Now, using the original line, use that list of indices to substitute the outword in the appropriate places. Use slices to do it, preferably from right to left, so the indices will work even though the string is changing. (The easiest way to do right to left is to reverse() the list. DaveA From darthkaboda at msn.com Mon Jul 27 05:15:58 2009 From: darthkaboda at msn.com (Darth Kaboda) Date: Sun, 26 Jul 2009 20:15:58 -0700 Subject: [Tutor] First code snipet In-Reply-To: <4A6C42D0.7000900@ieee.org> References: <1248570147.28544.249.camel@andi-lap> <4A6C42D0.7000900@ieee.org> Message-ID: > Good point. It is important to state your goal for the code, preferably > in comments in your code, as well as in the message asking us the > question. Suggest you include a doc-string for each class and method > declaration. > > But it's important to tell us how you expect to use it, as well. If > it's for your own learning, then it's pretty good as it is. But if you > intend to show it to prospective employers, there are a lot of ways to > clean it up. > > > So... > > Unlike Java, not everything needs to be in a class. This shuffler class > accomplishes nothing that the module doesn't already do. The only > instance attribute you use is rgen, and that could just as readily have > been a global (visible within the entire module). > > Naming is important. I think I would have factored it into three > functions cut() and ripple(). shuffle() simply calls cut(), then ripple(). > > You need to know the library better. Andreas already mentioned the std > library random.shuffle(), and you correctly explained why you didn't use > it. But there are other library functions that would make your code > more concise, more readable, and maybe faster. > > Starting with shuffle() (which I'd call ripple()) > > Because Python makes it easy to swap two variables in-place, it's common > to swap arguments directly, rather than copy them to local attributes. > So I'd replace the first 4 lines with: > if self.rgen.randint(0,1): #randomly decide which pile is shuffled > down first > inpile2, inpile1 = inpile1, inpile2 > > len() is very fast, so there's no need for a separate variable to keep > track of the lengths of inpile1 and inpile2. So eliminate all refs to > pile1c and pile2. In the while, just use > while len(inpile1) and len(inpile2): > > Lists have no type associated with them. Each object in a list has its > own type. So there's no meaning to constructing an empty list out of > another one. > rpile = [] > > pop(0) is slow, compared with pop(-1). If you used the latter, you > would have to do a reverse on the list when you were done to keep the > realism. And that would make the code less readable. So I think this > is an unnecessary optimization. But keep it in mind if you're ever > dealing with thousands of items in a list. Peeling them off from the > front one at a time will be slow. > > The logic of popping a random number of cards from one list, and > appending them to the result could be done the same way you do the > cut(), using slices. I think it would be worth it if you made a > separate function out of it, to call from whichever deck was being > operated on. > > Where you do the if i < pile1c you could instead use the min() > function. > i = min(len(inpile1), self.rgen.randint(1,4)) > > At the end of the function, the if pile1c: elif ... logic could be > replaced by > rpile.extend(inpile1).extend(inpile2) > > as there's no harm in extending with an empty list. > > HTH, DaveA > Dave and Alan, Thank you for the advice and showing me some of the small nuances I haven't quite figured out yet. I used both of your suggestions to change the class the updated code is attached if you'd like to see. I tried putting the two extends in the same line and that didn't work as extend doesn't return anything so ended up putting them on consecutive lines without the if statement. Instead of doing the pop method I took your advice and tried it with slices instead along with extends. Shortened the code a bit. One note on pop method is pop() and pop(-1) the same thing? Looks like it based on what I've read but not 100% confident in that answer. On the class versus module I wasn't sure where I'd end up taking this idea so went ahead and coded it as a class. If I actually do much more with this, other then just as a coding exercise to help learn Python, I might be adding things to this or using it as a superclass. Examples of expansion ability to queue up decks, have multiple shufflers going at the same time in a program etc... So without knowing all the options in Python figured the class gave me the greatest flexibility. Yeah otherwise I'd have just made a module and still might switch it if I expand on this depending on what the needs turn out to be. Again thanks to everyone for looking at my code and the quick and helpful feedback. Hoping to do start coding a larger project soon so you'll probably get some questions from me. Thanks, Brian -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: shuffler2.py URL: From cynicalairrick at gmail.com Mon Jul 27 07:44:56 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Sun, 26 Jul 2009 22:44:56 -0700 Subject: [Tutor] Reading and Manipulating XML Data In-Reply-To: References: <5cd723fd0907242034y39e20c2ane64e9acfd7abddae@mail.gmail.com> Message-ID: <5cd723fd0907262244h4bb6357fjebe76f4ef74a6d8b@mail.gmail.com> Hi Alan, I'm liking how clean Element tree is, thanks for the quick reply! Nice definition by the way, I think its a bit clearer now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Jul 27 09:54:13 2009 From: rdmoores at gmail.com (Dick Moores) Date: Mon, 27 Jul 2009 00:54:13 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? Message-ID: I've taken a long break from Python, and now I want to try scripting with 2.62. I downloaded and installed 2.62, changed Win XP environmental variables to use Python26. Entering python at the command line shows I'm using 2.62: C:\Documents and Settings\Riley>python Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> So I'm able to try out the new features of 2.6 (I had been using 2.51), but I can't get IDLE to use 2.6. When I click on E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. And of course, the new 2.6 features don't work. Advice, please. Thanks, Dick Moores From fomcl at yahoo.com Mon Jul 27 10:10:41 2009 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 27 Jul 2009 01:10:41 -0700 (PDT) Subject: [Tutor] simple text replace In-Reply-To: <4A6CDB9F.6080006@ieee.org> Message-ID: <936455.35974.qm@web110708.mail.gq1.yahoo.com> Hi! Did you consider using a regex? import re re.sub("python\s", "snake ", "python is cool, pythonprogramming...") Cheers!! Albert-Jan --- On Mon, 7/27/09, Dave Angel wrote: > From: Dave Angel > Subject: Re: [Tutor] simple text replace > To: "j booth" > Cc: tutor at python.org > Date: Monday, July 27, 2009, 12:41 AM > j booth wrote: > > Hello, > > > > I am scanning a text file and replacing words with > alternatives. My > > difficulty is that all occurrences are replaced (even > if they are part of > > another word!).. > > > > This is an example of what I have been using: > > > >? ???for line in > fileinput.FileInput("test_file.txt",inplace=1): > >??? > >>? ? ? ???line = > line.replace(original, new) > >>? ? ? ???print line, > >>? ? ? > ???fileinput.close() > >>? ??? > > > > > > original and new are variables that have string values > from functions.. > > original finds each word in a text file and old is a > manipulated > > replacement. Essentially, I would like to replace only > the occurrence that > > is currently selected-- not the rest. for example: > > > > python is great, but my python knowledge is limited! > regardless, I enjoy > >??? > >> pythonprogramming > >>? ??? > > > > > > returns something like: > > > > snake is great, but my snake knowledge is limited! > regardless, I enjoy > >??? > >> snakeprogramming > >>? ??? > > > > > > thanks so much! > > > >??? > Not sure what you mean by "currently selected," you're > processing a line at a time, and there are multiple > legitimate occurrences of the word in the line. > > The trick is to define what you mean by "word."? > replace() has no such notion.? So we want to write a > function such as: > > given three strings, line, inword, and outword.? Find > all occurrences of inword in the line, and replace all of > them with outword.? The definition of word is a group > of alphabetic characters (a-z perhaps) that is surrounded by > non-alphabetic characters. > > The approach that I'd use is to prepare a translated copy > of the line as follows:???Replace each > non-alphabetic character with a space.? Also insert a > space at the beginning and one at the end.? Now, take > the inword, and similarly add spaces at begin and end.? > Now search this modified line for all occurrences of this > modified inword, and make a list of the indices where it is > found.? In your example line, there would be 2 items in > the list. > > Now, using the original line, use that list of indices to > substitute the outword in the appropriate places.? Use > slices to do it, preferably from right to left, so the > indices will work even though the string is changing.? > (The easiest way to do right to left is to reverse() the > list. > > DaveA > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From davidwilson at Safe-mail.net Mon Jul 27 11:10:49 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Mon, 27 Jul 2009 05:10:49 -0400 Subject: [Tutor] renaming files within a directory Message-ID: Here is what I have so far: import os import csv countries = {} reader = csv.reader(open("countries.csv")) for row in reader: code, name = row countries[name] = code files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) print len(files) for file in files: file = file.strip('.svg') print file # if countries.has_key(file): # print file When I run this I get: Flag_of_Uganda Flag_of_the_United_State Flag_of_Abkhazia Flag_of_Montenegro Flag_of_Qatar Flag_of_Gabon Flag_of_Uzbekistan Flag_of_Kiribati Flag_of_Armenia Flag_of_Panama Flag_of_Monaco Flag_of_Australia Flag_of_Liechtenstein Flag_of_Tunisia Flag_of_Georgia Flag_of_Palau Flag_of_the_Central_African_Republic ... The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State Also, How do I remove 'Flag_of', 'Flag_of_the_' I guess after this I can compare the value with the key and map the tld? Or is it better to use regex and then search from the list of countries? But how??? -------- Original Message -------- From: Tim Golden Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org To: Cc: tutor at python.org Subject: Re: [Tutor] renaming files within a directory Date: Sun, 26 Jul 2009 20:41:10 +0100 > davidwilson at Safe-mail.net wrote: > > OK I am lost ;( > > > > I changed the code to: > > > >>>> reader = csv.reader(open("countries.csv"), delimiter=";") > >>>> for row in reader: > > ... print row > > ... > > ['bi', 'Burundi'] > > ['km', 'Comoros'] > > ['dj', 'Djibouti'] > > ['er', 'Eritrea'] > > > > ... > > > > Now each row is a list with two items each. > > > > But when I do this: > > > >>>> dic = [] > >>>> for row in reader: > > ... newdic.append({row[0]: row[1]}) > > ... > >>>> dic > > [] > > > > I get an empty dictionary > > Well, you actually get an empty list :) > To instantiate an empty dictionary, you use curly brackets: > > d = {} > > To add something to a dictionary, you use: > > d[] = > > Try something like this: > > > import csv > > reader = csv.reader(open("countries.csv"), delimiter=";") > countries = {} # note the curly brackets > for row in reader: > code, name = row # handy Python tuple unpacking > countries[name] = code > > > > > Once you're used to the idea, you can get reasonably slick > with dictionary initialisers and generator expressions: > > import csv > > reader = csv.reader(open("countries.csv"), delimiter=";") > countries = dict ((row[1], row[0]) for row in reader) > > And once you're really confident (and if you're a > fan of one-liners) you can get away with this: > > import csv > countries = dict ( > (name, code) for \ > (code, name) in \ > csv.reader (open ("countries.csv"), delimiter=";") > ) > > > BTW, I tend to open csv files with "rb" as it seems to > avoid line-ending issues with the csv module. YMMV. > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From cwitts at compuscan.co.za Mon Jul 27 11:30:11 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 27 Jul 2009 11:30:11 +0200 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6D73A3.4000907@compuscan.co.za> davidwilson at Safe-mail.net wrote: > Here is what I have so far: > > import os > import csv > > countries = {} > reader = csv.reader(open("countries.csv")) > for row in reader: > code, name = row > countries[name] = code > > files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) > print len(files) > > for file in files: > file = file.strip('.svg') > print file > # if countries.has_key(file): > # print file > > When I run this I get: > > Flag_of_Uganda > Flag_of_the_United_State > Flag_of_Abkhazia > Flag_of_Montenegro > Flag_of_Qatar > Flag_of_Gabon > Flag_of_Uzbekistan > Flag_of_Kiribati > Flag_of_Armenia > Flag_of_Panama > Flag_of_Monaco > Flag_of_Australia > Flag_of_Liechtenstein > Flag_of_Tunisia > Flag_of_Georgia > Flag_of_Palau > Flag_of_the_Central_African_Republic > ... > > The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State > > Also, How do I remove 'Flag_of', 'Flag_of_the_' > > I guess after this I can compare the value with the key and map the tld? > > Or is it better to use regex and then search from the list of countries? But how??? > > -------- Original Message -------- > From: Tim Golden > Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org > To: > Cc: tutor at python.org > Subject: Re: [Tutor] renaming files within a directory > Date: Sun, 26 Jul 2009 20:41:10 +0100 > > >> davidwilson at Safe-mail.net wrote: >> >>> OK I am lost ;( >>> >>> I changed the code to: >>> >>> >>>>>> reader = csv.reader(open("countries.csv"), delimiter=";") >>>>>> for row in reader: >>>>>> >>> ... print row >>> ... >>> ['bi', 'Burundi'] >>> ['km', 'Comoros'] >>> ['dj', 'Djibouti'] >>> ['er', 'Eritrea'] >>> >>> ... >>> >>> Now each row is a list with two items each. >>> >>> But when I do this: >>> >>> >>>>>> dic = [] >>>>>> for row in reader: >>>>>> >>> ... newdic.append({row[0]: row[1]}) >>> ... >>> >>>>>> dic >>>>>> >>> [] >>> >>> I get an empty dictionary >>> >> Well, you actually get an empty list :) >> To instantiate an empty dictionary, you use curly brackets: >> >> d = {} >> >> To add something to a dictionary, you use: >> >> d[] = >> >> Try something like this: >> >> >> import csv >> >> reader = csv.reader(open("countries.csv"), delimiter=";") >> countries = {} # note the curly brackets >> for row in reader: >> code, name = row # handy Python tuple unpacking >> countries[name] = code >> >> >> >> >> Once you're used to the idea, you can get reasonably slick >> with dictionary initialisers and generator expressions: >> >> import csv >> >> reader = csv.reader(open("countries.csv"), delimiter=";") >> countries = dict ((row[1], row[0]) for row in reader) >> >> And once you're really confident (and if you're a >> fan of one-liners) you can get away with this: >> >> import csv >> countries = dict ( >> (name, code) for \ >> (code, name) in \ >> csv.reader (open ("countries.csv"), delimiter=";") >> ) >> >> >> BTW, I tend to open csv files with "rb" as it seems to >> avoid line-ending issues with the csv module. YMMV. >> >> TJG >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Strip will remove those characters until it hits a character not in the set. You could use file.split('.svg')[0] -- Kind Regards, Christian Witts From cwitts at compuscan.co.za Mon Jul 27 11:32:28 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 27 Jul 2009 11:32:28 +0200 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6D742C.7000903@compuscan.co.za> davidwilson at Safe-mail.net wrote: > Here is what I have so far: > > import os > import csv > > countries = {} > reader = csv.reader(open("countries.csv")) > for row in reader: > code, name = row > countries[name] = code > > files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) > print len(files) > > for file in files: > file = file.strip('.svg') > print file > # if countries.has_key(file): > # print file > > When I run this I get: > > Flag_of_Uganda > Flag_of_the_United_State > Flag_of_Abkhazia > Flag_of_Montenegro > Flag_of_Qatar > Flag_of_Gabon > Flag_of_Uzbekistan > Flag_of_Kiribati > Flag_of_Armenia > Flag_of_Panama > Flag_of_Monaco > Flag_of_Australia > Flag_of_Liechtenstein > Flag_of_Tunisia > Flag_of_Georgia > Flag_of_Palau > Flag_of_the_Central_African_Republic > ... > > The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State > > Also, How do I remove 'Flag_of', 'Flag_of_the_' > > I guess after this I can compare the value with the key and map the tld? > > Or is it better to use regex and then search from the list of countries? But how??? > > -------- Original Message -------- > From: Tim Golden > Apparently from: tutor-bounces+davidwilson=safe-mail.net at python.org > To: > Cc: tutor at python.org > Subject: Re: [Tutor] renaming files within a directory > Date: Sun, 26 Jul 2009 20:41:10 +0100 > > >> davidwilson at Safe-mail.net wrote: >> >>> OK I am lost ;( >>> >>> I changed the code to: >>> >>> >>>>>> reader = csv.reader(open("countries.csv"), delimiter=";") >>>>>> for row in reader: >>>>>> >>> ... print row >>> ... >>> ['bi', 'Burundi'] >>> ['km', 'Comoros'] >>> ['dj', 'Djibouti'] >>> ['er', 'Eritrea'] >>> >>> ... >>> >>> Now each row is a list with two items each. >>> >>> But when I do this: >>> >>> >>>>>> dic = [] >>>>>> for row in reader: >>>>>> >>> ... newdic.append({row[0]: row[1]}) >>> ... >>> >>>>>> dic >>>>>> >>> [] >>> >>> I get an empty dictionary >>> >> Well, you actually get an empty list :) >> To instantiate an empty dictionary, you use curly brackets: >> >> d = {} >> >> To add something to a dictionary, you use: >> >> d[] = >> >> Try something like this: >> >> >> import csv >> >> reader = csv.reader(open("countries.csv"), delimiter=";") >> countries = {} # note the curly brackets >> for row in reader: >> code, name = row # handy Python tuple unpacking >> countries[name] = code >> >> >> >> >> Once you're used to the idea, you can get reasonably slick >> with dictionary initialisers and generator expressions: >> >> import csv >> >> reader = csv.reader(open("countries.csv"), delimiter=";") >> countries = dict ((row[1], row[0]) for row in reader) >> >> And once you're really confident (and if you're a >> fan of one-liners) you can get away with this: >> >> import csv >> countries = dict ( >> (name, code) for \ >> (code, name) in \ >> csv.reader (open ("countries.csv"), delimiter=";") >> ) >> >> >> BTW, I tend to open csv files with "rb" as it seems to >> avoid line-ending issues with the csv module. YMMV. >> >> TJG >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hit send a little early there. Strip will remove those characters until it hits a character not in the set. You could use file.split('.svg')[0] You could also use split to get rid of the Flag_of_ by doing file = file.split('.svg')[0].split('_')[2] or you could use replace for it file = file.split('.svg')[0].replace('Flag_of_', '') -- Kind Regards, Christian Witts From mail at timgolden.me.uk Mon Jul 27 11:21:13 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 27 Jul 2009 10:21:13 +0100 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6D7189.6010409@timgolden.me.uk> davidwilson at Safe-mail.net wrote: > Here is what I have so far: > > import os > import csv > > countries = {} > reader = csv.reader(open("countries.csv")) > for row in reader: > code, name = row > countries[name] = code > > files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) You don't really need the set () here, as I doubt your operating system allows two files of the same name in the same directory. Also, you can use os.listdir (".") if you want. > print len(files) > > for file in files: > file = file.strip('.svg') > print file > # if countries.has_key(file): > # print file > [... snip ...] > > The problem is that for example the file Flag_of_the_United_States.svg > when I use the strip('.svg') it is returned as Flag_of_the_United_State Yes, this is a common gotcha when using strip. Check out the docs of strip: """ Help on built-in function strip: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ The parameter to strip -- if given -- is a string of chars, any and all of which are stripped from the ends of the string. It is not a *string* which is stripped in its entirety; it is a list of characters. So here, Python is stripping any of ".", "s", "v", "g" from the ends of your string. I suggest you put together a little function, eg: def rstrip_string (look_in, look_for): if look_in.endswith (look_for): return look_in[:-len (look_for)] else: return look_in which you can then call: files = [rstrip_string (f, ".svg") for f in files] > > Also, How do I remove 'Flag_of', 'Flag_of_the_' Same sort of idea. > > I guess after this I can compare the value with the key and map the tld? > > Or is it better to use regex and then search from the list of countries? But how??? regex would be possible here, but probably overkill. You're very nearly there. Assuming the format of the strings is consistently simple, you can take shortcuts as above. If it's possible that one file has "flag_of" while another has "flag-of" and another "flags-of" then you might need to get fancier. TJG From alan.gauld at btinternet.com Mon Jul 27 11:22:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jul 2009 10:22:57 +0100 Subject: [Tutor] renaming files within a directory References: Message-ID: wrote > The problem is that for example the file Flag_of_the_United_States.svg > when I use the strip('.svg') it is returned as Flag_of_the_United_State Thats because strip removes all of the characters in the given string. You would probably be better removing the extension using the os.path.splitext() function. > Also, How do I remove 'Flag_of', 'Flag_of_the_' You could try replacing with a null string. Do the second one first followed by the first if necessary, using the string.replace() method. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Mon Jul 27 12:37:48 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 27 Jul 2009 06:37:48 -0400 Subject: [Tutor] simple text replace In-Reply-To: <936455.35974.qm@web110708.mail.gq1.yahoo.com> References: <936455.35974.qm@web110708.mail.gq1.yahoo.com> Message-ID: <4A6D837C.8060003@ieee.org> Albert-Jan Roskam wrote: > Hi! > > Did you consider using a regex? > > import re > re.sub("python\s", "snake ", "python is cool, pythonprogramming...") > > Cheers!! > Albert-Jan > > > --- On Mon, 7/27/09, Dave Angel wrote: > > >> From: Dave Angel >> Subject: Re: [Tutor] simple text replace >> To: "j booth" >> Cc: tutor at python.org >> Date: Monday, July 27, 2009, 12:41 AM >> j booth wrote: >> >>> Hello, >>> >>> I am scanning a text file and replacing words with >>> >> alternatives. My >> >>> difficulty is that all occurrences are replaced (even >>> >> if they are part of >> >>> another word!).. >>> >>> This is an example of what I have been using: >>> >>> for line in >>> >> fileinput.FileInput("test_file.txt",inplace=1): >> >>> >>> >>>> line = >>>> >> line.replace(original, new) >> >>>> print line, >>>> >>>> >> fileinput.close() >> >>>> >>>> >>> original and new are variables that have string values >>> >> from functions.. >> >>> original finds each word in a text file and old is a >>> >> manipulated >> >>> replacement. Essentially, I would like to replace only >>> >> the occurrence that >> >>> is currently selected-- not the rest. for example: >>> >>> python is great, but my python knowledge is limited! >>> >> regardless, I enjoy >> >>> >>> >>>> pythonprogramming >>>> >>>> >>> returns something like: >>> >>> snake is great, but my snake knowledge is limited! >>> >> regardless, I enjoy >> >>> >>> >>>> snakeprogramming >>>> >>>> >>> thanks so much! >>> >>> >>> >> Not sure what you mean by "currently selected," you're >> processing a line at a time, and there are multiple >> legitimate occurrences of the word in the line. >> >> The trick is to define what you mean by "word." >> replace() has no such notion. So we want to write a >> function such as: >> >> given three strings, line, inword, and outword. Find >> all occurrences of inword in the line, and replace all of >> them with outword. The definition of word is a group >> of alphabetic characters (a-z perhaps) that is surrounded by >> non-alphabetic characters. >> >> The approach that I'd use is to prepare a translated copy >> of the line as follows: Replace each >> non-alphabetic character with a space. Also insert a >> space at the beginning and one at the end. Now, take >> the inword, and similarly add spaces at begin and end. >> Now search this modified line for all occurrences of this >> modified inword, and make a list of the indices where it is >> found. In your example line, there would be 2 items in >> the list. >> >> Now, using the original line, use that list of indices to >> substitute the outword in the appropriate places. Use >> slices to do it, preferably from right to left, so the >> indices will work even though the string is changing. >> (The easiest way to do right to left is to reverse() the >> list. >> >> DaveA >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> (Please don't top-post on this list. The message then appears out of order. Append new responses to end, or inline when appropriate) Yes, a regex would make a lot of sense here. But a person should not take on regular expressions till they have lots of experience with the rest of the language. Besides, it's pretty easy to have subtle bugs, even with such a simple case. For example your re string would erroneously convert the word "newpython", and miss the last two occurrences of the real word "python" near the end of the string. import re print st = re.sub("python\s", "snake ", "python is cool, pythonprogramming... newpython becomes python, or python") Output: snake is cool, pythonprogramming... newsnake becomes python, or python (gives the wrong answer, in three places) DaveA From davea at ieee.org Mon Jul 27 12:56:26 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 27 Jul 2009 06:56:26 -0400 Subject: [Tutor] First code snipet In-Reply-To: References: <1248570147.28544.249.camel@andi-lap> <4A6C42D0.7000900@ieee.org> Message-ID: <4A6D87DA.8070609@ieee.org> Darth Kaboda wrote: >> Good point. It is important to state your goal for the code, preferably >> in comments in your code, as well as in the message asking us the >> question. Suggest you include a doc-string for each class and method >> declaration. >> >> But it's important to tell us how you expect to use it, as well. If >> it's for your own learning, then it's pretty good as it is. But if you >> intend to show it to prospective employers, there are a lot of ways to >> clean it up. >> >> >> So... >> >> Unlike Java, not everything needs to be in a class. This shuffler class >> accomplishes nothing that the module doesn't already do. The only >> instance attribute you use is rgen, and that could just as readily have >> been a global (visible within the entire module). >> >> Naming is important. I think I would have factored it into three >> functions cut() and ripple(). shuffle() simply calls cut(), then ripple(). >> >> You need to know the library better. Andreas already mentioned the std >> library random.shuffle(), and you correctly explained why you didn't use >> it. But there are other library functions that would make your code >> more concise, more readable, and maybe faster. >> >> Starting with shuffle() (which I'd call ripple()) >> >> Because Python makes it easy to swap two variables in-place, it's common >> to swap arguments directly, rather than copy them to local attributes. >> So I'd replace the first 4 lines with: >> if self.rgen.randint(0,1): #randomly decide which pile is shuffled >> down first >> inpile2, inpile1 = inpile1, inpile2 >> >> len() is very fast, so there's no need for a separate variable to keep >> track of the lengths of inpile1 and inpile2. So eliminate all refs to >> pile1c and pile2. In the while, just use >> while len(inpile1) and len(inpile2): >> >> Lists have no type associated with them. Each object in a list has its >> own type. So there's no meaning to constructing an empty list out of >> another one. >> rpile = [] >> >> pop(0) is slow, compared with pop(-1). If you used the latter, you >> would have to do a reverse on the list when you were done to keep the >> realism. And that would make the code less readable. So I think this >> is an unnecessary optimization. But keep it in mind if you're ever >> dealing with thousands of items in a list. Peeling them off from the >> front one at a time will be slow. >> >> The logic of popping a random number of cards from one list, and >> appending them to the result could be done the same way you do the >> cut(), using slices. I think it would be worth it if you made a >> separate function out of it, to call from whichever deck was being >> operated on. >> >> Where you do the if i < pile1c you could instead use the min() >> function. >> i = min(len(inpile1), self.rgen.randint(1,4)) >> >> At the end of the function, the if pile1c: elif ... logic could be >> replaced by >> rpile.extend(inpile1).extend(inpile2) >> >> as there's no harm in extending with an empty list. >> >> HTH, DaveA >> >> > > > Dave and Alan, > > > > Thank you for the advice and showing me some of the small nuances I haven't quite figured out yet. I used both of your suggestions to change the class the updated code is attached if you'd like to see. > > > > I tried putting the two extends in the same line and that didn't work as extend doesn't return anything so ended up putting them on consecutive lines without the if statement. > > > > Instead of doing the pop method I took your advice and tried it with slices instead along with extends. Shortened the code a bit. One note on pop method is pop() and pop(-1) the same thing? Looks like it based on what I've read but not 100% confident in that answer. > > > > On the class versus module I wasn't sure where I'd end up taking this idea so went ahead and coded it as a class. If I actually do much more with this, other then just as a coding exercise to help learn Python, I might be adding things to this or using it as a superclass. Examples of expansion ability to queue up decks, have multiple shufflers going at the same time in a program etc... So without knowing all the options in Python figured the class gave me the greatest flexibility. Yeah otherwise I'd have just made a module and still might switch it if I expand on this depending on what the needs turn out to be. > > > > Again thanks to everyone for looking at my code and the quick and helpful feedback. Hoping to do start coding a larger project soon so you'll probably get some questions from me. > > > > Thanks, > > Brian > > You're certainly welcome. Sorry I blew it on extend(). I should have known better; not just remembered. Python is pretty consistent - when a method modifies its self-data, it generally doesn't return it as well. For example sort() returns None, while sorted() returns the new list. As for pop(-1): it'll always take from the end of the list, rather than the beginning for pop(0). That's faster, but the result ends up backwards. So you call reverse() on the result to get it back to where you began. I hope I pointed out that it's a minor optimization for small lists, and that it might obscure clarity. However, the notion that -1 refers to the end of a list or string is a useful one to learn, for both indexing and slicing. From some perspectives, a module is analogous to a class for which all methods are class methods (java static). And that in turn is very similar to a class for which only one instance will ever be created. As your class currently stands, the only reason I can imagine needing a second instance is if you were operating on more than one deck simultaneously, and wanted random() to be repeatable between runs, so you would be separately maintaining the random seed for each deck. However, you're quite right that other methods and instance attributes might make it necessary to be a class. DaveA From kent37 at tds.net Mon Jul 27 13:01:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Jul 2009 07:01:32 -0400 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <1c2a2c590907270401y648cc412k39eca501a3f6a192@mail.gmail.com> On Mon, Jul 27, 2009 at 5:10 AM, wrote: > files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) > print len(files) > > for file in files: > ? ?file = file.strip('.svg') > ? ?print file > # ? ?if countries.has_key(file): > # ? ? ? print file > > When I run this I get: > > Flag_of_Uganda > ... > > The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State > > Also, How do I remove 'Flag_of', 'Flag_of_the_' I suggest you use glob.glob() instead of os.listdir(): files = glob.glob('Flag_of_*.svg) Then you know that each file name starts with Flag_of_ and ends with .svg. To remove them, since they are fixed strings you can just use slicing; file = file[8:-4] if file.startswith('the_'): file = file[4:] Kent From gregor.lingl at aon.at Mon Jul 27 13:27:33 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Mon, 27 Jul 2009 13:27:33 +0200 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: Message-ID: <4A6D8F25.5070300@aon.at> Dick Moores schrieb: > I've taken a long break from Python, and now I want to try scripting > with 2.62. I downloaded and installed 2.62, changed Win XP > environmental variables to use Python26. Entering python at the > command line shows I'm using 2.62: > > C:\Documents and Settings\Riley>python > Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > > > So I'm able to try out the new features of 2.6 (I had been using > 2.51), but I can't get IDLE to use 2.6. When I click on > E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says: > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > > And of course, the new 2.6 features don't work. > > Advice, please. > I suggest you have to change the association of *.pyw files to the program, which is used to 'open' it. In Windows explorer choose menu extras/directory options, then choose tab file types and select PYW type then press button 'advacned...' or somethng like this at the bottom of the tab, chose 'open' and the button to change this. If you see the entry "C:\Python25\pythonw.exe" "%1" %* change this to Python26 My translations from the German button captions to English might not be correct. Hope this helps anyway. Regards, Gregor > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From davidwilson at Safe-mail.net Mon Jul 27 14:26:23 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Mon, 27 Jul 2009 08:26:23 -0400 Subject: [Tutor] renaming files within a directory Message-ID: Here is the updated viersion: --- import glob import csv from os import rename countries = {} reader = csv.reader(open("countries.csv")) for row in reader: code, name = row countries[name] = code files = set([file for file in glob.glob('Flag_of_*.svg')]) for file in files: file = file[8:-4] if file.startswith('the_'): file = file[4:] if countries.has_key(file): b = 'flag-'+ countries[file] + '.svg' print b rename(file, b) But I cannot get the rename to take effect and I get an error: $ python rename_svg.py Uganda flag-ug.svg Traceback (most recent call last): File "rename_svg.py", line 21, in rename(file, b) OSError: [Errno 2] No such file or directory What am I missing? -------- Original Message -------- From: Kent Johnson Apparently from: kent3737 at gmail.com To: davidwilson at safe-mail.net Cc: mail at timgolden.me.uk, tutor at python.org Subject: Re: [Tutor] renaming files within a directory Date: Mon, 27 Jul 2009 07:01:32 -0400 > On Mon, Jul 27, 2009 at 5:10 AM, wrote: > > > files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) > > print len(files) > > > > for file in files: > > ? ?file = file.strip('.svg') > > ? ?print file > > # ? ?if countries.has_key(file): > > # ? ? ? print file > > > > When I run this I get: > > > > Flag_of_Uganda > > ... > > > > The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State > > > > Also, How do I remove 'Flag_of', 'Flag_of_the_' > > I suggest you use glob.glob() instead of os.listdir(): > > files = glob.glob('Flag_of_*.svg) > > Then you know that each file name starts with Flag_of_ and ends with > .svg. To remove them, since they are fixed strings you can just use > slicing; > file = file[8:-4] > if file.startswith('the_'): > file = file[4:] > > Kent From cwitts at compuscan.co.za Mon Jul 27 15:04:00 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Mon, 27 Jul 2009 15:04:00 +0200 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6DA5C0.4060108@compuscan.co.za> davidwilson at Safe-mail.net wrote: > Here is the updated viersion: > > --- > > import glob > import csv > from os import rename > > > countries = {} > reader = csv.reader(open("countries.csv")) > for row in reader: > code, name = row > countries[name] = code > > files = set([file for file in glob.glob('Flag_of_*.svg')]) > > for file in files: > file = file[8:-4] > if file.startswith('the_'): > file = file[4:] > if countries.has_key(file): > b = 'flag-'+ countries[file] + '.svg' > print b > rename(file, b) > > But I cannot get the rename to take effect and I get an error: > > $ python rename_svg.py > Uganda flag-ug.svg > Traceback (most recent call last): > File "rename_svg.py", line 21, in > rename(file, b) > OSError: [Errno 2] No such file or directory > > What am I missing? > > -------- Original Message -------- > From: Kent Johnson > Apparently from: kent3737 at gmail.com > To: davidwilson at safe-mail.net > Cc: mail at timgolden.me.uk, tutor at python.org > Subject: Re: [Tutor] renaming files within a directory > Date: Mon, 27 Jul 2009 07:01:32 -0400 > > >> On Mon, Jul 27, 2009 at 5:10 AM, wrote: >> >> >>> files = set([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) >>> print len(files) >>> >>> for file in files: >>> file = file.strip('.svg') >>> print file >>> # if countries.has_key(file): >>> # print file >>> >>> When I run this I get: >>> >>> Flag_of_Uganda >>> ... >>> >>> The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State >>> >>> Also, How do I remove 'Flag_of', 'Flag_of_the_' >>> >> I suggest you use glob.glob() instead of os.listdir(): >> >> files = glob.glob('Flag_of_*.svg) >> >> Then you know that each file name starts with Flag_of_ and ends with >> .svg. To remove them, since they are fixed strings you can just use >> slicing; >> file = file[8:-4] >> if file.startswith('the_'): >> file = file[4:] >> >> Kent >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You changed the name contained in file from the original so it now cannot find what you are referring to. Try not to shadow built-in names like file by the way, it can cause unintended side-effects. Make changes to this effect: for filename in files: fn = filename[8:-4] if fn.startswith('the_'): fn = fn[4:] if fn in countries: # Dictionaries can be accessed this way and it looks cleaner. new_filename = 'flag-%s.svg' % countries[fn] # String formatting is neater and faster than concatenation rename(filename, new_filename) -- Kind Regards, Christian Witts From davea at ieee.org Mon Jul 27 15:01:58 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 27 Jul 2009 09:01:58 -0400 Subject: [Tutor] renaming files within a directory In-Reply-To: References: Message-ID: <4A6DA546.3080005@ieee.org> davidwilson at Safe-mail.net wrote: > Here is the updated viersion: > > --- > > import glob > import csv > from os import rename > > > countries =} > reader =sv.reader(open("countries.csv")) > for row in reader: > code, name =ow > countries[name] =ode > > files =et([file for file in glob.glob('Flag_of_*.svg')]) > > for file in files: > file =ile[8:-4] > if file.startswith('the_'): > file =ile[4:] > if countries.has_key(file): > b =flag-'+ countries[file] + '.svg' > print b > rename(file, b) > > But I cannot get the rename to take effect and I get an error: > > $ python rename_svg.py > Uganda flag-ug.svg > Traceback (most recent call last): > File "rename_svg.py", line 21, in > rename(file, b) > OSError: [Errno 2] No such file or directory > > What am I missing? > > -------- Original Message -------- > From: Kent Johnson > Apparently from: kent3737 at gmail.com > To: davidwilson at safe-mail.net > Cc: mail at timgolden.me.uk, tutor at python.org > Subject: Re: [Tutor] renaming files within a directory > Date: Mon, 27 Jul 2009 07:01:32 -0400 > > >> On Mon, Jul 27, 2009 at 5:10 AM, wrote: >> >> >>> files =et([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) >>> print len(files) >>> >>> for file in files: >>> file =ile.strip('.svg') >>> print file >>> # if countries.has_key(file): >>> # print file >>> >>> When I run this I get: >>> >>> Flag_of_Uganda >>> ... >>> >>> The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State >>> >>> Also, How do I remove 'Flag_of', 'Flag_of_the_' >>> >> I suggest you use glob.glob() instead of os.listdir(): >> >> files =lob.glob('Flag_of_*.svg) >> >> Then you know that each file name starts with Flag_of_ and ends with >> .svg. To remove them, since they are fixed strings you can just use >> slicing; >> file =ile[8:-4] >> if file.startswith('the_'): >> file =ile[4:] >> >> Kent >> > > (Please don't top-post on this mailing list. It hopelessly confuses which order the quoted messages come.) > One reason the rename() will fail is that you're changing file between the for loop and the rename. Incidentally, file is a lousy name to use, since it already has a meaning in the std lib. It's the type of the object you get from open(), or from glob.glog(). I didn't check the rest, but for this change, you'd get: for infile in files: country = infile[8:-4] if country.startswith('the_'): country = country[4:] if countries.has_key(file): b = 'flag-'+ countries[country] + '.svg' print b rename(file, b) BTW, several other characters were dropped in your email. Did you retype the code (bad), or use cut/paste? DaveA From davea at ieee.org Mon Jul 27 15:03:25 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 27 Jul 2009 09:03:25 -0400 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: <4A6D8F25.5070300@aon.at> References: <4A6D8F25.5070300@aon.at> Message-ID: <4A6DA59D.6040906@ieee.org> Gregor Lingl wrote: >

Dick > Moores schrieb: >> I've taken a long break from Python, and now I want to try scripting >> with 2.62. I downloaded and installed 2.62, changed Win XP >> environmental variables to use Python26. Entering python at the >> command line shows I'm using 2.62: >> >> C:\Documents and Settings\Riley>python >> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >> So I'm able to try out the new features of 2.6 (I had been using >> 2.51), but I can't get IDLE to use 2.6. When I click on >> E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says: >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit >> (Intel)] on win32 >> Type "copyright", "credits" or "license()" for more information. >> >> And of course, the new 2.6 features don't work. >> >> Advice, please. >> > I suggest you have to change the association of *.pyw files to the > program, which is used to 'open' it. > > In Windows explorer choose menu extras/directory options, > then choose tab file types and select PYW type > then press button 'advacned...' or somethng like this at the bottom > of the tab, chose 'open' and the button to change this. > > If you see the entry > > "C:\Python25\pythonw.exe" "%1" %* > > change this to Python26 > > My translations from the German button captions to > English might not be correct. Hope this helps anyway. > > Regards, > Gregor > > >> Thanks, >> >> Dick Moores >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > For future reference, assoc and ftype are commandline tools that let you examine and modify those file associations. Very useful if you have to go back and forth between two versions. DaveA From rdmoores at gmail.com Mon Jul 27 15:58:53 2009 From: rdmoores at gmail.com (Dick Moores) Date: Mon, 27 Jul 2009 06:58:53 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: <4A6D8F25.5070300@aon.at> References: <4A6D8F25.5070300@aon.at> Message-ID: On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote: > Dick Moores schrieb: >> >> I've taken a long break from Python, and now I want to try scripting >> with 2.62. I downloaded and installed 2.62, changed Win XP >> environmental variables to use Python26. Entering python at the >> command line shows I'm using 2.62: >> >> C:\Documents and Settings\Riley>python >> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >> So I'm able to try out the new features of 2.6 (I had been using >> 2.51), but I can't get IDLE to use 2.6. When I click on >> E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says: >> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit >> (Intel)] on win32 >> Type "copyright", "credits" or "license()" for more information. >> >> And of course, the new 2.6 features don't work. >> >> Advice, please. >> > > I suggest you have to change the association of *.pyw files to the > program, which is used to 'open' it. > > In Windows explorer choose menu extras/directory options, > then choose tab file types and select PYW type > then press button 'advacned...' or somethng like this at the bottom > of the tab, chose 'open' and the button to change this. > > If you see the entry > > "C:\Python25\pythonw.exe" "%1" %* > > change this to Python26 Yes! After I did that, now when I call E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62. But I also want to use Ulipad, actually my main Python editor. When I call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer), Ulipad no longer opens. Before I made the change you suggested, at least Ulipad would open using 2.51. What can I do to use both IDLE and Ulipad with 2.62? Dick From davidwilson at Safe-mail.net Mon Jul 27 16:14:24 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Mon, 27 Jul 2009 10:14:24 -0400 Subject: [Tutor] renaming files within a directory Message-ID: Thank you all for your help. -------- Original Message -------- From: Dave Angel Apparently from: SRS0=PAJG=DU=ieee.org=davea at srs.perfora.net To: davidwilson at Safe-mail.net Cc: kent37 at tds.net, tutor at python.org Subject: Re: Re: [Tutor] renaming files within a directory Date: Mon, 27 Jul 2009 09:01:58 -0400 > davidwilson at Safe-mail.net wrote: > > Here is the updated viersion: > > > > --- > > > > import glob > > import csv > > from os import rename > > > > > > countries =} > > reader =sv.reader(open("countries.csv")) > > for row in reader: > > code, name =ow > > countries[name] =ode > > > > files =et([file for file in glob.glob('Flag_of_*.svg')]) > > > > for file in files: > > file =ile[8:-4] > > if file.startswith('the_'): > > file =ile[4:] > > if countries.has_key(file): > > b =flag-'+ countries[file] + '.svg' > > print b > > rename(file, b) > > > > But I cannot get the rename to take effect and I get an error: > > > > $ python rename_svg.py > > Uganda flag-ug.svg > > Traceback (most recent call last): > > File "rename_svg.py", line 21, in > > rename(file, b) > > OSError: [Errno 2] No such file or directory > > > > What am I missing? > > > > -------- Original Message -------- > > From: Kent Johnson > > Apparently from: kent3737 at gmail.com > > To: davidwilson at safe-mail.net > > Cc: mail at timgolden.me.uk, tutor at python.org > > Subject: Re: [Tutor] renaming files within a directory > > Date: Mon, 27 Jul 2009 07:01:32 -0400 > > > > > >> On Mon, Jul 27, 2009 at 5:10 AM, wrote: > >> > >> > >>> files =et([file for file in os.listdir(os.getcwd()) if file.endswith('svg')]) > >>> print len(files) > >>> > >>> for file in files: > >>> file =ile.strip('.svg') > >>> print file > >>> # if countries.has_key(file): > >>> # print file > >>> > >>> When I run this I get: > >>> > >>> Flag_of_Uganda > >>> ... > >>> > >>> The problem is that for example the file Flag_of_the_United_States.svg when I use the strip('.svg') it is returned as Flag_of_the_United_State > >>> > >>> Also, How do I remove 'Flag_of', 'Flag_of_the_' > >>> > >> I suggest you use glob.glob() instead of os.listdir(): > >> > >> files =lob.glob('Flag_of_*.svg) > >> > >> Then you know that each file name starts with Flag_of_ and ends with > >> .svg. To remove them, since they are fixed strings you can just use > >> slicing; > >> file =ile[8:-4] > >> if file.startswith('the_'): > >> file =ile[4:] > >> > >> Kent > >> > > > > (Please don't top-post on this mailing list. It hopelessly confuses which order the quoted messages come.) > > > > One reason the rename() will fail is that you're changing file between > the for loop and the rename. Incidentally, file is a lousy name to use, > since it already has a meaning in the std lib. It's the type of the > object you get from open(), or from glob.glog(). > > > I didn't check the rest, but for this change, you'd get: > > for infile in files: > country = infile[8:-4] > if country.startswith('the_'): > country = country[4:] > if countries.has_key(file): > b = 'flag-'+ countries[country] + '.svg' > print b > rename(file, b) > > > BTW, several other characters were dropped in your email. Did you > retype the code (bad), or use cut/paste? I just cut and paste from vim. Here is the final code: import glob import csv from os import rename countries = {} reader = csv.reader(open("countries.csv")) for row in reader: code, name = row countries[name] = code files = set([file for file in glob.glob('Flag_of_*.svg')]) for filename in files: fn = filename[8:-4] if fn.startswith('the_'): fn = fn[4:] if fn in countries: new_filename = 'flag-%s.svg' % countries[fn] rename(filename, new_filename) > > DaveA From alan.gauld at btinternet.com Mon Jul 27 18:27:45 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jul 2009 17:27:45 +0100 Subject: [Tutor] renaming files within a directory References: Message-ID: wrote > files = set([file for file in glob.glob('Flag_of_*.svg')]) > > for file in files: > file = file[8:-4] Yu probably want to keep the filename unouched and use a variable like country here. > if file.startswith('the_'): > file = file[4:] > if countries.has_key(file): > b = 'flag-'+ countries[file] + '.svg' > print b > rename(file, b) You are trying to use file in the rename but you have modified the filename so it is no longer valid. I'd use filename as the variable in the for loop and country for the modified version used to access the dictionary. > $ python rename_svg.py > Uganda flag-ug.svg Where does the Uganda come from? Loooks like the real code has an extra print statement somewhere? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jul 27 18:32:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jul 2009 17:32:39 +0100 Subject: [Tutor] How to use Python 2.6 with IDLE? References: <4A6D8F25.5070300@aon.at> Message-ID: "Dick Moores" wrote >> I suggest you have to change the association of *.pyw files to the >> program, which is used to 'open' it. >> > Yes! After I did that, now when I call > E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62. > > But I also want to use Ulipad, actually my main Python editor. When I > call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer), > Ulipad no longer opens. Before I made the change you suggested, at > least Ulipad would open using 2.51. What can I do to use both IDLE and > Ulipad with 2.62? What I do for these things is create a shortcut which specifies the full path to the interpreter and to the pyw file. I also set the working foldeer to wherever is most appropriate - usually my project folder. That's fairly bulletproof in my experience! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From eduardo.susan at gmail.com Mon Jul 27 18:35:08 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 27 Jul 2009 10:35:08 -0600 Subject: [Tutor] problem with csv dictreader Message-ID: <9356b9f30907270935k508018fbv38ad0c434fa6d7e5@mail.gmail.com> Hello, I'm enjoying learning python but then I come across some basic things that makes me stumped... I have 2 csv files and I want to see which ones are duplicates based on two criteria email, or telephone. The order of fields in both csv files are different. Here are a sample bogus data: import csv bv = """NAME,BVADDRTELNO1,BVADDREMAIL Company1, 1234567788, this at that.com CompanyA, 1231234455, that at this.com CompanyC, 1011011111, new at this.com CompanyD, 2222222222, old at olde.com """ site = """Company,Email,Phone "Company3","nothing at nada.com","1234560000" "CompanyD","old at olde.com","2222222222" "Company1","this at that.com","1234567788" """ bv = bv.upper() # This is just to make the data more homogeneous and detect duplicates more easily site = site.upper() bvreader = csv.DictReader(bv.splitlines(True)) sitelist = csv.DictReader(site.splitlines(True)) for row in sitelist: for line in bvreader: if row['EMAIL'] == line['BVADDREMAIL']: print line['NAME'], row['COMPANY'] #===== My questions are: Why nothing is being printed? Two rows should be printed right? What would be better for the outer loop, the bigger list or the small list? The biglist (bvreader) is under 2100 lines (244Kb) and the smaller list (sitelist) can be 20 lines or less. Thanks. Eduardo From davidwilson at Safe-mail.net Mon Jul 27 19:16:26 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Mon, 27 Jul 2009 13:16:26 -0400 Subject: [Tutor] subprocess.call Message-ID: Hello again, >From my previous post I would now like to transform the SVG images using the svg2png library, but am having difficulties in making it work. Here is the code: import glob import csv from os import rename import subprocess countries = {} reader = csv.reader(open("countries.csv")) for row in reader: code, name = row countries[name] = code files = set([file for file in glob.glob('Flag_of_*.svg')]) for filename in files: fn = filename[8:-4] if fn.startswith('the_'): fn = fn[4:] if fn in countries: new_filename = 'flag-%s' % countries[fn] subprocess.call(['svg2png --width=17 --height=12 %s %s' \ % (filename, new_filename + '.png')]) $ python rename_svg.py Traceback (most recent call last): File "rename_svg.py", line 22, in % (filename, new_filename + '.png')]) File "/home/dwilson/usr/local/python2.6/lib/python2.6/subprocess.py", line 444, in call return Popen(*popenargs, **kwargs).wait() File "/home/dwilson/usr/local/python2.6/lib/python2.6/subprocess.py", line 595, in __init__ errread, errwrite) File "/home/dwilson/usr/local/python2.6/lib/python2.6/subprocess.py", line 1092, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory Where am I doing this wrong? Dave From ctcast at gmail.com Mon Jul 27 20:13:31 2009 From: ctcast at gmail.com (Chris Castillo) Date: Mon, 27 Jul 2009 13:13:31 -0500 Subject: [Tutor] Eng to Leet Speek Message-ID: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> so I have a string: 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 \/\/1+# the |#a|-|i|_7? and I am trying to turn it into english with the following code: fileIn = open("encrypted.txt", "r").read() def eng2leet(astring): astring = astring.replace("4","a") astring = astring.replace("8","b") astring = astring.replace("[","c") astring = astring.replace("|)","d") astring = astring.replace("3","e") astring = astring.replace("|#","f") astring = astring.replace("6","g") astring = astring.replace("#","h") astring = astring.replace("1","i") astring = astring.replace("]","j") astring = astring.replace("|\\","k") astring = astring.replace("|_","l") astring = astring.replace("|-|","m") astring = astring.replace("|\\","n") astring = astring.replace("0","o") astring = astring.replace("|*","p") astring = astring.replace("0\\","q") astring = astring.replace("2","r") astring = astring.replace("5","s") astring = astring.replace("+","t") astring = astring.replace("|_|","u") astring = astring.replace("\/","v") astring = astring.replace("\/\/","w") astring = astring.replace("><","x") astring = astring.replace("7","y") astring = astring.replace("7_","z") return astring print eng2leet(fileIn) Only problem is that when it needs to translate a U or a W it prints an L or 2 V's. Need some help please. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Jul 27 20:14:19 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 27 Jul 2009 14:14:19 -0400 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> Message-ID: <4A6DEE7B.7020805@ieee.org> Dick Moores wrote: > On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote: > >> Dick Moores schrieb: >> >>> I've taken a long break from Python, and now I want to try scripting >>> with 2.62. I downloaded and installed 2.62, changed Win XP >>> environmental variables to use Python26. Entering python at the >>> command line shows I'm using 2.62: >>> >>> C:\Documents and Settings\Riley>python >>> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit >>> (Intel)] on win32 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> So I'm able to try out the new features of 2.6 (I had been using >>> 2.51), but I can't get IDLE to use 2.6. When I click on >>> E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says: >>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit >>> (Intel)] on win32 >>> Type "copyright", "credits" or "license()" for more information. >>> >>> And of course, the new 2.6 features don't work. >>> >>> Advice, please. >>> >>> >> I suggest you have to change the association of *.pyw files to the >> program, which is used to 'open' it. >> >> In Windows explorer choose menu extras/directory options, >> then choose tab file types and select PYW type >> then press button 'advacned...' or somethng like this at the bottom >> of the tab, chose 'open' and the button to change this. >> >> If you see the entry >> >> "C:\Python25\pythonw.exe" "%1" %* >> >> change this to Python26 >> > > Yes! After I did that, now when I call > E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62. > > But I also want to use Ulipad, actually my main Python editor. When I > call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer), > Ulipad no longer opens. Before I made the change you suggested, at > least Ulipad would open using 2.51. What can I do to use both IDLE and > Ulipad with 2.62? > > Dick > > I don't know IDLE, so I don't really know how it decides which Python to use. In this thread Gregor suggested fixing the file association, which is certainly reasonable. And I suggested what to me is an easier way to fix associations. But there may be another way that I just don't know about, such as some environment variable. You could send email to idle-dev at python.org. One other thought: Idle.bat is located in the install directory of python. So perhaps it locates the python that it's running with. Could you try running it more explicitly? Make your own bat file that instead of start idle.pyw %1 %2 %3 %4 %5 %6 %7 %8 %9 looks like e: cd \Python26\Lib\idlelib\ ..\..\pythonw.exe idle.pyw %* I do know that when you double-click on a xxx.pyw file in Explorer, it will use the association to decide which program, and there's only one program you can have there. My preference is to have it execute the program, not start IDLE, a text editor, or any IDE. You may feel differently, but if you agree with me, then you might want to add UliPad.exe in the context menu of explorer. If you do that successfully, then when you right-click on a .pyw file, one of your choices will be "Run Ulipad." The following is pretty-much pasted from some notes I took quite a while ago, and may not be quite right. So if you're not pretty familiar with the registry, you probably shouldn't experiment just based on this. >>>In the Windows registry, add a new key under HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell >>>Make its default value the item text you want in the context menu. >>>Add a new key under it, "command", and make its default value the command line you want to execute. Will look like this: >>>"complete path to ulipad.exe" %1 %* >>>See http://msdn.microsoft.com/en-us/library/dd807139(VS.85).aspx for more details In addition to adding it to right-click menu, you could also add it to the "open-with" list, or to "Send-To" list. I don't have any cookbook for any of these, but I've done each at one time or another. DaveA From sisson.j at gmail.com Mon Jul 27 20:38:14 2009 From: sisson.j at gmail.com (J Sisson) Date: Mon, 27 Jul 2009 13:38:14 -0500 Subject: [Tutor] Eng to Leet Speek In-Reply-To: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> Message-ID: <4297a9020907271138s521f86c7ue1e1913b7982f379@mail.gmail.com> You need a deterministic algorithm for conversion. It's impossible (without analyzing the context of the word) to translate "|_|#" (it's either "lf" or "uh", but which?). On Mon, Jul 27, 2009 at 1:13 PM, Chris Castillo wrote: > so I have a string: > > 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 > \/\/1+# the |#a|-|i|_7? > > > and I am trying to turn it into english with the following code: > > fileIn = open("encrypted.txt", "r").read() > > def eng2leet(astring): > astring = astring.replace("4","a") > astring = astring.replace("8","b") > astring = astring.replace("[","c") > astring = astring.replace("|)","d") > astring = astring.replace("3","e") > astring = astring.replace("|#","f") > astring = astring.replace("6","g") > astring = astring.replace("#","h") > astring = astring.replace("1","i") > astring = astring.replace("]","j") > astring = astring.replace("|\\","k") > astring = astring.replace("|_","l") > astring = astring.replace("|-|","m") > astring = astring.replace("|\\","n") > astring = astring.replace("0","o") > astring = astring.replace("|*","p") > astring = astring.replace("0\\","q") > astring = astring.replace("2","r") > astring = astring.replace("5","s") > astring = astring.replace("+","t") > astring = astring.replace("|_|","u") > astring = astring.replace("\/","v") > astring = astring.replace("\/\/","w") > astring = astring.replace("><","x") > astring = astring.replace("7","y") > astring = astring.replace("7_","z") > return astring > > print eng2leet(fileIn) > > Only problem is that when it needs to translate a U or a W it prints an L > or 2 V's. Need some help please. Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Computers are like air conditioners... They quit working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davidwilson at Safe-mail.net Mon Jul 27 20:40:27 2009 From: davidwilson at Safe-mail.net (davidwilson at Safe-mail.net) Date: Mon, 27 Jul 2009 14:40:27 -0400 Subject: [Tutor] subprocess.call Message-ID: OK I think I found my error, here is what I did: flags = set([file for file in glob.glob('flag-*.svg')]) def call(cmd): subprocess.call([cmd], shell=True) for flag in flags: name = flag[:-4] out = name+'.png' call('svg2png --width=17 --height=12 %s %s' \ % (flag, out)) Is this better? From davea at dejaviewphoto.com Mon Jul 27 20:13:54 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Mon, 27 Jul 2009 14:13:54 -0400 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> Message-ID: <4A6DEE62.70305@dejaviewphoto.com> Dick Moores wrote: > On Mon, Jul 27, 2009 at 04:27, Gregor Lingl wrote: > >> Dick Moores schrieb: >> >>> I've taken a long break from Python, and now I want to try scripting >>> with 2.62. I downloaded and installed 2.62, changed Win XP >>> environmental variables to use Python26. Entering python at the >>> command line shows I'm using 2.62: >>> >>> C:\Documents and Settings\Riley>python >>> Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit >>> (Intel)] on win32 >>> Type "help", "copyright", "credits" or "license" for more information. >>> >>> So I'm able to try out the new features of 2.6 (I had been using >>> 2.51), but I can't get IDLE to use 2.6. When I click on >>> E:\Python26\Lib\idlelib\idle.pyw, I get an IDLE instance that says: >>> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit >>> (Intel)] on win32 >>> Type "copyright", "credits" or "license()" for more information. >>> >>> And of course, the new 2.6 features don't work. >>> >>> Advice, please. >>> >>> >> I suggest you have to change the association of *.pyw files to the >> program, which is used to 'open' it. >> >> In Windows explorer choose menu extras/directory options, >> then choose tab file types and select PYW type >> then press button 'advacned...' or somethng like this at the bottom >> of the tab, chose 'open' and the button to change this. >> >> If you see the entry >> >> "C:\Python25\pythonw.exe" "%1" %* >> >> change this to Python26 >> > > Yes! After I did that, now when I call > E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62. > > But I also want to use Ulipad, actually my main Python editor. When I > call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer), > Ulipad no longer opens. Before I made the change you suggested, at > least Ulipad would open using 2.51. What can I do to use both IDLE and > Ulipad with 2.62? > > Dick > > I don't know IDLE, so I don't really know how it decides which Python to use. In this thread Gregor suggested fixing the file association, which is certainly reasonable. And I suggested what to me is an easier way to fix associations. But there may be another way that I just don't know about, such as some environment variable. You could send email to idle-dev at python.org. One other thought: Idle.bat is located in the install directory of python. So perhaps it locates the python that it's running with. Could you try running it more explicitly? Make your own bat file that instead of start idle.pyw %1 %2 %3 %4 %5 %6 %7 %8 %9 looks like e: cd \Python26\Lib\idlelib\ ..\..\pythonw.exe idle.pyw %* I do know that when you double-click on a xxx.pyw file in Explorer, it will use the association to decide which program, and there's only one program you can have there. My preference is to have it execute the program, not start IDLE, a text editor, or any IDE. You may feel differently, but if you agree with me, then you might want to add UliPad.exe in the context menu of explorer. If you do that successfully, then when you right-click on a .pyw file, one of your choices will be "Run Ulipad." The following is pretty-much pasted from some notes I took quite a while ago, and may not be quite right. So if you're not pretty familiar with the registry, you probably shouldn't experiment just based on this. >>>In the Windows registry, add a new key under HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell >>>Make its default value the item text you want in the context menu. >>>Add a new key under it, "command", and make its default value the command line you want to execute. Will look like this: >>>"complete path to ulipad.exe" %1 %* >>>See http://msdn.microsoft.com/en-us/library/dd807139(VS.85).aspx for more details In addition to adding it to right-click menu, you could also add it to the "open-with" list, or to "Send-To" list. I don't have any cookbook for any of these, but I've done each at one time or another. DaveA From ctcast at gmail.com Mon Jul 27 20:51:39 2009 From: ctcast at gmail.com (Chris Castillo) Date: Mon, 27 Jul 2009 13:51:39 -0500 Subject: [Tutor] Eng to Leet Speek In-Reply-To: <4297a9020907271138s521f86c7ue1e1913b7982f379@mail.gmail.com> References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> <4297a9020907271138s521f86c7ue1e1913b7982f379@mail.gmail.com> Message-ID: <50e459210907271151q6b492746h2dd646d1ec127e27@mail.gmail.com> On Mon, Jul 27, 2009 at 1:38 PM, J Sisson wrote: > You need a deterministic algorithm for conversion. It's impossible > (without analyzing the context of the word) to translate "|_|#" (it's either > "lf" or "uh", but which?). > > > > > On Mon, Jul 27, 2009 at 1:13 PM, Chris Castillo wrote: > >> so I have a string: >> >> 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 >> \/\/1+# the |#a|-|i|_7? >> >> >> and I am trying to turn it into english with the following code: >> >> fileIn = open("encrypted.txt", "r").read() >> >> def eng2leet(astring): >> astring = astring.replace("4","a") >> astring = astring.replace("8","b") >> astring = astring.replace("[","c") >> astring = astring.replace("|)","d") >> astring = astring.replace("3","e") >> astring = astring.replace("|#","f") >> astring = astring.replace("6","g") >> astring = astring.replace("#","h") >> astring = astring.replace("1","i") >> astring = astring.replace("]","j") >> astring = astring.replace("|\\","k") >> astring = astring.replace("|_","l") >> astring = astring.replace("|-|","m") >> astring = astring.replace("|\\","n") >> astring = astring.replace("0","o") >> astring = astring.replace("|*","p") >> astring = astring.replace("0\\","q") >> astring = astring.replace("2","r") >> astring = astring.replace("5","s") >> astring = astring.replace("+","t") >> astring = astring.replace("|_|","u") >> astring = astring.replace("\/","v") >> astring = astring.replace("\/\/","w") >> astring = astring.replace("><","x") >> astring = astring.replace("7","y") >> astring = astring.replace("7_","z") >> return astring >> >> print eng2leet(fileIn) >> >> Only problem is that when it needs to translate a U or a W it prints an L >> or 2 V's. Need some help please. Thanks >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Computers are like air conditioners... > They quit working when you open Windows. so is their some other way to go about this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Jul 27 21:08:08 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 27 Jul 2009 15:08:08 -0400 Subject: [Tutor] Eng to Leet Speek In-Reply-To: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> Message-ID: <4A6DFB18.9070809@ieee.org> Chris Castillo wrote: > so I have a string: > > 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 > \/\/1+# the |#a|-|i|_7? > > > and I am trying to turn it into english with the following code: > > fileIn = open("encrypted.txt", "r").read() > > def eng2leet(astring): > astring = astring.replace("4","a") > astring = astring.replace("8","b") > astring = astring.replace("[","c") > astring = astring.replace("|)","d") > astring = astring.replace("3","e") > astring = astring.replace("|#","f") > astring = astring.replace("6","g") > astring = astring.replace("#","h") > astring = astring.replace("1","i") > astring = astring.replace("]","j") > astring = astring.replace("|\\","k") > astring = astring.replace("|_","l") > astring = astring.replace("|-|","m") > astring = astring.replace("|\\","n") > astring = astring.replace("0","o") > astring = astring.replace("|*","p") > astring = astring.replace("0\\","q") > astring = astring.replace("2","r") > astring = astring.replace("5","s") > astring = astring.replace("+","t") > astring = astring.replace("|_|","u") > astring = astring.replace("\/","v") > astring = astring.replace("\/\/","w") > astring = astring.replace("><","x") > astring = astring.replace("7","y") > astring = astring.replace("7_","z") > return astring > > print eng2leet(fileIn) > > Only problem is that when it needs to translate a U or a W it prints an L or > 2 V's. Need some help please. Thanks > > Your problem is in the order of substitution. If you put the "v" test *after* the "w" test, you'll avoid one of your problems. And put the "l" test after the "u" test. And you didn't mention it, but "z" should come before "y". This is because some of your strings are substrings of others. A more general rule might be to put all the four-character substitutions first, then do all the three-character ones, then two, then one. That's not guaranteed to work, but by inspection I think it will. Another problem that could have hit you is that "\" is an escape character in strings. So you're taking advantage of the fact that \/ (for example) doesn't happen to be a valid escape sequence. The usual workaround is to use raw strings. For another example, look at the string for "n". Did you want two backslashes? You'll only get one as it sits. Did you mean for "k" and "n" to be the same? DaveA From rdmoores at gmail.com Mon Jul 27 21:09:15 2009 From: rdmoores at gmail.com (Dick Moores) Date: Mon, 27 Jul 2009 12:09:15 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> Message-ID: On Mon, Jul 27, 2009 at 09:32, Alan Gauld wrote: > > "Dick Moores" wrote > >>> I suggest you have to change the association of *.pyw files to the >>> program, which is used to 'open' it. >>> >> Yes! After I did that, now when I call >> E:\Python26\Lib\idlelib\idle.pyw the IDLE that opens uses 2.62. >> >> But I also want to use Ulipad, actually my main Python editor. When I >> call E:\Programs\Ulipad3.7\UliPad.pyw (by clicking on it in Explorer), >> Ulipad no longer opens. Before I made the change you suggested, at >> least Ulipad would open using 2.51. What can I do to use both IDLE and >> Ulipad with 2.62? > > What I do for these things is create a shortcut which specifies the full > path to the interpreter and to the pyw file. I also set the working foldeer > to wherever is most appropriate - usually my project folder. That's fairly > bulletproof in my experience! Alan, here's what have now to call Ulipad: the shortcut shown at . It opens Ulipad, but a Ulipad that uses 2.51, not 2.62 in its shell, but does use 2.62 to run scripts (Ulipad asked me which interpreter I wanted to use for that). So it seems I've almost got Ulipad where I want it. Perhaps the developer can help me get its shell to use 2.62 as well. I made a shortcut for IDLE that opens an IDLE that uses 2.62 (it's image is at ). Thanks, Dick From ctcast at gmail.com Mon Jul 27 21:23:28 2009 From: ctcast at gmail.com (Chris Castillo) Date: Mon, 27 Jul 2009 14:23:28 -0500 Subject: [Tutor] Eng to Leet Speek In-Reply-To: <4A6DFB18.9070809@ieee.org> References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> <4A6DFB18.9070809@ieee.org> Message-ID: <50e459210907271223r275534a9r17202ca065265c97@mail.gmail.com> On Mon, Jul 27, 2009 at 2:08 PM, Dave Angel wrote: > Chris Castillo wrote: > >> so I have a string: >> >> 1 4|-| 50 |_33+. I love [#ick3n 4nd ch3353. Don't you love +|_|2|\e7 >> \/\/1+# the |#a|-|i|_7? >> >> >> and I am trying to turn it into english with the following code: >> >> fileIn = open("encrypted.txt", "r").read() >> >> def eng2leet(astring): >> astring = astring.replace("4","a") >> astring = astring.replace("8","b") >> astring = astring.replace("[","c") >> astring = astring.replace("|)","d") >> astring = astring.replace("3","e") >> astring = astring.replace("|#","f") >> astring = astring.replace("6","g") >> astring = astring.replace("#","h") >> astring = astring.replace("1","i") >> astring = astring.replace("]","j") >> astring = astring.replace("|\\","k") >> astring = astring.replace("|_","l") >> astring = astring.replace("|-|","m") >> astring = astring.replace("|\\","n") >> astring = astring.replace("0","o") >> astring = astring.replace("|*","p") >> astring = astring.replace("0\\","q") >> astring = astring.replace("2","r") >> astring = astring.replace("5","s") >> astring = astring.replace("+","t") >> astring = astring.replace("|_|","u") >> astring = astring.replace("\/","v") >> astring = astring.replace("\/\/","w") >> astring = astring.replace("><","x") >> astring = astring.replace("7","y") >> astring = astring.replace("7_","z") >> return astring >> >> print eng2leet(fileIn) >> >> Only problem is that when it needs to translate a U or a W it prints an L >> or >> 2 V's. Need some help please. Thanks >> >> >> > Your problem is in the order of substitution. If you put the "v" test > *after* the "w" test, you'll avoid one of your problems. And put the "l" > test after the "u" test. And you didn't mention it, but "z" should come > before "y". This is because some of your strings are substrings of others. > A more general rule might be to put all the four-character substitutions > first, then do all the three-character ones, then two, then one. That's not > guaranteed to work, but by inspection I think it will. > > Another problem that could have hit you is that "\" is an escape character > in strings. So you're taking advantage of the fact that \/ (for example) > doesn't happen to be a valid escape sequence. The usual workaround is to > use raw strings. For another example, look at the string for "n". Did you > want two backslashes? You'll only get one as it sits. > > Did you mean for "k" and "n" to be the same? > > DaveA > > Yes that solved it and caught all exceptions (after changing the typo I had for the n) I really did not think about changing the order like that. I feel stupid for not thinking of that. Thank you for your insight. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Mon Jul 27 21:25:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 27 Jul 2009 21:25:16 +0200 Subject: [Tutor] subprocess.call In-Reply-To: References: Message-ID: <1248722716.5921.11.camel@infirit.homelinux.org> On Mon, 2009-07-27 at 14:40 -0400, davidwilson at Safe-mail.net wrote: > OK I think I found my error, here is what I did: > > flags = set([file for file in glob.glob('flag-*.svg')]) > > def call(cmd): > subprocess.call([cmd], shell=True) You hardly ever need shell=True. And using [cmd] is close but still not the way. Change it to simply cmd and read on. I would create an intermediate step creating the command you want suprocess to run. The first 3 parts never change in your script below. c = ['svg2png', '--width=17', '--height=12'] > for flag in flags: > name = flag[:-4] > out = name+'.png' You can add a list to a list so I would write the below as. call(c + [flag, out]) > call('svg2png --width=17 --height=12 %s %s' \ > % (flag, out)) > This should make subprocess take your full command. Whether the command is correct is another question ;-) Greets Sander From alan.gauld at btinternet.com Mon Jul 27 21:50:44 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 27 Jul 2009 19:50:44 +0000 (GMT) Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> Message-ID: <829301.66121.qm@web86707.mail.ird.yahoo.com> > > What I do for these things is create a shortcut which specifies the full > > path to the interpreter and to the pyw file. I also set the working foldeer > > to wherever is most appropriate - usually my project folder. That's fairly > > bulletproof in my experience! > > Alan, here's what have now to call Ulipad: the shortcut shown in the > attached image. It opens Ulipad, but a Ulipad that uses 2.51, not 2.62 So edit the Target field of the shortcut to say: E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw Or whatever combination of interpreter and editor you want. In other words explicitly specify both the interpreter and the file rather than relying on Windows file associations. And if that fails to work, the lasst resort is to write a batch file that calls the right file with the rigt interpreter and then create a shortcut to that! > at E:\Python26\pythonw.exe (is that what you mean by the > interpreter?). Yes that is the interpreter. Alan G. From alan.gauld at btinternet.com Mon Jul 27 22:02:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jul 2009 21:02:34 +0100 Subject: [Tutor] Eng to Leet Speek References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> Message-ID: "Chris Castillo" wrote > and I am trying to turn it into english with the following code: > > def eng2leet(astring): > astring = astring.replace("4","a") > astring = astring.replace("8","b") > astring = astring.replace("[","c") > astring = astring.replace("|)","d") You might want to investigate the maketrans and translate functions in the string module. The seem to be quite similar in intent to what you are trying to do? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Mon Jul 27 23:03:26 2009 From: rdmoores at gmail.com (Dick Moores) Date: Mon, 27 Jul 2009 14:03:26 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: <829301.66121.qm@web86707.mail.ird.yahoo.com> References: <4A6D8F25.5070300@aon.at> <829301.66121.qm@web86707.mail.ird.yahoo.com> Message-ID: On Mon, Jul 27, 2009 at 12:50, ALAN GAULD wrote: > > >> > What I do for these things is create a shortcut which specifies the full >> > path to the interpreter and to the pyw file. I also set the working foldeer >> > to wherever is most appropriate - usually my project folder. That's fairly >> > bulletproof in my experience! >> >> Alan, here's what have now to call Ulipad: the shortcut shown in the >> attached image. It opens Ulipad, but a Ulipad that uses 2.51, not 2.62 > > So edit the Target field of the shortcut to say: > > E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw No, I'd already tried that. Doesn't work. Nothing happens. > Or whatever combination of interpreter and editor you want. That is the correct combination. > In other words explicitly specify both the interpreter and the file rather than > relying on Windows file associations. > > And if that fails to work, the lasst resort is to write a batch file that calls > the right file with the rigt interpreter and then create a shortcut to that! Any chance you could write that batch file for me? Dick From alan.gauld at btinternet.com Mon Jul 27 23:32:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Jul 2009 22:32:02 +0100 Subject: [Tutor] How to use Python 2.6 with IDLE? References: <4A6D8F25.5070300@aon.at> <829301.66121.qm@web86707.mail.ird.yahoo.com> Message-ID: "Dick Moores" wrote >> So edit the Target field of the shortcut to say: >> >> E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw > > No, I'd already tried that. Doesn't work. Nothing happens. OK, You could try changing pythonw.exe tyo python.exe to bring up a console and watch for errors there.... Or just try typing the command into a console session till you get one that works! >> In other words explicitly specify both the interpreter and the file >> rather than >> relying on Windows file associations. >> >> And if that fails to work, the lasst resort is to write a batch file >> that calls >> the right file with the rigt interpreter and then create a shortcut to >> that! > > Any chance you could write that batch file for me? Look at the one used for IDLE in standard python - idle.bat. Just copy and edit it as suggested by someone earlier. Finally, never having used ulipad, is it the interpreter called by the editor that you are trying to change? Or the interpretor that runs the editor? When you say "nothing happens" do you mean the editor doesn't start? Or just that it still uses the wrong version of Python? If it's the interpreter used by the editor to run programs that may be defined in ulipad's config details somewhere - either an ini file or in the registry. In which case find it and edit it manually. Or it could be by ulipad reading it from the environment - in which case there won't be much you can do! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Tue Jul 28 00:19:49 2009 From: rdmoores at gmail.com (Dick Moores) Date: Mon, 27 Jul 2009 15:19:49 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> <829301.66121.qm@web86707.mail.ird.yahoo.com> Message-ID: On Mon, Jul 27, 2009 at 14:32, Alan Gauld wrote: > > "Dick Moores" wrote > >>> So edit the Target field of the shortcut to say: >>> >>> E:\Python26\pythonw.exe E:\Programs\Ulipad37\ulipad.pyw >> >> No, I'd already tried that. Doesn't work. Nothing happens. > > OK, You could try changing pythonw.exe tyo python.exe to > bring up a console and watch for errors there.... I get a console for a fraction of a second. Can't read anything it says. > Or just try typing the command into a console session till > you get one that works! >>> In other words explicitly specify both the interpreter and the file >>> rather than >>> relying on Windows file associations. >>> >>> And if that fails to work, the lasst resort is to write a batch file that >>> calls >>> the right file with the rigt interpreter and then create a shortcut to >>> that! >> >> Any chance you could write that batch file for me? > > Look at the one used for IDLE in standard python - idle.bat. > > Just copy and edit it as suggested by someone earlier. I'm not sure how to edit it. What's required for Ulipad is quite different, I believe. This is what I got from Dave Angel: e: cd \Python26\Lib\idlelib\ ..\..\pythonw.exe idle.pyw %* And I can't decipher it. What is the "..\..\"? I would like to learn how to write simple batch files, however, quite aside from writing one to solve my Ulipad problem. > Finally, never having used ulipad, is it the interpreter called by the > editor > that you are trying to change? Or the interpretor that runs the editor? The latter, I believe. > When you say "nothing happens" do you mean the editor doesn't start? Yes. > Or just that it still uses the wrong version of Python? > > If it's the interpreter used by the editor to run programs that may be > defined in ulipad's config details somewhere - either an ini file or > in the registry. ?In which case find it and edit it manually. > Or it could be by ulipad reading it from the environment - in which > case there won't be much you can do! I think I'll wait until the developer, who is in China (Beijing, I believe), wakes up and gets back to his computer. It's 6:19 am there now. If I understood him correctly, the version of Python Ulipad's shell uses should be the same as the version of Python it uses to run scripts inside Ulipad. But in my case, the shell runs 2.51; 2.62 runs my scripts. Thanks very much Alan, and everybody! If I get this solved, I'll write back. Dick From kent37 at tds.net Tue Jul 28 00:28:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Jul 2009 18:28:23 -0400 Subject: [Tutor] Eng to Leet Speek In-Reply-To: References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> Message-ID: <1c2a2c590907271528j1b9fae0blde9d54e14bdc0cca@mail.gmail.com> On Mon, Jul 27, 2009 at 4:02 PM, Alan Gauld wrote: > You might want to investigate the maketrans and translate functions in the > string module. > > The seem to be quite similar in intent to what you are trying to do? No, those will only do 1-for-1 character substitutions. Kent From memorylasts at gmail.com Tue Jul 28 00:17:51 2009 From: memorylasts at gmail.com (Ryan V) Date: Mon, 27 Jul 2009 15:17:51 -0700 Subject: [Tutor] Help... Message-ID: For this source code, i am getting some errors, and not sure how to fix it, as i am returning all the values. it is telling me that there is no value for the variables i am returning. any help is greatly appreciated! Source #main function def main(): print 'The menu is:' print 'Yum Yum Burger for $0.99' print 'Grease Yum Fries for $0.79' print 'Soda Yum For $1.09' mealOrder = input_meal() burgerPrice = input_burger() friesPrice = input_fries() sodaPrice = input_soda() mealEnd = input_mealEnd() calc_total(burgerPrice, friesPrice, sodaPrice) # print_info(total) def input_meal(): print 'If you want the Yum Yum Burger please press 1' print 'If you want the Grease Yum Fries please press 2' print 'If you want the Soda Yum please press 3' print 'If you entered no instead of yes just hit 4' mealOrder = input('Enter Now - ') if mealOrder == '1' : input_burger() elif mealOrder == '2' : input_fries() elif mealOrder == '3' : input_soda() elif mealOrder == '4' : calc_total(burgerPrice, friesPrice, sodaPrice) def input_burger(): amountBurger = input('How many burgers would you like?') burgerPrice = amountBurger * 0.99 input_mealEnd() return burgerPrice def input_fries(): amountFries = input('How many Fries would you like?') friesPrice = amountFries * 0.79 input_mealEnd() return friesPrice def input_soda(): amountSoda = input('How many sodas would you like?') sodaPrice = amountSoda * 1.09 input_mealEnd() return sodaPrice def input_mealEnd(): mealEnd = raw_input('Would you like to end your order? (Enter yes or no)') if mealEnd == 'yes' : calc_total(burgerPrice, friesPrice, sodaPrice) elif mealEnd == 'no' : input_meal() #Calculation of meal cost def calc_total(burgerPrice, friesPrice, sodaPrice): totalFood = burgerPrice + friesPrice + sodaPrice totalTax = totalFood * .06 total = totalTax + totalFood print 'The total price for food is $', totalFood print 'The Tax is $', totalTax print 'The total is $', total #Displays total, and what you ordered #def print_info(total): # print 'The meal price is $', total #call main function main() and here is the output i am getting The menu is: Yum Yum Burger for $0.99 Grease Yum Fries for $0.79 Soda Yum For $1.09 If you want the Yum Yum Burger please press 1 If you want the Grease Yum Fries please press 2 If you want the Soda Yum please press 3 If you entered no instead of yes just hit 4 Enter Now - 1 How many burgers would you like?2 Would you like to end your order? (Enter yes or no)no If you want the Yum Yum Burger please press 1 If you want the Grease Yum Fries please press 2 If you want the Soda Yum please press 3 If you entered no instead of yes just hit 4 Enter Now - 2 How many Fries would you like?2 Would you like to end your order? (Enter yes or no)no If you want the Yum Yum Burger please press 1 If you want the Grease Yum Fries please press 2 If you want the Soda Yum please press 3 If you entered no instead of yes just hit 4 Enter Now - 3 How many sodas would you like?2 Would you like to end your order? (Enter yes or no)yes *Traceback (most recent call last): File "...", line 74, in main() File "...", line 16, in main sodaPrice = input_soda() File "...", line 51, in input_soda input_mealEnd() File "...", line 57, in input_mealEnd calc_total(burgerPrice, friesPrice, sodaPrice) NameError: global name 'burgerPrice' is not defined* -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Jul 28 00:52:12 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 27 Jul 2009 18:52:12 -0400 Subject: [Tutor] Eng to Leet Speek In-Reply-To: <1c2a2c590907271528j1b9fae0blde9d54e14bdc0cca@mail.gmail.com> References: <50e459210907271113s70348b5fm85c9ccd34280a253@mail.gmail.com> <1c2a2c590907271528j1b9fae0blde9d54e14bdc0cca@mail.gmail.com> Message-ID: <4A6E2F9C.1010801@gmail.com> Kent Johnson wrote: > On Mon, Jul 27, 2009 at 4:02 PM, Alan Gauld wrote: > > >> You might want to investigate the maketrans and translate functions in the >> string module. >> >> The seem to be quite similar in intent to what you are trying to do? >> > > No, those will only do 1-for-1 character substitutions. Which could be applied to all the 1 character substitutions after dealing with the multi-character ones. -- Bob Gailer Chapel Hill NC 919-636-4239 From paras80 at gmail.com Tue Jul 28 00:47:41 2009 From: paras80 at gmail.com (Paras K.) Date: Mon, 27 Jul 2009 18:47:41 -0400 Subject: [Tutor] Getting Data from a Web Page Message-ID: First let me say this mailing list is GREAT!!! Has helped me out through many things. I have written some code with Python that currently goes through a directory of all csv files and pulls out the lines that are needed by this program. These csv files have the following information: IP Address, Activity, Count, Date Currently the code looks at the IP address and if it is part of the range overall range then it writes it to a new csv file. I have two things that I would like to improve on: 1) If the IP address falls within a specific range I want it to add an indicator at the end of it like -- NONDHCP IP (I believe I know how to do this, but any suggestion would be great) 2) If the IP is a DHCP IP -- I want it to be able to get the data from a webpage -- this webpage has like user information and etc. Is there any way to do that? Thank You for all your help in advance!!! -- Paras -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Tue Jul 28 01:39:25 2009 From: pine508 at hotmail.com (Che M) Date: Mon, 27 Jul 2009 19:39:25 -0400 Subject: [Tutor] self.name vs. passing a name Message-ID: This is another very basic structural question, related to one I asked last week, and again is not necessarily germane only to Python. Let's say you have a sequence of two calculations or manipulations you need to do, each one done as a function called by an overall calculate_something() function. The "answer" to each function is then used in the next function. I can think of two ways to make that answer available for use in the next function: 1) pass it in, or 2) declare it as self.answer and then it is available to the whole class instance. What are the dis/advantages to these two different ways? Here are examples, with only the overall calculate_something() function shown: 1.Pass the variable to the second function. def calculate_something(self): answer = self.do_first_calculation() #1st function returns answer self.do_second_calculation(answer) #2nd is passed answer and uses it. 2. Create the variable in the class instance scope and use that in the second function. def calculate_something(self): self.do_first_calculation() #1st function creates self.answer self.do_second_calculation() #2nd uses self.answer Both of these approaches can work, but I would like to better understand when it is best to do one or the other. Obviously if I know I will need to make self.answer available for use by other functions, I would want to choose (2). But what other considerations should I, well, consider? Thanks, Che _________________________________________________________________ NEW mobile Hotmail. Optimized for YOUR phone. Click here. http://windowslive.com/Mobile?ocid=TXT_TAGLM_WL_CS_MB_new_hotmail_072009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jul 28 01:40:34 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 27 Jul 2009 23:40:34 +0000 (GMT) Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> <829301.66121.qm@web86707.mail.ird.yahoo.com> Message-ID: <839711.54252.qm@web86711.mail.ird.yahoo.com> > I get a console for a fraction of a second. Can't read anything it says. > > > Or just try typing the command into a console session till > > you get one that works! > So what happens when you run the same command from a console? That should leave the errors visible. > I'm not sure how to edit it. What's required for Ulipad is quite > different, I believe. It shouldn't be, it just calls the interpreter with the pyw file to launch the editor and passes along any other command line arguments given to the bat file. > This is what I got from Dave Angel: > e: > cd \Python26\Lib\idlelib\ > ..\..\pythonw.exe idle.pyw %* > > And I can't decipher it. What is the "..\..\"? .. means the folder one level up, so ..\..\pythonw.exe means backup two levelsand call pythonw.exe there > I would like to learn how to write simple batch files, however, quite > aside from writing one to solve my Ulipad problem. It is a useful skill. > > that you are trying to change? Or the interpretor that runs the editor? > > The latter, I believe. OK, thats what I initially thought, but then wondered... > > When you say "nothing happens" do you mean the editor doesn't start? > > Yes. I'd definitely try running from a command prompt. > I think I'll wait until the developer, who is in China (Beijing, I > believe), wakes up and gets back to his computer. That might be best :-) > now. If I understood him correctly, the version of Python Ulipad's > shell uses should be the same as the version of Python it uses to run > scripts inside Ulipad. But in my case, the shell runs 2.51; 2.62 runs > my scripts. Now I'm confused again. What do you mean by the shell? Does Ulipad have a shell window like IDLE? If so it is almost certainly using the same interpreter as is running the editor itself (because the shell is probavbly using exec() ) The version of Python used to run your scripts could be anything however. Alan G. From kent37 at tds.net Tue Jul 28 03:39:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Jul 2009 21:39:30 -0400 Subject: [Tutor] self.name vs. passing a name In-Reply-To: References: Message-ID: <1c2a2c590907271839u4ebb2ee6qcfe9503bff37fa32@mail.gmail.com> On Mon, Jul 27, 2009 at 7:39 PM, Che M wrote: > 1.Pass the variable to the second function. > > def calculate_something(self): > ??? answer = self.do_first_calculation()??? #1st function returns answer > ??? self.do_second_calculation(answer)??? #2nd is passed answer and uses it. > > 2. Create the variable in the class instance scope and use that in the > second function. > > def calculate_something(self): > ??? self.do_first_calculation()???????????????? #1st function creates > self.answer > ??? self.do_second_calculation()???????????? #2nd uses self.answer > > Both of these approaches can work, but I would like to better understand > when it is best to do one or the other. i would use the first method. - it makes explicit that do_first_calculation() is computing something needed by the second - you could give the variable a better name which would make it easier to understand calculate_something() - answer is not part of the state of self and it has no meaning outside of calculate_something(), so don't clutter up self with the extra value. kent From mobiledreamers at gmail.com Tue Jul 28 05:31:25 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 27 Jul 2009 20:31:25 -0700 Subject: [Tutor] [Baypiggies] Egnyte: hiring In-Reply-To: <20090728024611.GA4649@panix.com> References: <20090728024611.GA4649@panix.com> Message-ID: Seems interesting http://fotoroll.com/searchvideo?q=vineet%20jain,%20ceo%20of%20egnyte&id=0&type=video On Mon, Jul 27, 2009 at 7:46 PM, Aahz wrote: > My new company (I just started today) closed a big venture capital round > (also today) and is looking to hire more people, preferably with Python > experience: > > Senior Linux Engineer: > http://sfbay.craigslist.org/pen/sof/1292008176.html > > Senior Platforms Engineer: > http://sfbay.craigslist.org/pen/sof/1291776907.html > > Venture announcement: > http://blogs.zdnet.com/BTL/?p=21777 > > I can't say a lot about the company myself yet, but I've gotten a good > impression of the team and the business plan. Find out more here: > http://www.egnyte.com/ > -- > Aahz (aahz at pythoncraft.com) <*> > http://www.pythoncraft.com/ > > "Many customs in this life persist because they ease friction and promote > productivity as a result of universal agreement, and whether they are > precisely the optimal choices is much less important." --Henry Spencer > _______________________________________________ > Baypiggies mailing list > Baypiggies at python.org > To change your subscription options or unsubscribe: > http://mail.python.org/mailman/listinfo/baypiggies > -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cynicalairrick at gmail.com Tue Jul 28 05:32:24 2009 From: cynicalairrick at gmail.com (Luis Galvan) Date: Mon, 27 Jul 2009 20:32:24 -0700 Subject: [Tutor] No Elegant XML Output in ElementTree? Message-ID: <5cd723fd0907272032t241f338l706785bea248d03a@mail.gmail.com> Hi tutors, Okay, so I just started to learn ElementTree (and XML processing in general) and I just can't, for the life of me, find a way to output the XML file in an actual hierarchic presentation. What I mean by this is that it all outputs on a single line. For example, I create an element tree in python: ____________________________ from xml.etree.ElementTree import ElementTree, SubElement, Element # Create example tree. root = Element("BFTypedBinder") root.set("binderType", "codename") # There's no point in this loop, it's only here for kicks. while True: x = raw_input("Yes or No? ") if x == "Yes": head = SubElement(root, "sample") title = SubElement(head, "sample2") title.text = "Sample Text" body = SubElement(root, "sample3") body.set("this", "that") body.text = "Done" break elif x == "No": break # Save output. tree = ElementTree(root) tree.write(xml.xml) ___________________________ Output using Notepad: Sample TextDone If I open xml.xml in Notepad, the whole tree is printed on one line, which isn't what I want. Of course, if I double click the file itself, it looks normal, but I still need the data itself to look hierarchic as well (It's a personal preference, and much more convenient when editing in a text editor). A few months back when I was attempting to learn Minidom, it didn't have this problem. I have looked through python.org's online documentation on ET and there's no method, class, or function that could help me achieve this, at least that I'm aware of. I know I might have to write a solution myself, but before I try (which would probably be disasterous), is there some existing built-in class in here that can help me without having to "reinvent the wheel"? -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Jul 28 07:55:44 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 27 Jul 2009 22:55:44 -0700 Subject: [Tutor] No Elegant XML Output in ElementTree? In-Reply-To: <5cd723fd0907272032t241f338l706785bea248d03a@mail.gmail.com> References: <5cd723fd0907272032t241f338l706785bea248d03a@mail.gmail.com> Message-ID: <40af687b0907272255m14f1f8b4re639d03d74c8ebb9@mail.gmail.com> On Mon, Jul 27, 2009 at 8:32 PM, Luis Galvan wrote: > Hi tutors, > Okay, so I just started to learn ElementTree (and XML processing in > general) and I just can't, for the life of me, find a way to output the XML > file in an actual hierarchic presentation. What you want is generically called "prettyprinting". I don't use ElementTree myself (I use Amara/Akara), so I don't know whether effbot followed through on this, but take a look at this page: http://effbot.org/zone/element-lib.htm I also found this page: http://renesd.blogspot.com/2007/05/pretty-print-xml-with-python.html and in the comments there's this, which looks pretty simple: To pretty print an ElementTree: from xml.minidom import parseString from xml.etree import ElementTree def prettyPrint(element): txt = ElementTree.tostring(element) print minidom.parseString(txt).toprettyxml() Substitute output to a file for "print", and you're done.In Amara, I do this: def Save(self): outFile = open(self.fileName,'w+b') self.xDoc.xml(outFile,indent=u'yes') outFile.close() but that's not much help for etree, I know... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Jul 28 08:15:18 2009 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 28 Jul 2009 08:15:18 +0200 Subject: [Tutor] Help... In-Reply-To: References: Message-ID: <4A6E9776.8070501@compuscan.co.za> Ryan V wrote: > For this source code, i am getting some errors, and not sure how to > fix it, as i am returning all the values. it is telling me that there > is no value for the variables i am returning. any help is greatly > appreciated! > Source > #main function > def main(): > print 'The menu is:' > print 'Yum Yum Burger for $0.99' > print 'Grease Yum Fries for $0.79' > print 'Soda Yum For $1.09' > mealOrder = input_meal() > burgerPrice = input_burger() > friesPrice = input_fries() > sodaPrice = input_soda() > mealEnd = input_mealEnd() > calc_total(burgerPrice, friesPrice, sodaPrice) > # print_info(total) > > def input_meal(): > print 'If you want the Yum Yum Burger please press 1' > print 'If you want the Grease Yum Fries please press 2' > print 'If you want the Soda Yum please press 3' > print 'If you entered no instead of yes just hit 4' > mealOrder = input('Enter Now - ') > if mealOrder == '1' : > input_burger() > elif mealOrder == '2' : > input_fries() > elif mealOrder == '3' : > input_soda() > elif mealOrder == '4' : > calc_total(burgerPrice, friesPrice, sodaPrice) > > def input_burger(): > amountBurger = input('How many burgers would you like?') > burgerPrice = amountBurger * 0.99 > input_mealEnd() > return burgerPrice > > def input_fries(): > amountFries = input('How many Fries would you like?') > friesPrice = amountFries * 0.79 > input_mealEnd() > return friesPrice > > def input_soda(): > amountSoda = input('How many sodas would you like?') > sodaPrice = amountSoda * 1.09 > input_mealEnd() > return sodaPrice > > def input_mealEnd(): > mealEnd = raw_input('Would you like to end your order? (Enter yes > or no)') > if mealEnd == 'yes' : > calc_total(burgerPrice, friesPrice, sodaPrice) > elif mealEnd == 'no' : > input_meal() > > #Calculation of meal cost > def calc_total(burgerPrice, friesPrice, sodaPrice): > totalFood = burgerPrice + friesPrice + sodaPrice > totalTax = totalFood * .06 > total = totalTax + totalFood > print 'The total price for food is $', totalFood > print 'The Tax is $', totalTax > print 'The total is $', total > #Displays total, and what you ordered > #def print_info(total): > # print 'The meal price is $', total > > #call main function > main() > and here is the output i am getting > > The menu is: > Yum Yum Burger for $0.99 > Grease Yum Fries for $0.79 > Soda Yum For $1.09 > If you want the Yum Yum Burger please press 1 > If you want the Grease Yum Fries please press 2 > If you want the Soda Yum please press 3 > If you entered no instead of yes just hit 4 > Enter Now - 1 > How many burgers would you like?2 > Would you like to end your order? (Enter yes or no)no > If you want the Yum Yum Burger please press 1 > If you want the Grease Yum Fries please press 2 > If you want the Soda Yum please press 3 > If you entered no instead of yes just hit 4 > Enter Now - 2 > How many Fries would you like?2 > Would you like to end your order? (Enter yes or no)no > If you want the Yum Yum Burger please press 1 > If you want the Grease Yum Fries please press 2 > If you want the Soda Yum please press 3 > If you entered no instead of yes just hit 4 > Enter Now - 3 > How many sodas would you like?2 > Would you like to end your order? (Enter yes or no)yes > *Traceback (most recent call last): > File "...", line 74, in > main() > File "...", line 16, in main > sodaPrice = input_soda() > File "...", line 51, in input_soda > input_mealEnd() > File "...", line 57, in input_mealEnd > calc_total(burgerPrice, friesPrice, sodaPrice) > NameError: global name 'burgerPrice' is not defined* > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You're caliing calc_total() in your input_mealEnd() function and in the scope of that function there are no variables names burgerPrice, friesPrice or sodaPrice. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Tue Jul 28 10:48:26 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Jul 2009 09:48:26 +0100 Subject: [Tutor] Help... References: Message-ID: "Ryan V" wrote > as i am returning all the values. it is telling me that there is no value > for the variables i am returning. any help is greatly appreciated! You are returning the values to variables in the main function. But in Python variables inside functions (aka local variables) are only visible inside that fuinction, they are NOT cvisible to functions that are called from inside the same function. So yor variables in main() are not visible to the input_xxxx set of functions. They are visible to calc_price because you pass them in as arguments. > def main(): > print 'The menu is:' > print 'Yum Yum Burger for $0.99' > print 'Grease Yum Fries for $0.79' > print 'Soda Yum For $1.09' > mealOrder = input_meal() > burgerPrice = input_burger() > friesPrice = input_fries() > sodaPrice = input_soda() > mealEnd = input_mealEnd() > calc_total(burgerPrice, friesPrice, sodaPrice) > # print_info(total) > > def input_meal(): > print 'If you want the Yum Yum Burger please press 1' > print 'If you want the Grease Yum Fries please press 2' > print 'If you want the Soda Yum please press 3' > print 'If you entered no instead of yes just hit 4' Whee would the user enter no instead of yes? At this stage of the program you haven't asked them to enter yes or no. BTW from a presentation point of view you might want to put the menu in a long string using triple quotes which will help you align the menu options: print ''' If you want the Yum Yum Burger please press 1 If you want the Grease Yum Fries please press 2 If you want the Soda Yum please press 3 If you entered no instead of yes just hit 4 ''' > mealOrder = input('Enter Now - ') In Python 2.x using input() is considered a bad idea since it allows users to (deliberately or by accident) enter python code that could do damage to your program or even your computer! Its better to use raw_input() and convert the result to the required type, such as int. mealOrder = int( raw_input('Enter Now - ') ) Slightly more typing but much safer. > if mealOrder == '1' : > input_burger() > elif mealOrder == '2' : > input_fries() > elif mealOrder == '3' : > input_soda() > elif mealOrder == '4' : > calc_total(burgerPrice, friesPrice, sodaPrice) But this won't work because you are inside input_meal() which doesn''t have any variables called burgerPrice etc. However, this also means that you are going to call calc_total twice, since after you return from input_meal() you also call calc_total in main(). I suspect you don't want that, instead you want to return the values back to main so that calc_total there can do the calculation after all the data collection has been completed? > def input_burger(): > amountBurger = input('How many burgers would you like?') > burgerPrice = amountBurger * 0.99 > input_mealEnd() > return burgerPrice Now this is where it gets really complicated. You call input_MealEnd here which in turn can call input_meal which in turn can call input_burger and so on. This kind of deep cyclic tree of function calls is called recursion and is not the best way to control the flow of your code. Look at using loops and branches to do that at the top level. The top level function should control the flow of your program, the lower level functions should perform only one step and return a value. > def input_fries(): > amountFries = input('How many Fries would you like?') > friesPrice = amountFries * 0.79 > input_mealEnd() > return friesPrice Notice that these other functions are exactly the same as each other apart from the names you used for the variables. You could therefore write one function that takes the food and price as parameters: > def input_food(food, price): > amount = int( raw_input('How many %s would you like?' % food) ) > thePrice = amount * price > return thePrice You would then call it as: friesPrice = input_food('fries', 0.79) > def input_mealEnd(): > mealEnd = raw_input('Would you like to end your order? (Enter yes or > no)') > if mealEnd == 'yes' : > calc_total(burgerPrice, friesPrice, sodaPrice) > elif mealEnd == 'no' : > input_meal() And here we have yet another call to calc_total.... > #Calculation of meal cost > def calc_total(burgerPrice, friesPrice, sodaPrice): > totalFood = burgerPrice + friesPrice + sodaPrice > totalTax = totalFood * .06 > total = totalTax + totalFood > print 'The total price for food is $', totalFood > print 'The Tax is $', totalTax > print 'The total is $', total Its probably better not to print the values in a rfunction that claims to calculate. Instead return the values so that a display function can print them suitable formatted. That way you can easily change the display(to HTML say) without changing the calculation functions. So instead of the print lines simply return the three values: return totalFood, totalTax, total > #Displays total, and what you ordered > #def print_info(total): > # print 'The meal price is $', total Then I'd extend this to print all of the values that were in the calc_total function > Would you like to end your order? (Enter yes or no)yes > *Traceback (most recent call last): > File "...", line 74, in > main() > File "...", line 16, in main > sodaPrice = input_soda() > File "...", line 51, in input_soda > input_mealEnd() > File "...", line 57, in input_mealEnd > calc_total(burgerPrice, friesPrice, sodaPrice) > NameError: global name 'burgerPrice' is not defined* Remember the local variables of function A are not visible to functions that are called by A HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jul 28 10:54:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Jul 2009 09:54:04 +0100 Subject: [Tutor] self.name vs. passing a name References: Message-ID: "Che M" wrote > Let's say you have a sequence of two calculations ...each one > done as a function called by an overall calculate_something() function. > The "answer" to each function is then used in the next function. > I can think of two ways to make that answer available ... > 1) pass it in, or > 2) declare it as self.answer The first is the best solution in the general case however, 1) if your functions are methods of a class AND 2) you can use the intermediate result for something useful elsewhere in the class then you could use the second method. Otherwise the second merthod is just a variation in storing the result in a global variable wjhich is generally considered a bad design style. In general keep data as close to its point of use as possible. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Tue Jul 28 11:20:23 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 28 Jul 2009 05:20:23 -0400 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <4A6D8F25.5070300@aon.at> <829301.66121.qm@web86707.mail.ird.yahoo.com> Message-ID: <4A6EC2D7.2080006@ieee.org> Dick Moores wrote: > > > I'm not sure how to edit it. What's required for Ulipad is quite > different, I believe. > > This is what I got from Dave Angel: > e: > cd \Python26\Lib\idlelib\ > ..\..\pythonw.exe idle.pyw %* > > And I can't decipher it. What is the "..\..\"? > > Just ask. The double-dots are the standard way of indicating "the directory above the previous one." That's useful knowledge not only within batch files but also within shortcuts and within Python programs. The batch file starts by changing to the E: drive. Then it changes to the explicit directory \Python26\Lib\idlelib, and because of the leading slash, that refers to an absolute directory, irrespective of what the current directory happened to be earlier. The 3rd line means that we want to run a program pythonw.exe, located two directories up from the current one, *without changing" the current directory. It could have been written: e:\Python26\pythonw.exe idle.pyw %* but then if you ever changed to a different version, or installed on a different drive or directory, you'd have two places in the batch file to change. I like using relative directories where possible. Finally, the %* at the end means copy whatever other parameters were passed to the batch file, as additional parameters to the program. > I would like to learn how to write simple batch files, however, quite > aside from writing one to solve my Ulipad problem. > > > From davea at ieee.org Tue Jul 28 12:04:12 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 28 Jul 2009 06:04:12 -0400 Subject: [Tutor] Help... In-Reply-To: References: Message-ID: <4A6ECD1C.6050406@ieee.org> Ryan V wrote: > For this source code, i am getting some errors, and not sure how to fix it, > as i am returning all the values. it is telling me that there is no value > for the variables i am returning. any help is greatly appreciated! > Source > #main function > def main(): > print 'The menu is:' > print 'Yum Yum Burger for $0.99' > print 'Grease Yum Fries for $0.79' > print 'Soda Yum For $1.09' > mealOrder = input_meal() > burgerPrice = input_burger() > friesPrice = input_fries() > sodaPrice = input_soda() > mealEnd = input_mealEnd() > calc_total(burgerPrice, friesPrice, sodaPrice) > # print_info(total) > > def input_meal(): > print 'If you want the Yum Yum Burger please press 1' > print 'If you want the Grease Yum Fries please press 2' > print 'If you want the Soda Yum please press 3' > print 'If you entered no instead of yes just hit 4' > mealOrder = input('Enter Now - ') > if mealOrder == '1' : > input_burger() > elif mealOrder == '2' : > input_fries() > elif mealOrder == '3' : > input_soda() > elif mealOrder == '4' : > calc_total(burgerPrice, friesPrice, sodaPrice) > > def input_burger(): > amountBurger = input('How many burgers would you like?') > burgerPrice = amountBurger * 0.99 > input_mealEnd() > return burgerPrice > > def input_fries(): > amountFries = input('How many Fries would you like?') > friesPrice = amountFries * 0.79 > input_mealEnd() > return friesPrice > > def input_soda(): > amountSoda = input('How many sodas would you like?') > sodaPrice = amountSoda * 1.09 > input_mealEnd() > return sodaPrice > > def input_mealEnd(): > mealEnd = raw_input('Would you like to end your order? (Enter yes or > no)') > if mealEnd == 'yes' : > calc_total(burgerPrice, friesPrice, sodaPrice) > elif mealEnd == 'no' : > input_meal() > > #Calculation of meal cost > def calc_total(burgerPrice, friesPrice, sodaPrice): > totalFood = burgerPrice + friesPrice + sodaPrice > totalTax = totalFood * .06 > total = totalTax + totalFood > print 'The total price for food is $', totalFood > print 'The Tax is $', totalTax > print 'The total is $', total > #Displays total, and what you ordered > #def print_info(total): > # print 'The meal price is $', total > > #call main function > main() > and here is the output i am getting > > The menu is: > Yum Yum Burger for $0.99 > Grease Yum Fries for $0.79 > Soda Yum For $1.09 > If you want the Yum Yum Burger please press 1 > If you want the Grease Yum Fries please press 2 > If you want the Soda Yum please press 3 > If you entered no instead of yes just hit 4 > Enter Now - 1 > How many burgers would you like?2 > Would you like to end your order? (Enter yes or no)no > If you want the Yum Yum Burger please press 1 > If you want the Grease Yum Fries please press 2 > If you want the Soda Yum please press 3 > If you entered no instead of yes just hit 4 > Enter Now - 2 > How many Fries would you like?2 > Would you like to end your order? (Enter yes or no)no > If you want the Yum Yum Burger please press 1 > If you want the Grease Yum Fries please press 2 > If you want the Soda Yum please press 3 > If you entered no instead of yes just hit 4 > Enter Now - 3 > How many sodas would you like?2 > Would you like to end your order? (Enter yes or no)yes > *Traceback (most recent call last): > File "...", line 74, in > main() > File "...", line 16, in main > sodaPrice = input_soda() > File "...", line 51, in input_soda > input_mealEnd() > File "...", line 57, in input_mealEnd > calc_total(burgerPrice, friesPrice, sodaPrice) > NameError: global name 'burgerPrice' is not defined* > > Please tell us - is this your first programming language, or are you comfortable with another, and you need to see how Python differs from it? I suspect it's your first. The main problem is that you're trying to use a function meal_end() to do flow control that needs to be in main(). Each time the user says "no" to "Would you like to end your order" you don't loop back to the same place, you call a new copy of input_meal(). (That's called recursion, and it's very useful, but not here). But you never return to the first copy of input_meal(). So you end up with several copies of that function. And only when all of them return (which won't happen) would you get back to main(). You need a loop (while or for), not recursion. Second problem is that you're calling functions that return values, and only some of the time recording those actual values anywhere. When/if input_meal() calls input_burger(), it doesn't save the result anywhere. So if it did return, main() still couldn't get the value, it's already lost. Third problem is that you have function input_mealEnd() that defines only one variable, but then expect three others to somehow have useful values. Fourth is that you don't have a good way to terminate the program. Where do you expect to go after printing the current order? You might expect to start a new order, or something else, but that would require that you be back at main(), or returning from main(). The best answer to the loop problem is to make a loop either in main() or in input_meal(). Currently it's not clear which one you had intended to be the loop, since they both expect to ask for all the items. Since input_meal() never returns, main() never gets its chance to ask, nor to save the results. But basically, you have to consolidate these two functions, and make most of the function a while-loop. The best answer to the problem of the local variables is to define a class. In fact, all these functions should probably be methods of that class. Then you'd have an instance of the class for each customer, and member data (attributes) for each of the things she can order. But I expect that classes are a later lesson in your course. So you probably need to arrange that all data is propagated back to your primary loop, so it's all visible at the same time. So, to fix the problems: truncate main() after the call to input_meal(). let input_meal() do all the work for this customer, and maybe main() will someday ask for next customer or something like that. input_meal() needs to be a while loop You need to start by initializing the three variables burgerPrice, friesPrice, and sodaPrice to 0, so they'll always have some value. Initlialize meal_order to 0 as well, and loop while it's not equal to 4. Now, when input_meal calls each of those functions, you have two choices, based on the answer to the following question. What do you want to happen if the customer chooses "burgers" twice, and enters two different amounts? Does he get both orders, or does the second value replace the first? That will determine what you do with the return value of input_burger(), for example. Now, when the while loop finishes, you can print the totals and return to main(). You're done with that customer. DaveA From davea at ieee.org Tue Jul 28 12:18:20 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 28 Jul 2009 06:18:20 -0400 Subject: [Tutor] self.name vs. passing a name In-Reply-To: References: Message-ID: <4A6ED06C.5020107@ieee.org> Che M wrote: > This is another very basic structural question, related to one I asked last week, and again is not necessarily germane only to Python. > > Let's say you have a sequence of two calculations or manipulations you need to do, each one done as a function called by an overall calculate_something() function. The "answer" to each function is then used in the next function. I can think of two ways to make that answer available for use in the next function: 1) pass it in, or 2) declare it as self.answer and then it is available to the whole class instance. > > What are the dis/advantages to these two different ways? Here are examples, with only the overall calculate_something() function shown: > > 1.Pass the variable to the second function. > > def calculate_something(self): > answer = self.do_first_calculation() #1st function returns answer > self.do_second_calculation(answer) #2nd is passed answer and uses it. > > 2. Create the variable in the class instance scope and use that in the second function. > > def calculate_something(self): > > self.do_first_calculation() #1st function creates self.answer > > self.do_second_calculation() #2nd uses self.answer > > Both of these approaches can work, but I would like to better understand when it is best to do one or the other. Obviously if I know I will need to make self.answer available for use by other functions, I would want to choose (2). But what other considerations should I, well, consider? > > Thanks, > Che > > > You call these functions, but since you have the "self" argument, I'll assume it's a method instead. use #2 only if the "answer" is relevant for further operations, AND (is time-consuming to calculate compared to the memory consumed by storing it, OR if calculating it has side effects) prefer #1 because: it doesn't take up space in the object it goes away when the particular method ends, not when the object is destroyed (rule -- the sooner the better) it doesn't clutter the namespace of the class From rdmoores at gmail.com Tue Jul 28 12:35:59 2009 From: rdmoores at gmail.com (Dick Moores) Date: Tue, 28 Jul 2009 03:35:59 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: <4A6EC2D7.2080006@ieee.org> References: <4A6D8F25.5070300@aon.at> <829301.66121.qm@web86707.mail.ird.yahoo.com> <4A6EC2D7.2080006@ieee.org> Message-ID: On Tue, Jul 28, 2009 at 02:20, Dave Angel wrote: > Dick Moores wrote: >> >> >> I'm not sure how to edit it. What's required for Ulipad is quite >> different, I believe. >> >> This is what I got from Dave Angel: >> e: >> cd \Python26\Lib\idlelib\ >> ..\..\pythonw.exe idle.pyw %* >> >> And I can't decipher it. What is the "..\..\"? >> >> > > Just ask. The double-dots are the standard way of indicating "the > directory above the previous one." That's useful knowledge not only within > batch files but also within shortcuts and within Python programs. > > The batch file starts by changing to the E: drive. Then it changes to the > explicit directory \Python26\Lib\idlelib, and because of the leading slash, > that refers to an absolute directory, irrespective of what the current > directory happened to be earlier. The 3rd line means that we want to run a > program pythonw.exe, located two directories up from the current one, > *without changing" the current directory. It could have been written: > > e:\Python26\pythonw.exe idle.pyw %* > > but then if you ever changed to a different version, or installed on a > different drive or directory, you'd have two places in the batch file to > change. I like using relative directories where possible. > > Finally, the %* at the end means copy whatever other parameters were passed > to the batch file, as additional parameters to the program. Thanks, Dave. Very informative. Dick From vnbang2003 at yahoo.com Tue Jul 28 15:10:39 2009 From: vnbang2003 at yahoo.com (VIJAY KUMAR) Date: Tue, 28 Jul 2009 18:40:39 +0530 (IST) Subject: [Tutor] Django test case problem In-Reply-To: <24680724.post@talk.nabble.com> Message-ID: <556769.22953.qm@web95309.mail.in2.yahoo.com> Hi, ?? I am running testcase from django when I run them from models.py it run. ?? But when I put the same in test.py in the same directory where models is define it not even getting called. ? My structure django application is? mysite Settings.py ???????? Urls.py ??????????Polls ???????????????? __int__.py ?????????????????models.py ???????????????? test.py ???????????????? views.py I used this command to run the test cases?? python manage.py test polls Can some help me know what am I missing or should need to do something? so my testcase from test.py start get executed. I tried to follow this link for the same http://docs.djangoproject.com/en/dev/topics/testing/ ? ? ? with thanks Vijay ? Love Cricket? Check out live scores, photos, video highlights and more. Click here http://cricket.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From amrita at iisermohali.ac.in Tue Jul 28 15:23:00 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Tue, 28 Jul 2009 18:53:00 +0530 (IST) Subject: [Tutor] how to get blank value In-Reply-To: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> Message-ID: <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> Sorry to say, but till now I have not got the solution of my problem, I tried with this command:- import re if __name__ == '__main__': data = open('chem.txt').readlines() for line in data: RE = re.compile('C = (.)',re.M) matches = RE.findall(line) for m in matches: print line but with this also I am getting those lines for which C value is there. > Hi, > > I have a file having lines:- > > 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = > 85 ALA H = 8.60 N = CA = HA = 4.65 C = > > Now i want to make two another file in which i want to put those lines for > which C is missing and another one for which N,CA and C all are missing, > > With these commands:- > > import re > f = open('chem.txt') > for line in f: > if re.search('C = ',line): > print line > > I am getting those lines for which C value is there but how to get those > one for which it doesn't have any value, i did google search but still i > am not getting. > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From bgailer at gmail.com Tue Jul 28 16:17:36 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 28 Jul 2009 10:17:36 -0400 Subject: [Tutor] how to get blank value In-Reply-To: <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> Message-ID: <4A6F0880.9@gmail.com> amrita at iisermohali.ac.in wrote: > Sorry to say, but till now I have not got the solution of my problem, I > tried with this command:- > > import re > > # assuming H = , N = , CA = , HA = and C = always present in that order if __name__ == '__main__': data = open('chem.txt').readlines() for line in data: line = line.split('=') if not line[5]: # C value missing if len(line[2])==1 and len(line[3])==1: # N and CA values missing print "all missing", line else: print "C missing", line > > >> Hi, >> >> I have a file having lines:- >> >> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 >> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = >> 85 ALA H = 8.60 N = CA = HA = 4.65 C = >> >> Now i want to make two another file in which i want to put those lines for >> which C is missing and another one for which N,CA and C all are missing, >> >> With these commands:- >> >> import re >> f = open('chem.txt') >> for line in f: >> if re.search('C = ',line): >> print line >> >> I am getting those lines for which C value is there but how to get those >> one for which it doesn't have any value, i did google search but still i >> am not getting. >> >> Amrita Kumari >> Research Fellow >> IISER Mohali >> Chandigarh >> INDIA >> >> >> -- Bob Gailer Chapel Hill NC 919-636-4239 From eduardo.susan at gmail.com Tue Jul 28 16:48:13 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 28 Jul 2009 08:48:13 -0600 Subject: [Tutor] Messages not going through (testing again) Message-ID: <9356b9f30907280748mb711b9ex894e59769bb89a79@mail.gmail.com> Hello, this is just a test. I have posted 2 different messages and they have never reached this list. Eduardo From madhav.bnk at gmail.com Tue Jul 28 16:52:23 2009 From: madhav.bnk at gmail.com (B.Nanda Kishore) Date: Tue, 28 Jul 2009 20:22:23 +0530 Subject: [Tutor] [BangPypers] Django test case problem In-Reply-To: <556769.22953.qm@web95309.mail.in2.yahoo.com> References: <24680724.post@talk.nabble.com> <556769.22953.qm@web95309.mail.in2.yahoo.com> Message-ID: <26030bef0907280752m6e1086bbj51135d603e56f8c@mail.gmail.com> By default django looks for a file called *tests.py*(plural) and not * test.py*. Check that and let us know. Regards, Nandakishore On Tue, Jul 28, 2009 at 6:40 PM, VIJAY KUMAR wrote: > Hi, > > I am running testcase from django when I run them from models.py it > run. > > But when I put the same in test.py in the same directory where models > is define it not even getting called. > > My structure django application is mysite > > Settings.py > > Urls.py > > Polls > > __int__.py > > models.py > > test.py > > views.py > > I used this command to run the test cases python manage.py test polls > > Can some help me know what am I missing or should need to do something so > my testcase from test.py start get executed. > > I tried to follow this link for the same > http://docs.djangoproject.com/en/dev/topics/testing/ > > > > > > > > with thanks > > Vijay > > > ------------------------------ > Love Cricket? Check out live scores, photos, video highlights and more. Click > here . > _______________________________________________ > BangPypers mailing list > BangPypers at python.org > http://mail.python.org/mailman/listinfo/bangpypers > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ataulla at gmail.com Tue Jul 28 17:15:01 2009 From: ataulla at gmail.com (Ataulla S H) Date: Tue, 28 Jul 2009 20:45:01 +0530 Subject: [Tutor] Messages not going through (testing again) In-Reply-To: <9356b9f30907280748mb711b9ex894e59769bb89a79@mail.gmail.com> References: <9356b9f30907280748mb711b9ex894e59769bb89a79@mail.gmail.com> Message-ID: welcome to Tutor :) On Tue, Jul 28, 2009 at 8:18 PM, Eduardo Vieira wrote: > Hello, this is just a test. I have posted 2 different messages and > they have never reached this list. > > Eduardo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Ataulla SH web:www.kring.com personal blog:www.ataulla.objectis.net KRING Technologies India Pvt. Ltd. 1st Floor, Tower B, Infinity Towers, DLF II, Gurgaon-122 002 -------------- next part -------------- An HTML attachment was scrubbed... URL: From shawn at skrite.net Tue Jul 28 17:45:46 2009 From: shawn at skrite.net (shawn bright) Date: Tue, 28 Jul 2009 10:45:46 -0500 Subject: [Tutor] how to know if process is running? Message-ID: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> Hey all, I have an app that runs in a GUI written in pygtk. It spawns several threads, and runs all the time. It is mission critical that we can never have two instances of this running at once. So, my question is, how can i write something that will know if there is an instance of that something already running? I am doing this in python 2.5 on Ubuntu, if that matters ( which i suspect it does ). thanks, shawn From shawn at skrite.net Tue Jul 28 18:22:02 2009 From: shawn at skrite.net (shawn bright) Date: Tue, 28 Jul 2009 11:22:02 -0500 Subject: [Tutor] how to know if process is running? In-Reply-To: <2ac5d4850907280910l979968dp8edc453c51e01245@mail.gmail.com> References: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> <2ac5d4850907280910l979968dp8edc453c51e01245@mail.gmail.com> Message-ID: <384c93600907280922y3cd7ed0fme04b2bef4fdec3f@mail.gmail.com> Thanks for the pointers Wayne, Tino, Looks easier than i had thought. sk On Tue, Jul 28, 2009 at 11:10 AM, Tino Dai wrote: > On Tue, Jul 28, 2009 at 11:45 AM, shawn bright wrote: >> >> So, my question is, how can i write something that will know if there >> is an instance of that something already running? >> > > There are a lot of ways to do this. Writing to a file on the filesystem and > having the 2nd process check for that file. Have the thread write to a log > file every x seconds and having the 2nd process check for that. Having some > sort of ipc mechanism set up (http://docs.python.org/library/ipc.html). Have > a semaphore mechanism set up. > (http://www.python.org/doc/2.5.2/lib/semaphore-objects.html) > > HTH, > Tino > > > > From amrita at iisermohali.ac.in Tue Jul 28 18:59:19 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Tue, 28 Jul 2009 22:29:19 +0530 (IST) Subject: [Tutor] how to get blank value In-Reply-To: <4A6F0880.9@gmail.com> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> <4A6F0880.9@gmail.com> Message-ID: <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> It is not giving any value, without any error ph08001 at sys53:~> python trial.py ph08001 at sys53:~> it is coming out from shell. Thanks for help. Amrita > amrita at iisermohali.ac.in wrote: >> Sorry to say, but till now I have not got the solution of my problem, I >> tried with this command:- >> >> import re >> >> > # assuming H = , N = , CA = , HA = and C = always present in that order > if __name__ == '__main__': > data = open('chem.txt').readlines() > for line in data: > line = line.split('=') > if not line[5]: # C value missing > if len(line[2])==1 and len(line[3])==1: # N and CA values missing > print "all missing", line > else: > print "C missing", line > >> >> >>> Hi, >>> >>> I have a file having lines:- >>> >>> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 >>> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = >>> 85 ALA H = 8.60 N = CA = HA = 4.65 C = >>> >>> Now i want to make two another file in which i want to put those lines >>> for >>> which C is missing and another one for which N,CA and C all are >>> missing, >>> >>> With these commands:- >>> >>> import re >>> f = open('chem.txt') >>> for line in f: >>> if re.search('C = ',line): >>> print line >>> >>> I am getting those lines for which C value is there but how to get >>> those >>> one for which it doesn't have any value, i did google search but still >>> i >>> am not getting. >>> >>> Amrita Kumari >>> Research Fellow >>> IISER Mohali >>> Chandigarh >>> INDIA >>> >>> >>> > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From cfuller084 at thinkingplanet.net Tue Jul 28 18:51:39 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 28 Jul 2009 11:51:39 -0500 Subject: [Tutor] how to know if process is running? In-Reply-To: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> References: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> Message-ID: <200907281151.39699.cfuller084@thinkingplanet.net> On Tuesday 28 July 2009 10:45, shawn bright wrote: > Hey all, > > I have an app that runs in a GUI written in pygtk. It spawns several > threads, and runs all the time. > It is mission critical that we can never have two instances of this > running at once. > > So, my question is, how can i write something that will know if there > is an instance of that something already running? > > I am doing this in python 2.5 on Ubuntu, if that matters ( which i > suspect it does ). The usual way is with file locks, but these are tricky to do in a cross platform way, and I find that when the program crashes unexpectedly, it can take awhile for the locks to get cleaned up by the operating system. What I do is open an UDP socket. The code is dead simple: from socket import socket, AF_INET, SOCK_DGRAM def check_port(addr): s = socket(AF_INET, SOCK_DGRAM) try: s.bind( addr ) except SocketError, e: if type(e.args) == tuple: if e[0] == errno.EADDRINUSE: return True raise else: s.close() return False def check_port(addr): return check_port(addr, SOCK_DGRAM) # returns False if the port is bound def socket_lock(port, check_only=False): s = socket(AF_INET, SOCK_DGRAM) addr = ('localhost', port) if not check_port(addr): if not check_only: s.bind( addr ) return s else: return True else: return False addr is the address tuple used by the socket module. First element is hostname (usually "localhost"), and the second element is the port number. Note that you need root/Administrator privileges to open a port under 1024. Cheers From quasipedia at gmail.com Tue Jul 28 19:11:12 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 28 Jul 2009 19:11:12 +0200 Subject: [Tutor] how to know if process is running? In-Reply-To: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> References: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> Message-ID: <1248801072.507.1.camel@jabbar> I am not an expert, but if I got you correctly, what you want to achieve is a "singleton": http://en.wikipedia.org/wiki/Singleton_pattern if you watch at the sample implementation, there is a Python example too. Mac. On Tue, 2009-07-28 at 10:45 -0500, shawn bright wrote: > Hey all, > > I have an app that runs in a GUI written in pygtk. It spawns several > threads, and runs all the time. > It is mission critical that we can never have two instances of this > running at once. > > So, my question is, how can i write something that will know if there > is an instance of that something already running? > > I am doing this in python 2.5 on Ubuntu, if that matters ( which i > suspect it does ). > > thanks, > shawn > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at gmail.com Tue Jul 28 19:22:19 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 28 Jul 2009 13:22:19 -0400 Subject: [Tutor] how to get blank value In-Reply-To: <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> <4A6F0880.9@gmail.com> <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> Message-ID: <4A6F33CB.4080800@gmail.com> amrita at iisermohali.ac.in wrote: > It is not giving any value, without any error > > ph08001 at sys53:~> python trial.py > ph08001 at sys53:~> > it is coming out from shell. > Try this. I embedded the test data to simplify testing: data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = 85 ALA H = 8.60 N = CA = HA = 4.65 C =""".split('\n') for line in data: line2 = line.split('=') if not line2[5]: # C value missing if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values missing print "all missing", line else: print "C missing", line -- Bob Gailer Chapel Hill NC 919-636-4239 From quasipedia at gmail.com Tue Jul 28 19:22:11 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 28 Jul 2009 19:22:11 +0200 Subject: [Tutor] Two problems related to dispathing. Message-ID: <1248801731.507.12.camel@jabbar> Hello, I'm working on an application in which I need the main loop to call the same method on a number of objects. I came up with this solution that seem to work, but I was wondering if there is a better / more pythonic solution to the problem. def invokeAll(method, data): """This function is a dispatcher: it invokes all the content types of the application calling 'contenttype.method(data)'""" return [getattr(content, method)(data) for content in contents] I am also unsatisfied by how I generate the content list I use in the above function. In fact, as I have the need to access the object both individually and with the dispatcher, I am doing something like this every time I instantiate a new object: mycontent = ContentA() contents.append(mycontent) ...but although I "feel" this is silly, I can't imagine how to get it better (i.e. a single call that will make available the object with his unique name and append it to the list of contents. Thank you in advance for your input, Mac. From shawn at skrite.net Tue Jul 28 19:32:51 2009 From: shawn at skrite.net (shawn bright) Date: Tue, 28 Jul 2009 12:32:51 -0500 Subject: [Tutor] how to know if process is running? In-Reply-To: <1248801072.507.1.camel@jabbar> References: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> <1248801072.507.1.camel@jabbar> Message-ID: <384c93600907281032y71b43dfbj24fa62eebd959c3@mail.gmail.com> Hey all, i used the popen with getpid() option. working well so far, thanks to all of you. shawn On Tue, Jul 28, 2009 at 12:11 PM, Mac Ryan wrote: > I am not an expert, but if I got you correctly, what you want to achieve > is a "singleton": http://en.wikipedia.org/wiki/Singleton_pattern if you > watch at the sample implementation, there is a Python example too. > > Mac. > > On Tue, 2009-07-28 at 10:45 -0500, shawn bright wrote: >> Hey all, >> >> I have an app that runs in a GUI written in pygtk. It spawns several >> threads, and runs all the time. >> It is mission critical that we can never have two instances of this >> running at once. >> >> So, my question is, how can i write something that will know if there >> is an instance of that something already running? >> >> I am doing this in python 2.5 on Ubuntu, if that matters ( which i >> suspect it does ). >> >> thanks, >> shawn >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Tue Jul 28 19:47:52 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Jul 2009 13:47:52 -0400 Subject: [Tutor] Two problems related to dispathing. In-Reply-To: <1248801731.507.12.camel@jabbar> References: <1248801731.507.12.camel@jabbar> Message-ID: <1c2a2c590907281047v49652d42he4201ba76c8fde76@mail.gmail.com> On Tue, Jul 28, 2009 at 1:22 PM, Mac Ryan wrote: > def invokeAll(method, data): > ? ?"""This function is a dispatcher: it invokes all the content types > ? ?of the application calling 'contenttype.method(data)'""" > ? ?return [getattr(content, method)(data) for content in contents] In Python 2.6 you can use operator.methodcaller() to do this: def invokeAll(method, data): caller = operator.methodcaller(method, data) return map(caller, contents) > mycontent = ContentA() > contents.append(mycontent) This is not so bad. You could also make a class member of the base class that keeps track of instances: class ContentA(object): contents = [] def __init__(self): contents.append(self) Kent From alan.gauld at btinternet.com Tue Jul 28 19:56:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Jul 2009 18:56:02 +0100 Subject: [Tutor] how to get blank value References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> Message-ID: wrote > Sorry to say, but till now I have not got the solution of my problem, I > tried with this command:- > > import re > > if __name__ == '__main__': > data = open('chem.txt').readlines() > for line in data: > RE = re.compile('C = (.)',re.M) The regex still does not match the end of line. The regex character for end of line is $ thus you should find something like > RE = re.compile('C =$') You might need to allow for whitespace between the = and $... If the blanks are not at the end of the line things get slightly more complicated HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jul 28 20:03:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Jul 2009 19:03:27 +0100 Subject: [Tutor] Two problems related to dispathing. References: <1248801731.507.12.camel@jabbar> Message-ID: "Mac Ryan" wrote > above function. In fact, as I have the need to access the object both > individually and with the dispatcher, I am doing something like this > every time I instantiate a new object: > > > mycontent = ContentA() > contents.append(mycontent) > > > ...but although I "feel" this is silly, I can't imagine how to get it > better (i.e. a single call that will make available the object with his > unique name and append it to the list of contents. There is no simpler solution without changing the class. If you can do that you could pass the container to the constructor and get the class to add itself to the container.... HTH, Alan G. From alan.gauld at btinternet.com Tue Jul 28 20:00:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 28 Jul 2009 19:00:25 +0100 Subject: [Tutor] how to know if process is running? References: <384c93600907280845o689d02a5k4cdba1d22c919659@mail.gmail.com> Message-ID: "shawn bright" wrote > So, my question is, how can i write something that will know if there > is an instance of that something already running? > > I am doing this in python 2.5 on Ubuntu, if that matters ( which i > suspect it does ). I suspect the simplest way is to use the ps command and grep. Wrap your code in a shell script that checks ps before launching the script. If thats not acceptable call ps from subprocess module as soon as you start, hopefuilly that won;t break anything although the processes will be running together briefly. If so you could do the check then fork() or exec() to create the real new process... Finally you can write a signal file into /tmp and then look for that file on startup. Don't forget to delete it when you exit though! Lots of options depending on how hard core you need to be! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From quasipedia at gmail.com Tue Jul 28 21:32:06 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 28 Jul 2009 21:32:06 +0200 Subject: [Tutor] Two problems related to dispathing. In-Reply-To: References: <1248801731.507.12.camel@jabbar> Message-ID: <1248809526.3693.1.camel@jabbar> On Tue, 2009-07-28 at 19:03 +0100, Alan Gauld wrote: > There is no simpler solution without changing the class. > If you can do that you could pass the container to the constructor > and get the class to add itself to the container.... Kent, Alan... thank you very much, indeed I finally adopted the solution that both of you suggested, and I am now an happy man! :) Mac. From amrita at iisermohali.ac.in Tue Jul 28 21:33:53 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Wed, 29 Jul 2009 01:03:53 +0530 (IST) Subject: [Tutor] how to get blank value In-Reply-To: <4A6F33CB.4080800@gmail.com> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> <4A6F0880.9@gmail.com> <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> <4A6F33CB.4080800@gmail.com> Message-ID: <9486.210.212.36.65.1248809633.squirrel@www.iisermohali.ac.in> with these data it is giving output but when I tried if __name__ == '__main__': data = open('chem.txt').readlines() for line in data: line2 = line.split('=') if not line2[5]: # C value missing if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values missing print "all missing", line else: print "C missing", line by putting data in .txt file then it is not giving output. Actually I have few large data file what I want that I will put those lines in one file for which only C value is missing and in another one I will put those line for which N, CA and C all values are missing. Thanks for help. Amrita > amrita at iisermohali.ac.in wrote: >> It is not giving any value, without any error >> >> ph08001 at sys53:~> python trial.py >> ph08001 at sys53:~> >> it is coming out from shell. >> > Try this. I embedded the test data to simplify testing: > > data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = > 85 ALA H = 8.60 N = CA = HA = 4.65 C =""".split('\n') > for line in data: > line2 = line.split('=') > if not line2[5]: # C value missing > if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values > missing > print "all missing", line > else: > print "C missing", line > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From shantanoo at gmail.com Tue Jul 28 22:28:21 2009 From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Wed, 29 Jul 2009 01:58:21 +0530 Subject: [Tutor] how to get blank value In-Reply-To: <9486.210.212.36.65.1248809633.squirrel@www.iisermohali.ac.in> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> <4A6F0880.9@gmail.com> <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> <4A6F33CB.4080800@gmail.com> <9486.210.212.36.65.1248809633.squirrel@www.iisermohali.ac.in> Message-ID: You may like to have a look @ pyparsing module. URL: http://pyparsing.wikispaces.com/ HTH. regards, shantanoo On 29-Jul-09, at 1:03 AM, amrita at iisermohali.ac.in wrote: > with these data it is giving output but when I tried > > if __name__ == '__main__': > data = open('chem.txt').readlines() > for line in data: > line2 = line.split('=') > if not line2[5]: # C value missing > if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values > missing > print "all missing", line > else: > print "C missing", line > > by putting data in .txt file then it is not giving output. Actually > I have > few large data file what I want that I will put those lines in one > file > for which only C value is missing and in another one I will put > those line > for which N, CA and C all values are missing. > > Thanks for help. > Amrita > >> amrita at iisermohali.ac.in wrote: >>> It is not giving any value, without any error >>> >>> ph08001 at sys53:~> python trial.py >>> ph08001 at sys53:~> >>> it is coming out from shell. >>> >> Try this. I embedded the test data to simplify testing: >> >> data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 >> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = >> 85 ALA H = 8.60 N = CA = HA = 4.65 C =""".split('\n') >> for line in data: >> line2 = line.split('=') >> if not line2[5]: # C value missing >> if len(line2[2]) <= 5 and len(line2[3]) <= 5: # N and CA values >> missing >> print "all missing", line >> else: >> print "C missing", line >> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 >> > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From davea at ieee.org Tue Jul 28 23:26:10 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 28 Jul 2009 17:26:10 -0400 Subject: [Tutor] how to get blank value In-Reply-To: <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> References: <13706.210.212.36.65.1248532908.squirrel@www.iisermohali.ac.in> <11693.210.212.36.65.1248787380.squirrel@www.iisermohali.ac.in> <4A6F0880.9@gmail.com> <23352.210.212.36.65.1248800359.squirrel@www.iisermohali.ac.in> Message-ID: <4A6F6CF2.6090001@ieee.org> amrita at iisermohali.ac.in wrote: > It is not giving any value, without any error > > ph08001 at sys53:~> python trial.py > ph08001 at sys53:~> > it is coming out from shell. > > Thanks for help. > Amrita > > >> amrita at iisermohali.ac.in wrote: >> >>> Sorry to say, but till now I have not got the solution of my problem, I >>> tried with this command:- >>> >>> import re >>> >>> >>> >> # assuming H = , N = , CA = , HA = and C = always present in that order >> if __name__ == '__main__': >> data = open('chem.txt').readlines() >> for line in data: >> line = line.split('=') >> if not line[5]: # C value missing >> if len(line[2])==1 and len(line[3])==1: # N and CA values missing >> print "all missing", line >> else: >> print "C missing", line >> >> >>> >>>> Hi, >>>> >>>> I have a file having lines:- >>>> >>>> 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 >>>> 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = >>>> 85 ALA H = 8.60 N = CA = HA = 4.65 C = >>>> >>>> Now i want to make two another file in which i want to put those lines >>>> for >>>> which C is missing and another one for which N,CA and C all are >>>> missing, >>>> >>>> With these commands:- >>>> >>>> import re >>>> f = open('chem.txt') >>>> for line in f: >>>> if re.search('C = ',line): >>>> print line >>>> >>>> I am getting those lines for which C value is there but how to get >>>> those >>>> one for which it doesn't have any value, i did google search but still >>>> i >>>> am not getting. >>>> >>>> Amrita Kumari >>>> Research Fellow >>>> IISER Mohali >>>> Chandigarh >>>> INDIA >>>> >>>> >>>> >>>> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 >> >> > > > Amrita Kumari > Research Fellow > IISER Mohali > Chandigarh > INDIA > > > If you add a strip() ,method call to Bob's line2 definition, it should work with your data, when read from file. line2 = line.strip().split('=') But you should realize his code assumes the data fits rather rigid rules. Before you use such code, you should make sure the data will fit it correctly. For example, a blank line will crash the loop. A line with the four variables in some other order will not work. A fifth variable on a line will make it not work. DaveA From pine508 at hotmail.com Wed Jul 29 02:21:17 2009 From: pine508 at hotmail.com (Che M) Date: Tue, 28 Jul 2009 20:21:17 -0400 Subject: [Tutor] self.name vs. passing a name In-Reply-To: References: Message-ID: > > The "answer" to each function is then used in the next function. > > I can think of two ways to make that answer available ... > > 1) pass it in, or > > 2) declare it as self.answer Thank you Alan, Kent, and Dave. Full agreement, and it makes sense to me. (Maybe this is also an example of "explicit is better than implicit"?) Che _________________________________________________________________ Windows Live? Hotmail?: Celebrate the moment with your favorite sports pics. Check it out. http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports -------------- next part -------------- An HTML attachment was scrubbed... URL: From burgess.nick at gmail.com Wed Jul 29 04:36:07 2009 From: burgess.nick at gmail.com (Nick Burgess) Date: Tue, 28 Jul 2009 22:36:07 -0400 Subject: [Tutor] searching for an ip and subnets in a dir of csv's Message-ID: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> Good evening List, I am trying to have this script search for an IP or nearest subnet match in a dir of csv's. It works with an absolute match, It will be receiving a whole IP address, so if there is no absolute match no data is returned, however if it is listed somewhere in a subnet I want to know. I need it to search and loop through the 32 bit, then the 24 bit, 16, 8. I am stumped at how to cut of the numbers on the right with the period as the delimiter. I have looked at strip, split need a clue what else to try. Thanks! args.append(arg.strip("\n")) args = list(set(args)) for arg in args: for f in files: pattern = re.compile(sys.argv[1]) <---- I am thinking loop 4 times and do something different here ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') for row in ff: if any(pattern.search(cell) for cell in row): print f print ', '.join(row) From pedrooconnell at gmail.com Wed Jul 29 04:44:36 2009 From: pedrooconnell at gmail.com (pedro) Date: Tue, 28 Jul 2009 22:44:36 -0400 Subject: [Tutor] "File exists, overwrite?" dialog help Message-ID: Hi I am learning python for use in Nuke (image compositing software). I would like to test if a file exists and receive a warning if it does. To do a Nuke command line render, it looks something like this: /Applications/Nuke5.1v5/Nuke5.1v5.app/Contents/MacOS/Nuke5.1v5 -iX WriteComp '/Volumes/sgtb/comp_v05.nk' Where "WriteComp" is the name of a write node within the nuke script '/Volumes/sgtb/comp_v05.nk'. The problem with the above command line command is that it overwrites the files that "WriteComp" points to without warning me. So what I would like to do is have the command line (or python) ask "File exists, overwrite?" Below I have some code which tests whether the file already exists by parsing the Nuke script. It is working fine. I am not sure how to combine the script below with the command line command above so that the above command won't be executed unless I am first asked "File exists, overwrite?" #################start import re, linecache, shutil, sys, os theFile = (sys.argv[1]) lines = theFile.readlines() theFile.close() pattern = re.compile(' name WriteComp') for i, line in enumerate(lines): if pattern.search(line): theWriteFilePath = linecache.getline(theFile.name, i-1) #nukeFilePathAsString = nukeFilePathContainerAsString = '/'.join((theWriteFilePath.split()[1]).split('/')[:-1]) nukeImageAsString = '/'.join((theWriteFilePath.split()[1]).split('/')[-1:]) nukeImageWithZeroesAsString = nukeImageAsString.split('.')[0] + '.0001.' + nukeImageAsString.split('.')[2] thePythonFriendlyFilePath = nukeFilePathContainerAsString + '/'+ nukeImageWithZeroesAsString #print thePythonFriendlyFilePath if os.path.exists(thePythonFriendlyFilePath): print 'yes' #########################end Thanks Pete From peterjohnanderson at gmail.com Wed Jul 29 05:30:26 2009 From: peterjohnanderson at gmail.com (pja) Date: Wed, 29 Jul 2009 13:30:26 +1000 Subject: [Tutor] Problem with multiple input Message-ID: <4A6FC252.8020405@gmail.com> Hi! I am trying to teach myself Python (using John Zelle's book "Python Programming"). One major problem is that the book is written for Python 2.x and I am using Python 3.1 (and don't want to switch back). There is a sample script for calculating the sum and difference of two numbers: # sum_and_difference.py def sumDiff(x,y): total = x + y diff = x - y return total, diff def main(): # Introduction print("This program calculates the sum and difference of two numbers.") # number1 = float(input("Enter the first number: ")) # number2 = float(input("Enter the second number: ")) number1, number2 = (input("Please enter two numbers: ").split()) number1, number2 = float(number1), float(number2) total, diff = sumDiff(number1, number2) diff = abs(diff) print("The sum is", total, "and the difference is", diff) main() I have commented out the two lines where user input is collected (that works fine) and tried to replace the two lines with a single input line. The example code works but I don't think it is either optimum or elegant. Could someone help me with the "correct" Python way of doing this. Also the working code only woks with input numbers that are separated by a space. How would I do this with numbers that are separated by a comma? Thanks in advance. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From alan.gauld at btinternet.com Wed Jul 29 05:51:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Jul 2009 04:51:00 +0100 Subject: [Tutor] Problem with multiple input References: <4A6FC252.8020405@gmail.com> Message-ID: "pja" wrote > One major problem is that the book is written for Python 2.x and I am > using Python 3.1 (and don't want to switch back). Very few books/tutorials exist yet for v3. But you seem to be coping with the differences adequately. My tutorial for v3 is almost half-way complete, you might find it useful as a secondary resource: http://www.alan-g.me.uk/l2p/ def main(): # Introduction print("This program calculates the sum and difference of two numbers.") # number1 = float(input("Enter the first number: ")) # number2 = float(input("Enter the second number: ")) number1, number2 = (input("Please enter two numbers: ").split()) number1, number2 = float(number1), float(number2) > The example code works but I don't think it is either optimum or > elegant. Could someone help me with the "correct" Python way of doing That loooks OK although its a little bit unusual to request two input values on one line - just because of the difficulty of parsing the result. Its hard enough to get users to input correct values one at a time! Never mind formatting two values... as you discovered: > Also the working code only woks with input numbers that are separated by > a space. How would I do this with numbers that are separated by a comma? However you can pass a string to split() that will split the line on any of the characters in the string. So in your case you could request a split using spaces and commas - and I suggest adding semi colons and tabs too? number1, number2 = (input("Please enter two numbers: ").split(" ,;\t")) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ptmcg at austin.rr.com Wed Jul 29 06:36:49 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 28 Jul 2009 23:36:49 -0500 Subject: [Tutor] how to get blank value In-Reply-To: References: Message-ID: <99D25C8FCB81490FAF2463D73CC3D54F@AWA2> Ok, I've seen various passes at this problem using regex, split('='), etc., but the solutions seem fairly fragile, and the OP doesn't seem happy with any of them. Here is how this problem looks if you were going to try breaking it up with pyparsing: - Each line starts with an integer, and the string "ALA" - "ALA" is followed by a series of "X = 1.2"-type attributes, where the value part might be missing. And to implement (with a few bells and whistles thrown in for free): data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = 85 ALA H = 8.60 N = CA = HA = 4.65 C =""".splitlines() from pyparsing import * # define some basic data expressions integer = Word(nums) real = Combine(Word(nums) + "." + Word(nums)) # use parse actions to automatically convert numeric # strings to actual numbers at parse time integer.setParseAction(lambda tokens:int(tokens[0])) real.setParseAction(lambda tokens:float(tokens[0])) # define expressions for 'X = 1.2' assignments; note that the # value might be missing, so use Optional - we'll fill in # a default value of 0.0 if no value is given keyValue = Word(alphas.upper()) + '=' + \ Optional(real|integer, default=0.0) # define overall expression for the data on a line dataline = integer + "ALA" + OneOrMore(Group(keyValue))("kvdata") # attach parse action to define named values in the returned tokens def assignDataByKey(tokens): for k,_,v in tokens.kvdata: tokens[k] = v dataline.setParseAction(assignDataByKey) # for each line in the input data, parse it and print some of the data fields for d in data: print d parsedData = dataline.parseString(d) print parsedData.dump() print parsedData.CA print parsedData.N print Prints out: 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 [48, 'ALA', ['H', '=', 8.3300000000000001], ['N', '=', 120.77], ['CA', '=', 55.18], ['HA', '=', 4.1200000000000001], ['C', '=', 181.5]] - C: 181.5 - CA: 55.18 - H: 8.33 - HA: 4.12 - N: 120.77 - kvdata: [['H', '=', 8.3300000000000001], ['N', '=', 120.77], ['CA', '=', 55.18], ['HA', '=', 4.1200000000000001], ['C', '=', 181.5]] 55.18 120.77 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = [104, 'ALA', ['H', '=', 7.7000000000000002], ['N', '=', 121.20999999999999], ['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]] - C: 0.0 - CA: 54.32 - H: 7.7 - HA: 4.21 - N: 121.21 - kvdata: [['H', '=', 7.7000000000000002], ['N', '=', 121.20999999999999], ['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]] 54.32 121.21 85 ALA H = 8.60 N = CA = HA = 4.65 C = [85, 'ALA', ['H', '=', 8.5999999999999996], ['N', '=', 0.0], ['CA', '=', 0.0], ['HA', '=', 4.6500000000000004], ['C', '=', 0.0]] - C: 0.0 - CA: 0.0 - H: 8.6 - HA: 4.65 - N: 0.0 - kvdata: [['H', '=', 8.5999999999999996], ['N', '=', 0.0], ['CA', '=', 0.0], ['HA', '=', 4.6500000000000004], ['C', '=', 0.0]] 0.0 0.0 Learn more about pyparsing at http://pyparsing.wikispaces.com. -- Paul From amrita at iisermohali.ac.in Wed Jul 29 07:13:09 2009 From: amrita at iisermohali.ac.in (amrita at iisermohali.ac.in) Date: Wed, 29 Jul 2009 10:43:09 +0530 (IST) Subject: [Tutor] how to get blank value In-Reply-To: <99D25C8FCB81490FAF2463D73CC3D54F@AWA2> References: <99D25C8FCB81490FAF2463D73CC3D54F@AWA2> Message-ID: <4956.210.212.36.65.1248844389.squirrel@www.iisermohali.ac.in> Thanks for help Sir but with these commands it is showing error:- ph08001 at sys53:~> python trip.py Traceback (most recent call last): File "trip.py", line 6, in from pyparsing import * ImportError: No module named pyparsing > Ok, I've seen various passes at this problem using regex, split('='), > etc., > but the solutions seem fairly fragile, and the OP doesn't seem happy with > any of them. Here is how this problem looks if you were going to try > breaking it up with pyparsing: > - Each line starts with an integer, and the string "ALA" > - "ALA" is followed by a series of "X = 1.2"-type attributes, where the > value part might be missing. > > And to implement (with a few bells and whistles thrown in for free): > > data = """48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = > 85 ALA H = 8.60 N = CA = HA = 4.65 C =""".splitlines() > > > from pyparsing import * > > # define some basic data expressions > integer = Word(nums) > real = Combine(Word(nums) + "." + Word(nums)) > > # use parse actions to automatically convert numeric > # strings to actual numbers at parse time > integer.setParseAction(lambda tokens:int(tokens[0])) > real.setParseAction(lambda tokens:float(tokens[0])) > > # define expressions for 'X = 1.2' assignments; note that the > # value might be missing, so use Optional - we'll fill in > # a default value of 0.0 if no value is given > keyValue = Word(alphas.upper()) + '=' + \ > Optional(real|integer, default=0.0) > > # define overall expression for the data on a line > dataline = integer + "ALA" + OneOrMore(Group(keyValue))("kvdata") > > # attach parse action to define named values in the returned tokens > def assignDataByKey(tokens): > for k,_,v in tokens.kvdata: > tokens[k] = v > dataline.setParseAction(assignDataByKey) > > # for each line in the input data, parse it and print some of the data > fields > for d in data: > print d > parsedData = dataline.parseString(d) > print parsedData.dump() > print parsedData.CA > print parsedData.N > print > > > Prints out: > > 48 ALA H = 8.33 N = 120.77 CA = 55.18 HA = 4.12 C = 181.50 > [48, 'ALA', ['H', '=', 8.3300000000000001], ['N', '=', 120.77], ['CA', > '=', > 55.18], ['HA', '=', 4.1200000000000001], ['C', '=', 181.5]] > - C: 181.5 > - CA: 55.18 > - H: 8.33 > - HA: 4.12 > - N: 120.77 > - kvdata: [['H', '=', 8.3300000000000001], ['N', '=', 120.77], ['CA', '=', > 55.18], ['HA', '=', 4.1200000000000001], ['C', '=', 181.5]] > 55.18 > 120.77 > > 104 ALA H = 7.70 N = 121.21 CA = 54.32 HA = 4.21 C = > [104, 'ALA', ['H', '=', 7.7000000000000002], ['N', '=', > 121.20999999999999], > ['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]] > - C: 0.0 > - CA: 54.32 > - H: 7.7 > - HA: 4.21 > - N: 121.21 > - kvdata: [['H', '=', 7.7000000000000002], ['N', '=', 121.20999999999999], > ['CA', '=', 54.32], ['HA', '=', 4.21], ['C', '=', 0.0]] > 54.32 > 121.21 > > 85 ALA H = 8.60 N = CA = HA = 4.65 C = > [85, 'ALA', ['H', '=', 8.5999999999999996], ['N', '=', 0.0], ['CA', '=', > 0.0], ['HA', '=', 4.6500000000000004], ['C', '=', 0.0]] > - C: 0.0 > - CA: 0.0 > - H: 8.6 > - HA: 4.65 > - N: 0.0 > - kvdata: [['H', '=', 8.5999999999999996], ['N', '=', 0.0], ['CA', '=', > 0.0], ['HA', '=', 4.6500000000000004], ['C', '=', 0.0]] > 0.0 > 0.0 > > > Learn more about pyparsing at http://pyparsing.wikispaces.com. > > -- Paul > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Amrita Kumari Research Fellow IISER Mohali Chandigarh INDIA From ptmcg at austin.rr.com Wed Jul 29 07:44:43 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 29 Jul 2009 00:44:43 -0500 Subject: [Tutor] how to get blank value In-Reply-To: <4956.210.212.36.65.1248844389.squirrel@www.iisermohali.ac.in> References: <99D25C8FCB81490FAF2463D73CC3D54F@AWA2> <4956.210.212.36.65.1248844389.squirrel@www.iisermohali.ac.in> Message-ID: <6433EFD2D2B4414DAD52DDA3E98E0116@AWA2> > -----Original Message----- > From: amrita at iisermohali.ac.in [mailto:amrita at iisermohali.ac.in] > Sent: Wednesday, July 29, 2009 12:13 AM > To: Paul McGuire > Cc: tutor at python.org > Subject: Re: [Tutor] how to get blank value > > Thanks for help Sir but with these commands it is showing error:- > > ph08001 at sys53:~> python trip.py > Traceback (most recent call last): > File "trip.py", line 6, in > from pyparsing import * > ImportError: No module named pyparsing > Wow. You are on your own from here, you will have to do *some* work for yourself. This problem should definitely be within the abilities of a "Research Fellow" to solve. Did you even see the link I added at the bottom of my earlier post? From ldl08 at gmx.net Wed Jul 29 08:29:43 2009 From: ldl08 at gmx.net (David) Date: Wed, 29 Jul 2009 14:29:43 +0800 Subject: [Tutor] concerning help() function Message-ID: <4A6FEC57.10103@gmx.net> Dear Tutors, whenever I make use of the help() function, I have a good chance of getting an error. I have not yet understood this tool very well. Take the modules operator and random as examples. The former is built-in, the latter not. Do I wish to see the help files, I have to use a different syntax: help(random) help('operator') I figured this by trial and error, and I am keen to find out when the help() function is to be supplied with a string, and when no '' is required. It certainly does not seem intuitive to me! Many thanks, David From peter.anderson at internode.on.net Wed Jul 29 08:16:51 2009 From: peter.anderson at internode.on.net (Peter Anderson) Date: Wed, 29 Jul 2009 16:16:51 +1000 Subject: [Tutor] Problem with multiple input In-Reply-To: References: Message-ID: <4A6FE953.5010403@internode.on.net> Alan, Thanks heaps for the quick feedback. I think you are right about multiple inputs on the one line. Looks elegant but is hard work. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From bala.biophysics at gmail.com Wed Jul 29 13:51:12 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Wed, 29 Jul 2009 13:51:12 +0200 Subject: [Tutor] curve fitting Message-ID: <288df32a0907290451t3ace762dgd902cc928b23dd35@mail.gmail.com> Friends, I wish to do some curve fitting with python by defining my own equations. Could someone please give some guidance or examples on doing the same. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Jul 29 14:13:19 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 29 Jul 2009 07:13:19 -0500 Subject: [Tutor] searching for an ip and subnets in a dir of csv's In-Reply-To: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> References: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> Message-ID: <333efb450907290513m1a7c7415m5fbbc24c15d68625@mail.gmail.com> On Tue, Jul 28, 2009 at 9:36 PM, Nick Burgess wrote: > Good evening List, > > I am trying to have this script search for an IP or nearest subnet > match in a dir of csv's. It works with an absolute match, It will be > receiving a whole IP address, so if there is no absolute match no data > is returned, however if it is listed somewhere in a subnet I want to > know. I need it to search and loop through the 32 bit, then the 24 > bit, 16, 8. I am stumped at how to cut of the numbers on the right > with the period as the delimiter. I have looked at strip, split need a > clue what else to try. > > Thanks! > > > > args.append(arg.strip("\n")) > args = list(set(args)) > for arg in args: > for f in files: > pattern = re.compile(sys.argv[1]) <---- I > am thinking loop 4 times and do something different here > ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') > for row in ff: > if any(pattern.search(cell) for cell in row): > print f > print ', '.join(row) It's often helpful to provide example data and solutions so we know exactly what you're looking for. If we understand quickly, chances are we'll reply just as quickly. If you have the IPs 192.168.1.1 192.168.1.10 192.168.2.2 192.169.1.1 And you were looking for 192.168.1.2, do you want it to return nothing? Or both 192.168.1.1 and 192.168.1.10? Or only 192.168.1.1 as it's the closest match? Also, I don't know if I'd do re.compile on the raw sys.argv data, but perhaps filter it - just compiling is error prone and possibly a security hole. Even if you're doing it just for yourself, I'd still try to make it as break-proof as possible. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Wed Jul 29 14:39:32 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 29 Jul 2009 07:39:32 -0500 Subject: [Tutor] concerning help() function In-Reply-To: <4A6FEC57.10103@gmx.net> References: <4A6FEC57.10103@gmx.net> Message-ID: <333efb450907290539p25e1f0d4u7c2cc51685ce6e14@mail.gmail.com> On Wed, Jul 29, 2009 at 1:29 AM, David wrote: > Dear Tutors, > > whenever I make use of the help() function, I have a good chance of > getting an error. I have not yet understood this tool very well. > > Take the modules operator and random as examples. The former is > built-in, the latter not. > Do I wish to see the help files, I have to use a different syntax: > > help(random) > help('operator') > > I figured this by trial and error, and I am keen to find out when the > help() function is to be supplied with a string, and when no '' is > required. It certainly does not seem intuitive to me! >>> operator Traceback (most recent call last): File "", line 1, in NameError: name 'operator' is not defined >>> help('operator') >>> random Traceback (most recent call last): File "", line 1, in NameError: name 'random' is not defined >>> help(random) Traceback (most recent call last): File "", line 1, in NameError: name 'random' is not defined >>> help('random') (produces the helpfile) This goes back to pythons objects. If something is an object in python, you can probably pass it to help(), otherwise you need to pass a string. >>> operator = 'foo' >>> help(operator) Welcome to ASCII Assassin! (1) Start Game (2) Instructions :> I guess that's an easter egg... so I'm off to play ASCII Assassin! HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From burgess.nick at gmail.com Wed Jul 29 14:43:12 2009 From: burgess.nick at gmail.com (Nick Burgess) Date: Wed, 29 Jul 2009 08:43:12 -0400 Subject: [Tutor] searching for an ip and subnets in a dir of csv's In-Reply-To: <333efb450907290513m1a7c7415m5fbbc24c15d68625@mail.gmail.com> References: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> <333efb450907290513m1a7c7415m5fbbc24c15d68625@mail.gmail.com> Message-ID: <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> And you were looking for 192.168.1.2, do you want it to return nothing? Or both 192.168.1.1 and 192.168.1.10? Or only 192.168.1.1 as it's the closest match? I would like it to return both, all possible matches. The data looks something like this in the CSV's, Server foo.bar.org 10.2.2.2 such&such org Apache farm subnet 10.2.3.0/24 so&so corp. the format is random The script will be ran from a third party tool so only one argument can be passed to it which will be an entire IP address. If within the CSV's there is no 32 bit match there could be a subnet that might match, thats why I need it to loop over the dots. If there is a 32 bit and a subnet match both will be returned which is desirable . I figured out a way to cut of the ends from the dots using the following code, string.rsplit('.',1)[:1]; looping over this and incrementing the first digit cuts of the octets from the IP correctly. My problem now is that the rsplit returns a list and I need a string. I am stuck on how to use the rsplit. Thanks. ipAdres = re.compile(sys.argv[1]) print ipAdres.pattern print ipAdres.pattern.rsplit('.',1)[:1] for arg in args: for f in files: ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') for row in ff: if any(ipAdres.search(cell) for cell in row): print f print ', '.join(row) On Wed, Jul 29, 2009 at 8:13 AM, Wayne wrote: > On Tue, Jul 28, 2009 at 9:36 PM, Nick Burgess > wrote: >> >> Good evening List, >> >> I am trying to have this script search for an IP or nearest subnet >> match in a dir of csv's. It works with an absolute match, ?It will be >> receiving a whole IP address, so if there is no absolute match no data >> is returned, however if it is listed somewhere in a subnet I want to >> know. ? I need it to search and loop through the 32 bit, then the 24 >> bit, 16, 8. ?I am stumped at how to cut of the numbers on the right >> with the period as the delimiter. I have looked at strip, split need a >> clue what else to try. >> >> Thanks! >> >> >> >> ? ? ? ?args.append(arg.strip("\n")) >> args = list(set(args)) >> for arg in args: >> ? ?for f in files: >> ? ? ? ?pattern = re.compile(sys.argv[1]) ? ? ? ? ? ? ? ? ? <---- ? I >> am thinking loop 4 times and do something different here >> ? ? ? ?ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') >> ? ? ? ?for row in ff: >> ? ? ? ? ? ?if any(pattern.search(cell) for cell in row): >> ? ? ? ? ? ? ? ?print f >> ? ? ? ? ? ? ? ?print ', '.join(row) > > It's often helpful to provide example data and solutions so we know exactly > what you're looking for. If we understand quickly, chances are we'll reply > just as quickly. > > If you have the IPs > > 192.168.1.1 > 192.168.1.10 > 192.168.2.2 > 192.169.1.1 > > And you were looking for 192.168.1.2, do you want it to return nothing? Or > both 192.168.1.1 and 192.168.1.10? Or only 192.168.1.1 as it's the closest > match? > > Also, I don't know if I'd do re.compile on the raw sys.argv data, but > perhaps filter it - just compiling is error prone and possibly a security > hole. Even if you're doing it just for yourself, I'd still try to make it as > break-proof as possible. > > HTH, > Wayne > > From srilyk at gmail.com Wed Jul 29 15:05:58 2009 From: srilyk at gmail.com (Wayne) Date: Wed, 29 Jul 2009 08:05:58 -0500 Subject: [Tutor] searching for an ip and subnets in a dir of csv's In-Reply-To: <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> References: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> <333efb450907290513m1a7c7415m5fbbc24c15d68625@mail.gmail.com> <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> Message-ID: <333efb450907290605l7190b374yab2b3539116338df@mail.gmail.com> On Wed, Jul 29, 2009 at 7:43 AM, Nick Burgess wrote: > And you were looking for 192.168.1.2, do you want it to return nothing? Or > both 192.168.1.1 and 192.168.1.10? Or only 192.168.1.1 as it's the closest > match? > > I would like it to return both, all possible matches. > > The data looks something like this in the CSV's, > > Server foo.bar.org 10.2.2.2 such&such org > Apache farm subnet 10.2.3.0/24 so&so corp. > > the format is random > > The script will be ran from a third party tool so only one argument > can be passed to it which will be an entire IP address. If within the > CSV's there is no 32 bit match there could be a subnet that might > match, thats why I need it to loop over the dots. If there is a 32 > bit and a subnet match both will be returned which is desirable . http://www.velocityreviews.com/forums/t356058-regular-expressions-and-matches.html That will give you the regex for matching any IP addresses. If you use the findall method http://docs.python.org/library/re.html then it will give you a list of IPs (as strings). If you packed each of these IPs into a dictionary you could use this to get the key: for ip in iplist: key = ip[:ip.rfind('.')] # Gets everything but the last bit if mydict.get(key): mydict[key].append(ip) else: mydict[key] = [ip] Then you just have to do something like mydict.get(sys.argv[1][:sys.argv[1].rfind('.')] Which will return None or the list of IPs. Although now that I'm thinking a little more about it, that's probably excessive for your needs - you can just do this: matches = [] ipnet = sys.argv[1][:sys.argv[1].rfind('.')] for ip in iplist: if ip.startswith(ipnet): matches.append(ip) and that should give you a list of all IPs within that same subnet. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Wed Jul 29 15:42:31 2009 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 29 Jul 2009 15:42:31 +0200 Subject: [Tutor] curve fitting In-Reply-To: <288df32a0907290451t3ace762dgd902cc928b23dd35@mail.gmail.com> References: <288df32a0907290451t3ace762dgd902cc928b23dd35@mail.gmail.com> Message-ID: <200907291542.32380.eike.welk@gmx.net> On Wednesday 29 July 2009, Bala subramanian wrote: > Friends, > > I wish to do some curve fitting with python by defining my own > equations. Could someone please give some guidance or examples on > doing the same. You can use the Numpy/Scipy libraries for that. I think they have examples for curve fitting on their website. But unfortunately the website is down (or my Internet is broken). http://www.scipy.org/ There are also special mailing lists for Numpy/Scipy/Matplotlib users, to which you should subscribe. This one would be good for your question: http://projects.scipy.org/mailman/listinfo/scipy-user If I understand you right, you have a formula with some parameters. Now you are searching for parameter values so that the formula really goes through the data points. This is a task for optimization functions. Kind regards, Eike. From jsseabold at gmail.com Wed Jul 29 15:59:55 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Wed, 29 Jul 2009 09:59:55 -0400 Subject: [Tutor] curve fitting In-Reply-To: <200907291542.32380.eike.welk@gmx.net> References: <288df32a0907290451t3ace762dgd902cc928b23dd35@mail.gmail.com> <200907291542.32380.eike.welk@gmx.net> Message-ID: On Wed, Jul 29, 2009 at 9:42 AM, Eike Welk wrote: > On Wednesday 29 July 2009, Bala subramanian wrote: >> Friends, >> >> I wish to do some curve fitting with python by defining my own >> equations. Could someone please give some guidance or examples on >> doing the same. > What kind of curve fitting exactly? Linear equations? Can you provide an example? > You can use the Numpy/Scipy libraries for that. I think they have > examples for curve fitting on their website. But unfortunately the > website is down (or my Internet is broken). > > http://www.scipy.org/ > There were some problems with the site yesterday as well. Scipy would be a good place to start. I am in the home stretch of completing a google summer of code project to integrate some mostly linear statistical models (different flavors of least squares fitting, generalized linear models, robust statistics, generalized additive models, etc.) into SciPy, which might also be of interest to you depending on your needs (some info here ). There are also some "cookbook" examples from the scipy page that show some recipes for doing some basic curve fitting (OLS, interpolation) with the available tools. > There are also special mailing lists for Numpy/Scipy/Matplotlib users, > to which you should subscribe. This one would be good for your > question: > http://projects.scipy.org/mailman/listinfo/scipy-user > > > If I understand you right, you have a formula with some parameters. > Now you are searching for parameter values so that the formula really > goes through the data points. This is a task for optimization > functions. > > Kind regards, > Eike. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From martin at linux-ip.net Wed Jul 29 16:04:28 2009 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 29 Jul 2009 09:04:28 -0500 Subject: [Tutor] searching for an ip and subnets in a dir of csv's In-Reply-To: <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> References: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> <333efb450907290513m1a7c7415m5fbbc24c15d68625@mail.gmail.com> <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, : The script will be ran from a third party tool so only one : argument can be passed to it which will be an entire IP address. : If within the CSV's there is no 32 bit match there could be a : subnet that might match, thats why I need it to loop over the : dots. If there is a 32 bit and a subnet match both will be : returned which is desirable . : : I figured out a way to cut of the ends from the dots using the : following code, : : string.rsplit('.',1)[:1]; You, very likely, know something about your data that I do not, however, I couldn't help but notice that your choice of octet boundaries is not really quite sufficient when trying to find the network in which a given host would live. The /24, /16 and /8 boundaries are used in classful routing (class C, class B and class A respectively), which has largely been supplanted by CIDR. Classless InterDomain Routing (CIDR) allows for netmasks which do not fall on the octet boundaries. Consider the IP 66.102.1.104. Here are some of the network addresses (prefixes) that could contain that host: 66.102.1.104/32 66.102.1.104/31 66.102.1.104/30 66.102.1.104/29 66.102.1.96/28 66.102.1.96/27 66.102.1.64/26 66.102.1.0/25 66.102.1.0/24 66.102.0.0/23 66.102.0.0/22 If you found any of these in your input data, that would indicate that the host 66.102.1.104 would be inside that network. With that said, here's a little function (my bad reimplementation of something probably in an IP handling library like ipaddr [0]) that will return a list of prefixes in string form which you can search for in your input text. Remember when searching for IPs in their string form that you should anchor (at absolute least) at the beginning of the string. In short, without the anchoring, you'll get three results, where only one should actually match. (Imagine looking for '4.17.112.0/24' without an anchor at the front. You'd also match '24.17.112.0/24' and '174.17.112.0/24'.) : looping over this and incrementing the first digit cuts of the : octets from the IP correctly. My problem now is that the rsplit : returns a list and I need a string. I am stuck on how to use the : rsplit. Thanks. : : : ipAdres = re.compile(sys.argv[1]) : print ipAdres.pattern : print ipAdres.pattern.rsplit('.',1)[:1] : for arg in args: : for f in files: : ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') : for row in ff: : if any(ipAdres.search(cell) for cell in row): : print f : print ', '.join(row) Good luck in your text searching! - -Martin [0] An IP address handling library that is much richer than the hastily-written snippet below: http://code.google.com/p/ipaddr-py/ #! /usr/bin/env python # # import sys import struct import socket maxmasklen = 32 def list_networks( ip, minmasklen=8, defaultmasklen=32 ): if ip is None: raise ValueError, "Supply an IP to this function" mask = defaultmasklen ip = struct.unpack('>L',socket.inet_aton( ip )) networks = list() while mask >= minmasklen: bits = maxmasklen - mask ip = ( ( ( ip[0] >> bits ) << bits ), ) net = socket.inet_ntoa( struct.pack( '>L', ip[0] ) ) + '/' + str( mask ) networks.append( net ) mask -= 1 return networks if __name__ == '__main__': for ip in sys.argv[1:]: networks = list_networks( ip ); for network in networks: print network print # -- end of file - -- Martin A. Brown http://linux-ip.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: pgf-0.72 (http://linux-ip.net/sw/pine-gpg-filter/) iD8DBQFKcFbwHEoZD1iZ+YcRApGhAJ9fJxjEigCeCZ7cpDSa9uCoAadl+QCfYkhI 7fR7P0mZRsBl4lbleqkDoqw= =ns0F -----END PGP SIGNATURE----- From martin at linux-ip.net Wed Jul 29 16:04:28 2009 From: martin at linux-ip.net (Martin A. Brown) Date: Wed, 29 Jul 2009 09:04:28 -0500 Subject: [Tutor] searching for an ip and subnets in a dir of csv's In-Reply-To: <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> References: <3a13c8e50907281936g747c5f68t982c0fa0f9a8e55e@mail.gmail.com> <333efb450907290513m1a7c7415m5fbbc24c15d68625@mail.gmail.com> <3a13c8e50907290543q11839438sb0d513a8154dbd16@mail.gmail.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, : The script will be ran from a third party tool so only one : argument can be passed to it which will be an entire IP address. : If within the CSV's there is no 32 bit match there could be a : subnet that might match, thats why I need it to loop over the : dots. If there is a 32 bit and a subnet match both will be : returned which is desirable . : : I figured out a way to cut of the ends from the dots using the : following code, : : string.rsplit('.',1)[:1]; You, very likely, know something about your data that I do not, however, I couldn't help but notice that your choice of octet boundaries is not really quite sufficient when trying to find the network in which a given host would live. The /24, /16 and /8 boundaries are used in classful routing (class C, class B and class A respectively), which has largely been supplanted by CIDR. Classless InterDomain Routing (CIDR) allows for netmasks which do not fall on the octet boundaries. Consider the IP 66.102.1.104. Here are some of the network addresses (prefixes) that could contain that host: 66.102.1.104/32 66.102.1.104/31 66.102.1.104/30 66.102.1.104/29 66.102.1.96/28 66.102.1.96/27 66.102.1.64/26 66.102.1.0/25 66.102.1.0/24 66.102.0.0/23 66.102.0.0/22 If you found any of these in your input data, that would indicate that the host 66.102.1.104 would be inside that network. With that said, here's a little function (my bad reimplementation of something probably in an IP handling library like ipaddr [0]) that will return a list of prefixes in string form which you can search for in your input text. Remember when searching for IPs in their string form that you should anchor (at absolute least) at the beginning of the string. In short, without the anchoring, you'll get three results, where only one should actually match. (Imagine looking for '4.17.112.0/24' without an anchor at the front. You'd also match '24.17.112.0/24' and '174.17.112.0/24'.) : looping over this and incrementing the first digit cuts of the : octets from the IP correctly. My problem now is that the rsplit : returns a list and I need a string. I am stuck on how to use the : rsplit. Thanks. : : : ipAdres = re.compile(sys.argv[1]) : print ipAdres.pattern : print ipAdres.pattern.rsplit('.',1)[:1] : for arg in args: : for f in files: : ff = csv.reader(open (f, 'rb'), delimiter=' ', quotechar='|') : for row in ff: : if any(ipAdres.search(cell) for cell in row): : print f : print ', '.join(row) Good luck in your text searching! - -Martin [0] An IP address handling library that is much richer than the hastily-written snippet below: http://code.google.com/p/ipaddr-py/ #! /usr/bin/env python # # import sys import struct import socket maxmasklen = 32 def list_networks( ip, minmasklen=8, defaultmasklen=32 ): if ip is None: raise ValueError, "Supply an IP to this function" mask = defaultmasklen ip = struct.unpack('>L',socket.inet_aton( ip )) networks = list() while mask >= minmasklen: bits = maxmasklen - mask ip = ( ( ( ip[0] >> bits ) << bits ), ) net = socket.inet_ntoa( struct.pack( '>L', ip[0] ) ) + '/' + str( mask ) networks.append( net ) mask -= 1 return networks if __name__ == '__main__': for ip in sys.argv[1:]: networks = list_networks( ip ); for network in networks: print network print # -- end of file - -- Martin A. Brown http://linux-ip.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: pgf-0.72 (http://linux-ip.net/sw/pine-gpg-filter/) iD8DBQFKcFbwHEoZD1iZ+YcRApGhAJ9fJxjEigCeCZ7cpDSa9uCoAadl+QCfYkhI 7fR7P0mZRsBl4lbleqkDoqw= =ns0F -----END PGP SIGNATURE----- From davea at ieee.org Wed Jul 29 17:22:55 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 29 Jul 2009 11:22:55 -0400 Subject: [Tutor] concerning help() function In-Reply-To: <4A6FEC57.10103@gmx.net> References: <4A6FEC57.10103@gmx.net> Message-ID: <4A70694F.1000007@ieee.org> David wrote: > Dear Tutors, > > whenever I make use of the help() function, I have a good chance of > getting an error. I have not yet understood this tool very well. > > Take the modules operator and random as examples. The former is > built-in, the latter not. > Do I wish to see the help files, I have to use a different syntax: > > help(random) > help('operator') > > I figured this by trial and error, and I am keen to find out when the > help() function is to be supplied with a string, and when no '' is > required. It certainly does not seem intuitive to me! > > Many thanks, > > David > > > As far as I know, the only difference between the two forms is that with the quotes, you can get help on a module that has *not* been imported, while if a module had been imported, you can leave off the quotes. For those two modules, you need the quotes till you import them. I don't see any difference between them, at least in :Python 2.6.2 For things that are really built-in, such as the function open(), you can get help without importing anything, since it's already visible. So you can say help(open), or help(property). DaveA From cosmicsand27 at yahoo.com Wed Jul 29 17:59:02 2009 From: cosmicsand27 at yahoo.com (Raj Medhekar) Date: Wed, 29 Jul 2009 08:59:02 -0700 (PDT) Subject: [Tutor] Web crawling! Message-ID: <97233.1648.qm@web43406.mail.sp1.yahoo.com> Does anyone know a good webcrawler that could be used in tandem with the Beautiful soup parser to parse out specific elements from news sites like BBC and CNN? Thanks! -Raj -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Wed Jul 29 18:14:21 2009 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 29 Jul 2009 18:14:21 +0200 Subject: [Tutor] curve fitting In-Reply-To: <200907291542.32380.eike.welk@gmx.net> References: <288df32a0907290451t3ace762dgd902cc928b23dd35@mail.gmail.com> <200907291542.32380.eike.welk@gmx.net> Message-ID: <200907291814.22141.eike.welk@gmx.net> On Wednesday 29 July 2009, Eike Welk wrote: > You can use the Numpy/Scipy libraries for that. I think they have > examples for curve fitting on their website. This page contains examples: http://www.scipy.org/Cookbook/FittingData - Eike. From jsseabold at gmail.com Wed Jul 29 18:26:45 2009 From: jsseabold at gmail.com (Skipper Seabold) Date: Wed, 29 Jul 2009 12:26:45 -0400 Subject: [Tutor] curve fitting In-Reply-To: <288df32a0907290727i8b3f521sa4c0f689720e2f8d@mail.gmail.com> References: <288df32a0907290451t3ace762dgd902cc928b23dd35@mail.gmail.com> <200907291542.32380.eike.welk@gmx.net> <288df32a0907290727i8b3f521sa4c0f689720e2f8d@mail.gmail.com> Message-ID: On Wed, Jul 29, 2009 at 10:27 AM, Bala subramanian wrote: > I have to do the following: > > Eq 1) F = A * FB + (1-A) FO --------- (1) > > Eq 2) A = 1/2a0 [ ( ao + x + bo) - { ( ao + x + bo)2 - 4 aobo ) }0.5 ] > ............................. (2) > > KNOWN: F, FB, FO, ao, > UNKNOWN:? bo > > I have to fit the data first to Eq 1, find A and then fit it to Eq 2 to find > bo. I know python programming but am very new to this kind of analysis. I > would greatly appreciate if you could provide me some guidance on how to do > the same. > > Thanks, > Bala > It's good practice to reply-all to a mailing list and not to top post (replying at the top of an email), so it's easier to read and follow the discussion. What is your fitting criterion? Ie., are you trying to minimize the sum of squared errors (least squares), etc. There are different fitting criteria depending on what kind of data you have and where your noise is expected to come from. It looks like you could do this with a least squares fit if you want, putting linear constraints on the coefficients (which should be a part of the scipy.models soon), or you could rearrange the equations to get your unknown in only one place. Eq 1 would then be F = FO + A * (FB - FA) You can do similarly for equation 2 I think but didn't look closely. I'm still not sure what everything is in those equations. If you ask over on the scipy-user list and include the equations and a data example, you will almost certainly get some more help. Cheers, Skipper > > On Wed, Jul 29, 2009 at 3:59 PM, Skipper Seabold > wrote: >> >> On Wed, Jul 29, 2009 at 9:42 AM, Eike Welk wrote: >> > On Wednesday 29 July 2009, Bala subramanian wrote: >> >> Friends, >> >> >> >> I wish to do some curve fitting with python by defining my own >> >> equations. Could someone please give some guidance or examples on >> >> doing the same. >> > >> >> What kind of curve fitting exactly? ?Linear equations? ?Can you >> provide an example? >> >> > You can use the Numpy/Scipy libraries for that. I think they have >> > examples for curve fitting on their website. But unfortunately the >> > website is down (or my Internet is broken). >> > >> > http://www.scipy.org/ >> > >> >> There were some problems with the site yesterday as well. ?Scipy would >> be a good place to start. ?I am in the home stretch of completing a >> google summer of code project to integrate some mostly linear >> statistical models (different flavors of least squares fitting, >> generalized linear models, robust statistics, generalized additive >> models, etc.) into SciPy, which might also be of interest to you >> depending on your needs (some info here >> ). ?There are also some "cookbook" >> examples from the scipy page that show some recipes for doing some >> basic curve fitting (OLS, interpolation) with the available tools. >> >> > There are also special mailing lists for Numpy/Scipy/Matplotlib users, >> > to which you should subscribe. This one would be good for your >> > question: >> > http://projects.scipy.org/mailman/listinfo/scipy-user >> > >> > >> > If I understand you right, you have a formula with some parameters. >> > Now you are searching for parameter values so that the formula really >> > goes through the data points. This is a task for optimization >> > functions. >> > >> > Kind regards, >> > Eike. >> > _______________________________________________ >> > Tutor maillist ?- ?Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From eike.welk at gmx.net Wed Jul 29 19:23:49 2009 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 29 Jul 2009 19:23:49 +0200 Subject: [Tutor] Fwd: Re: curve fitting Message-ID: <200907291923.50059.eike.welk@gmx.net> Forwarding Skipper's other message, which must have somehow been lost: ---------- Forwarded Message ---------- Subject: Re: [Tutor] curve fitting Date: Wednesday 29 July 2009 From: Skipper Seabold To: Eike Welk On Wed, Jul 29, 2009 at 9:42 AM, Eike Welk wrote: > On Wednesday 29 July 2009, Bala subramanian wrote: >> Friends, >> >> I wish to do some curve fitting with python by defining my own >> equations. Could someone please give some guidance or examples on >> doing the same. > What kind of curve fitting exactly? Linear equations? Can you provide an example? > You can use the Numpy/Scipy libraries for that. I think they have > examples for curve fitting on their website. But unfortunately the > website is down (or my Internet is broken). > > http://www.scipy.org/ > There were some problems with the site yesterday as well. Scipy would be a good place to start. I am in the home stretch of completing a google summer of code project to integrate some mostly linear statistical models (different flavors of least squares fitting, generalized linear models, robust statistics, generalized additive models, etc.) into SciPy, which might also be of interest to you depending on your needs (some info here ). There are also some "cookbook" examples from the scipy page that show some recipes for doing some basic curve fitting (OLS, interpolation) with the available tools. > There are also special mailing lists for Numpy/Scipy/Matplotlib users, > to which you should subscribe. This one would be good for your > question: > http://projects.scipy.org/mailman/listinfo/scipy-user > > > If I understand you right, you have a formula with some parameters. > Now you are searching for parameter values so that the formula really > goes through the data points. This is a task for optimization > functions. > > Kind regards, > Eike. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------------------------------- From ctcast at gmail.com Wed Jul 29 19:55:27 2009 From: ctcast at gmail.com (Chris Castillo) Date: Wed, 29 Jul 2009 12:55:27 -0500 Subject: [Tutor] (no subject) Message-ID: <50e459210907291055n6311813cvcac121646a8e579e@mail.gmail.com> # Module demonstrates use of lists and set theory principles def Unite(set1, set2): # evaluate 2 lists, join both into 1 new list newList = [] for item in set1: newList.append(item) for item in set2: newList.append(item) newList.sort() return newList def Intersect(set1, set2): # evaluate 2 lists, check for commonalities, output commonalities to 1 new list newList = [] for item in set1: if item in set1 and item in set2: newList.append(item) newList.sort() return newList def Negate(set1, set2): # evaluate 2 lists, return negation of 1st list newList = [] for item in set1: if item in set2: set1.remove(item) newList = set1 return newList could this be done in a more elegant fashion? From tomar.arun at gmail.com Wed Jul 29 20:43:46 2009 From: tomar.arun at gmail.com (Arun Tomar) Date: Thu, 30 Jul 2009 00:13:46 +0530 Subject: [Tutor] Web crawling! In-Reply-To: <97233.1648.qm@web43406.mail.sp1.yahoo.com> References: <97233.1648.qm@web43406.mail.sp1.yahoo.com> Message-ID: <202c460907291143s33599035j68672f2b63da2036@mail.gmail.com> Hi! Raj. On Wed, Jul 29, 2009 at 9:29 PM, Raj Medhekar wrote: > Does anyone know a good webcrawler that could be used in tandem with the > Beautiful soup parser to parse out specific elements from news sites like > BBC and CNN? Thanks! > -Raj > As i didn't find any good webcrawler as per my clients need, so i wrote one for them, but it's specific for their need only. i can't disclose any more details about it. In short, i'm using my app to crawl the specific sites, then parse it with beautiful soup and extract all the links on that page, then visit the links and search for the keywords on those pages. If the keyword is occurs more than the specified limit then it's a useful link and store it in the database or else leave it. -- Regards, Arun Tomar blog: http://linuxguy.in website: http://www.solutionenterprises.co.in -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinces1979 at gmail.com Wed Jul 29 20:53:32 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 29 Jul 2009 12:53:32 -0600 Subject: [Tutor] Web crawling! In-Reply-To: <97233.1648.qm@web43406.mail.sp1.yahoo.com> References: <97233.1648.qm@web43406.mail.sp1.yahoo.com> Message-ID: <1e53c510907291153q4d0fde0dhb237bdb876083978@mail.gmail.com> On Wed, Jul 29, 2009 at 9:59 AM, Raj Medhekar wrote: > Does anyone know a good webcrawler that could be used in tandem with the > Beautiful soup parser to parse out specific elements from news sites like > BBC and CNN? Thanks! > -Raj > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I have used httplib2 http://code.google.com/p/httplib2/ to crawl sites(with auth/cookies) and lxml (html xpath) to parse out links. but you could use builtin urllib2 to request pages if no auth/cookie support is required, here is a simple example import urllib2 from lxml import html page = urllib2.urlopen("http://this.page.com ") data = html.fromstring(page.read()) all_links = data.xpath("//a") # all links on the page for link in all_links: print link.attrib["href"] -------------- next part -------------- An HTML attachment was scrubbed... URL: From goodpotatoes at yahoo.com Wed Jul 29 19:35:45 2009 From: goodpotatoes at yahoo.com (gpo) Date: Wed, 29 Jul 2009 10:35:45 -0700 (PDT) Subject: [Tutor] Issues with regex escaping on \{ Message-ID: <24724060.post@talk.nabble.com> My regex is being run in both Python v2.6 and v3.1 For this example, I'll give one line. This lines will be read out of log files. I'm trying to get the GUID for the User ID to query a database with it, so I'd like a sub match. Here is the code ----------------- import re line = '>Checking Privilege for UserId: {88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: {71AD2527-8494-4654-968D-FE61E9A6A9DF}. Returned hr = 0' pUserID=re.compile('UserID: \{(.+)\}',re.I) #Sub match is one or more characters between the first set of squigglies immediately following 'UserID: ' #the output is: (re.search(pUserID,line)).group(1) '88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: {71AD2527-8494-4654-968D-FE61E9A6A9DF' ----------- Why isn't the match terminating after it finds the first \} ? -- View this message in context: http://www.nabble.com/Issues-with-regex-escaping-on-%5C%7B-tp24724060p24724060.html Sent from the Python - tutor mailing list archive at Nabble.com. From relipse at gmail.com Wed Jul 29 20:32:37 2009 From: relipse at gmail.com (tearsfornations) Date: Wed, 29 Jul 2009 11:32:37 -0700 (PDT) Subject: [Tutor] Parsing Bible verses In-Reply-To: <5e58f2e40905252255x31c20568uf6ebd1687e294fd7@mail.gmail.com> References: <9356b9f30905211426v3b684694if8ef0fc730e82258@mail.gmail.com> <8633E44E09394855BC66724793935E49@kisc.edu.np> <9356b9f30905252248m43541578m78f0bb7a998ba7a6@mail.gmail.com> <5e58f2e40905252255x31c20568uf6ebd1687e294fd7@mail.gmail.com> Message-ID: <24725020.post@talk.nabble.com> hey, i recently was working on some custom bible software and created an sqlite3 database of a few different bibles, one of which is the American Standard Version (ASV) which you can download here http://tearsfornations.hostcell.net/bibledoth/asv.bible.sqlite3 here is the create tables CREATE TABLE bible_info ( description VARCHAR(55), abbreviation VARCHAR(7), comments TEXT, font VARCHAR(15), format VARCHAR(10), strongs BOOLEAN ); CREATE TABLE [bible_verses] ( [b] int(4) NULL, [c] int(4) NULL, [v] int(4) NULL, [t] text NULL, PRIMARY KEY ([b],[c],[v]) ); John Fouhy wrote: > > 2009/5/26 Eduardo Vieira : >> Now, a little farther on the topic of a Bible database. I'm not sure >> how I should proceed. I don't really have the db file I need, I will >> have to generate it somehow, from a bible software, because the >> version I want is for Portuguese. I have found a bible in sql, a bible >> in MS Access to give me some ideas on how to structure my database. >> But my question is do I really need a sql database for my need, since >> I will be only reading from it? Never adding or updating. One like >> sqlite. Would a pickled dictionary from Bible_reference to verse be >> faster? Should I work with anydbm? > > If you don't want to use a database, you should probably use the shelve > module. > > However, there is really no particular reason not to use a relational > database. It seems a solution fairly well suited to your problem. > Python has a database supplied these days: sqlite3. I suggest using > that, rather than MS Access. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Parsing-Bible-verses-tp23660711p24725020.html Sent from the Python - tutor mailing list archive at Nabble.com. From vinces1979 at gmail.com Wed Jul 29 21:18:04 2009 From: vinces1979 at gmail.com (vince spicer) Date: Wed, 29 Jul 2009 13:18:04 -0600 Subject: [Tutor] Issues with regex escaping on \{ In-Reply-To: <24724060.post@talk.nabble.com> References: <24724060.post@talk.nabble.com> Message-ID: <1e53c510907291218y4dd1ec30h506eea1b543763a9@mail.gmail.com> On Wed, Jul 29, 2009 at 11:35 AM, gpo wrote: > > My regex is being run in both Python v2.6 and v3.1 > For this example, I'll give one line. This lines will be read out of log > files. I'm trying to get the GUID for the User ID to query a database with > it, so I'd like a sub match. Here is the code > ----------------- > import re > line = '>Checking Privilege for UserId: > {88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: > {71AD2527-8494-4654-968D-FE61E9A6A9DF}. Returned hr = 0' > pUserID=re.compile('UserID: \{(.+)\}',re.I) #Sub match is one or more > characters between the first set of squigglies immediately following > 'UserID: ' > > #the output is: > (re.search(pUserID,line)).group(1) > '88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: > {71AD2527-8494-4654-968D-FE61E9A6A9DF' > ----------- > Why isn't the match terminating after it finds the first \} ? > -- > View this message in context: > http://www.nabble.com/Issues-with-regex-escaping-on-%5C%7B-tp24724060p24724060.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > your grouping (.+) appears to be greedy, you can make it non-greedy with a question mark EX: pUserID=re.compile('UserID:\s+{(.+?)}',re.I) Vince -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Wed Jul 29 21:29:17 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 29 Jul 2009 15:29:17 -0400 Subject: [Tutor] manipulating lists In-Reply-To: <50e459210907291055n6311813cvcac121646a8e579e@mail.gmail.com> References: <50e459210907291055n6311813cvcac121646a8e579e@mail.gmail.com> Message-ID: <4A70A30D.7010301@ieee.org> (You omitted a title, so I made one up. Hope it's okay) Chris Castillo wrote: > # Module demonstrates use of lists and set theory principles > > def Unite(set1, set2): # evaluate 2 lists, join both into 1 new list > newList = [] > for item in set1: > newList.append(item) > for item in set2: > newList.append(item) > newList.sort() > return newList > > def Intersect(set1, set2): # evaluate 2 lists, check for > commonalities, output commonalities to 1 new list > newList = [] > for item in set1: > if item in set1 and item in set2: > newList.append(item) > newList.sort() > return newList > > def Negate(set1, set2): # evaluate 2 lists, return negation of 1st list > newList = [] > for item in set1: > if item in set2: > set1.remove(item) > newList = set1 > return newList > > > could this be done in a more elegant fashion? > > Note: don't ever use tabs in source code. Use spaces to indent - preferably 4 each. If you accidentally mix spaces and tabs, you could have very mysterious bugs Just by inspection - untested code: #Use docstring. Use extend rather than append in loop. Use slice notation to make a copy of the items in the list def Unite(set1, set2): """ evaluate 2 lists, join both into 1 new list""" newList = set1[:] newList.extend(set2) return sorted(newList) def Intersect(set1, set2): """ evaluate 2 lists, check for commonalities, output commonalities to 1 new list""" newList = [] for item in set1: if item in set2: newList.append(item) return sorted(newList) #This one was buggy; it modified set1 in place, and returned another reference to it def Negate(set1, set2): """ evaluate 2 lists, items that are in first list, but not in second """ newList = set1[:] for item in set2: newList.remove(item) return newList #Question: did you mean to sort this one too? Now, could these be improved further? Absolutely. Using list comprehensions or similar techniques, some of these loops could be one-liners. But I'm guessing you're a beginner in Python, and it's more important that you get used to writing readable, robust code than clever code. One thing I do recommend, even at this stage, is to study set(). DaveA From bill at celestial.net Wed Jul 29 21:39:37 2009 From: bill at celestial.net (Bill Campbell) Date: Wed, 29 Jul 2009 12:39:37 -0700 Subject: [Tutor] Issues with regex escaping on \{ In-Reply-To: <1e53c510907291218y4dd1ec30h506eea1b543763a9@mail.gmail.com> References: <24724060.post@talk.nabble.com> <1e53c510907291218y4dd1ec30h506eea1b543763a9@mail.gmail.com> Message-ID: <20090729193937.GA26359@ayn.mi.celestial.com> On Wed, Jul 29, 2009, vince spicer wrote: >On Wed, Jul 29, 2009 at 11:35 AM, gpo wrote: > >> >> My regex is being run in both Python v2.6 and v3.1 >> For this example, I'll give one line. This lines will be read out of log >> files. I'm trying to get the GUID for the User ID to query a database with >> it, so I'd like a sub match. Here is the code >> ----------------- >> import re >> line = '>Checking Privilege for UserId: >> {88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: >> {71AD2527-8494-4654-968D-FE61E9A6A9DF}. Returned hr = 0' >> pUserID=re.compile('UserID: \{(.+)\}',re.I) #Sub match is one or more >> characters between the first set of squigglies immediately following >> 'UserID: ' >> >> #the output is: >> (re.search(pUserID,line)).group(1) >> '88F96ED2-D471-DE11-95B6-0050569E7C88}, PrivilegeId: >> {71AD2527-8494-4654-968D-FE61E9A6A9DF' >> ----------- >> Why isn't the match terminating after it finds the first \} ? ... >your grouping (.+) appears to be greedy, you can make it non-greedy with a >question mark As a general rule, it's a Good Idea(tm) to write regular expressions using the raw quote syntax. Instead of: re.compile('UserID: \{(.+)\}',...) Use: re.compile(r'UserID: \{(.+)\}',...) The alternative is to backwhack any special characters with an appropriate number if ``\'' characters, whatever that may be. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 Government is a broker in pillage, and every election is a sort of advance auction in stolen goods. -- H.L. Mencken From alan.gauld at btinternet.com Wed Jul 29 21:49:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Jul 2009 20:49:13 +0100 Subject: [Tutor] concerning help() function References: <4A6FEC57.10103@gmx.net> Message-ID: "David" wrote > whenever I make use of the help() function, I have a good chance of > getting an error. I have not yet understood this tool very well. You need to import the module to maker the name visible > help(random) > help('operator') > > I figured this by trial and error, error mainly. What you are seeing is the help for the string 'operator' - which is the same as the help for any other string - the builtin string methods. Comparte it with >>> help('') HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jul 29 21:52:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Jul 2009 20:52:36 +0100 Subject: [Tutor] concerning help() function References: <4A6FEC57.10103@gmx.net> Message-ID: > help('operator') > > I figured this by trial and error, and I am keen to find out when the Oops, always try before posting! And don;t assume... I juast vdid and you are right, it does give help on an unimported module! Sorry, how embarrassing! :-) Alan G From alan.gauld at btinternet.com Wed Jul 29 21:54:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 29 Jul 2009 20:54:41 +0100 Subject: [Tutor] (no subject) References: <50e459210907291055n6311813cvcac121646a8e579e@mail.gmail.com> Message-ID: "Chris Castillo" wrote ># Module demonstrates use of lists and set theory principles > > could this be done in a more elegant fashion? Yes use the Python set type. Alan G From wescpy at gmail.com Wed Jul 29 22:17:45 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 29 Jul 2009 13:17:45 -0700 Subject: [Tutor] Issues with regex escaping on \{ In-Reply-To: <24724060.post@talk.nabble.com> References: <24724060.post@talk.nabble.com> Message-ID: <78b3a9580907291317sc33403epb4bd55ffaed4c992@mail.gmail.com> in addition to the good advice from vince (watch out for greediness regardless of what you're looking for) and bill (use raw strings... regexes are one of their primary use cases!), another thing that may help with the greediness issue are the character sets you're using inside to match with. for example, if you know the string inside the curly braces, e.g., {88F96ED2-D471-DE11-95B6-0050569E7C88}, are numbers and letters and dashes, you can use "[\w-]+" which means one or more alphanumeric characters plus the dash. the use of ".+" is just *asking* for greedy gobbling up of characters like "}" because "." means match any single character. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Wed Jul 29 22:27:23 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 29 Jul 2009 13:27:23 -0700 Subject: [Tutor] implementing set operations [was Re: (no subject)] Message-ID: <78b3a9580907291327p36bf7bd7kaa2b2aa87db4a4eb@mail.gmail.com> > could this be done in a more elegant fashion? in addition to alan's obvious solution, if you wanted to roll your own, you have a good start. my comments below. > def Unite(set1, set2): ? ? ? ? ?# evaluate 2 lists, join both into 1 new list > ? ? ? ?newList = [] > ? ? ? ?for item in set1: > ? ? ? ? ? ? ? ?newList.append(item) > ? ? ? ?for item in set2: > ? ? ? ? ? ? ? ?newList.append(item) > ? ? ? ?newList.sort() > ? ? ? ?return newList - as a style point, use lowercase for all function and variable names. Capping the first letter is recommended only for class names. - changing it from "unite" to "union" would make it slightly more accurate - why the sort()? sets, are by default, unordered data structures... think of drawing its elements inside the circles in Venn diagrams. - if you do end up using Python sets, use the set() factory function in 2.x, i.e, newSet = set(set1) + set(set2); or set literals in Python 3.x, i.e., mySet = {1, 5, -4, 42}, if you have the exact elements > def Intersect(set1, set2): ? ? ? ? ? ? ?# evaluate 2 lists, check for > commonalities, output commonalities to 1 new list > ? ? ? ?newList = [] > ? ? ? ?for item in set1: > ? ? ? ? ? ? ? ?if item in set1 and item in set2: > ? ? ? ? ? ? ? ? ? ? ? ?newList.append(item) > ? ? ? ?newList.sort() > ? ? ? ?return newList - the "item in set1 and " in the if-statement is redundant. blow it away - i think you can build it using a listcomp > def Negate(set1, set2): ? ? ? ? # evaluate 2 lists, return negation of 1st list > ? ? ? ?newList = [] > ? ? ? ?for item in set1: > ? ? ? ? ? ? ? ?if item in set2: > ? ? ? ? ? ? ? ? ? ? ? ?set1.remove(item) > ? ? ? ?newList = set1 > ? ? ? ?return newList - you probably don't want to call set1.remove(). lists are immutable, and you would've change the contents of set1. it's best if you made newList a copy of set1, i.e., newList = list(set1) or newList = set1[:], and *then* did your for-loop - better yet, use a list comp with an if to build newList to avoid all of the shenanigans i just described hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Thu Jul 30 00:04:15 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 29 Jul 2009 15:04:15 -0700 Subject: [Tutor] implementing set operations [was Re: (no subject)] In-Reply-To: <78b3a9580907291327p36bf7bd7kaa2b2aa87db4a4eb@mail.gmail.com> References: <78b3a9580907291327p36bf7bd7kaa2b2aa87db4a4eb@mail.gmail.com> Message-ID: <78b3a9580907291504i3ac5bea2h4b7c3f6bdf687aa3@mail.gmail.com> > - you probably don't want to call set1.remove(). lists are immutable, > and you would've change the contents of set1. sorry, make that "mutable." sets, dicts, and lists are standard Python types that are mutable. -wesley From amit.pureenergy at gmail.com Thu Jul 30 00:45:23 2009 From: amit.pureenergy at gmail.com (Amit Sethi) Date: Thu, 30 Jul 2009 04:15:23 +0530 Subject: [Tutor] Currency conversion module in python Message-ID: Hi , Does anybody know of any currency conversion module in python -- A-M-I-T S|S From wescpy at gmail.com Thu Jul 30 10:06:33 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 30 Jul 2009 01:06:33 -0700 Subject: [Tutor] how to join two different files In-Reply-To: <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> References: <2359.210.212.36.65.1247855827.squirrel@www.iisermohali.ac.in> <1c2a2c590907171327h57c2ce7fi7169d546f0b0663a@mail.gmail.com> <78b3a9580907171550t2325312cgc5d938b05e11a22e@mail.gmail.com> Message-ID: <78b3a9580907300106g60186af9jf33f118cc12e7efd@mail.gmail.com> >> Maybe you could break that up a bit? This is the tutor list, not a >> one-liner competition! > > rather than one-liners, we can try to create the most "Pythonic" solution. below's my entry. :-) > > myMac$ cat parafiles.py > #!/usr/bin/env python > > from itertools import izip > from os.path import exists > > def parafiles(*files): > ? ?vec = (open(f) for f in files if exists(f)) > ? ?data = izip(*vec) > ? ?[f.close() for f in vec] > ? ?return data > > for data in parafiles('fileA.txt', 'fileB.txt'): > ? ?print ' '.join(d.strip() for d in data) i proposed this problem as a code golfing competition to my co-workers, and after tweaking it slightly to take filenames from the command-line instead of as function parameters, i reduced my original solution to: from itertools import izip from os.path import exists from sys import argv vec = (open(f) for f in argv[1:] if exists(f)) for d in izip(*vec): print ' '.join(c.strip() for c in d) for f in vec: f.close() if this was a code golf competition, and i was more careless about leaking filehandles (or letting Python deal with it), i can actually reduce it to an ugly (yet elegant) 1-liner serving as an example of how *not* to code in production: print '\n'.join(' '.join(c.strip() for c in d) for d in izip(*(open(f) for f in argv[1:] if exists(f)))) note that the only list used here is sys.argv (using map() or [listcomp] creates lists which use memory... superfluous if only iterating across them once). anyway, please don't try this at work folks. :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From zebra05 at gmail.com Thu Jul 30 10:02:39 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Thu, 30 Jul 2009 10:02:39 +0200 Subject: [Tutor] Currency conversion module in python In-Reply-To: References: Message-ID: Hi Amit, this might be what you want..hopefully with a dollop of humor :) http://lmgtfy.com/?q=currency+conversion+module+in+python&l=1 Cheers On Thu, Jul 30, 2009 at 12:45 AM, Amit Sethi wrote: > Hi , Does anybody know of any currency conversion module in python > > -- > A-M-I-T S|S > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Thu Jul 30 10:39:15 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 30 Jul 2009 14:09:15 +0530 Subject: [Tutor] flag to call methods on objects? Message-ID: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> hello I wanted to prevent other users of my computers to read my files. So tried to creat a module to achieve it. I used a flag to deside which methods to be called on the object. somehow it is not working.I realise after 2 days of struggle that as it is usuel , I am blind to my faults. I tested all the metheds except main() in idle interactively,found them working. So there is a bug in the main(), kan anyone point it out to me? #! usr/bin/env python import ast,random,os,zlib,string key=5 class Cripto(object): def __init__(self,afile): self.afile=afile def __digi(self,astring): y=[] for x in astring: y.append(ord(x)) y=str(y) return y def __undigi(self,astring): alist=ast.literal_eval(astring) y=[] for x in alist: y.append(chr(x)) astring=''.join(y) return astring def __gen_string(self): s='' nl=random.sample(string.ascii_letters,key) for x in nl:s+=x return s def __lengthen(self,astring): s=list(astring) ns='' for x in s: ns+=x ns+=gen_string() return ns def __shorten(self,astring): s=list(astring) ns='' for x in range(0,len(s),key+1): ns+=s[x] return ns def __compress(self,astring): astring=zlib.compress(astring) return astring def __decompress(self,astring): astring=zlib.decompress(astring) return astring def main(self): sorce=open(self.afile,'r') data=(sorce.readlines()) dest=open ((os.path.split(self.afile)[0]+os.sep+'temp'),'w') if data[:1]=='flag1\n': ns='flag0\n' data=data[1:] for line in data: nl=__compress((__digi(__lengthen(line.strip()))))+'\n' ns+=nl dest.write(ns) elif data[:1]=='flag0\n': ns='flag1\n' data=data[1:] for line in data: nl=__decompress((__undigi(__shorten(line.strip()))))+'\n' ns+=nl dest.write(ns) sorce.close() dest.close() os.remove(self.afile) os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) #======== a=Cripto('C:/pp.txt') a.main() <\code> -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Thu Jul 30 15:49:53 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 30 Jul 2009 19:19:53 +0530 Subject: [Tutor] flag to call methods on objects? In-Reply-To: References: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> Message-ID: <9e3fac840907300649v9335345s867474a2ae311b05@mail.gmail.com> On 7/30/09, Rich Lovely wrote: > > 2009/7/30 prasad rao prasadaraon50 at gmail.com: >I'm sure there are modules available for PGP that are either part of > >the stdlib, or available from a quick google. PGP (or GPG) encryopts > I never know there is an encryption module in stdlib. What is its name? Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Jul 30 16:11:42 2009 From: srilyk at gmail.com (Wayne) Date: Thu, 30 Jul 2009 09:11:42 -0500 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <9e3fac840907300649v9335345s867474a2ae311b05@mail.gmail.com> References: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> <9e3fac840907300649v9335345s867474a2ae311b05@mail.gmail.com> Message-ID: <333efb450907300711n6fdc0a64jb66c2b3407ef7c30@mail.gmail.com> On Thu, Jul 30, 2009 at 8:49 AM, prasad rao wrote: > > > On 7/30/09, Rich Lovely wrote: >> >> 2009/7/30 prasad rao prasadaraon50 at gmail.com: > > > > > >I'm sure there are modules available for PGP that are either part of >> >the stdlib, or available from a quick google. PGP (or GPG) encryopts >> > > I never know there is an encryption module in stdlib. > What is its name? > If you're only partially concerned (i.e. don't care about 'real' encryption) you can use some of the string library encryptions. def test_encod(mystr): mystr = str(mystr) print "%s zip encoded: %s" % (mystr, mystr.encode('zip')) print "%s rot13 encoded: %s" % (mystr, mystr.encode('rot13')) print "%s hex encoded: %s" % (mystr, mystr.encode('hex')) print "%s Base 64 encoded: %s" % (mystr, mystr.encode('base64')) In [41]: test_encode("The quick brown fox jumps over the lazy dogs") The quick brown fox jumps over the lazy dogs zip encoded: x? ?HU(,?L?VH*?/?SH??P?*?-(V?/K-R(J?$VU*???l)M The quick brown fox jumps over the lazy dogs rot13 encoded: Gur dhvpx oebja sbk whzcf bire gur ynml qbtf The quick brown fox jumps over the lazy dogs hex encoded: 54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f6773 The quick brown fox jumps over the lazy dogs Base 64 encoded: VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZ3M= So you could easily convert with encode and then reconvert with decode. Another option would be a simple XOR of your data ( from here: http://www.evanfosmark.com/2008/06/xor-encryption-with-python/ ) from itertools import izip, cycle def xor_crypt_string(data, key): return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key))) On the page provided someone also gave their code that can encrypt files. Of course any of these methods presume you're just trying to keep the casual snoop from getting access to your data. Anyone with time/inclination/tools can go ahead and break most encryptions. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Jul 30 17:02:46 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 30 Jul 2009 11:02:46 -0400 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> References: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> Message-ID: <4A71B616.6050200@ieee.org> prasad rao wrote: > hello > I wanted to prevent other users of my computers to read my files. > So tried to creat a module to achieve it. > I used a flag to deside which methods to be called on the object. > somehow it is not working.I realise after 2 days of struggle that > as it is usuel , I am blind to my faults. > I tested all the metheds except main() in idle interactively,found them > working. > So there is a bug in the main(), kan anyone point it out to me? > > > > > #! usr/bin/env python > > import ast,random,os,zlib,string > key=5 > class Cripto(object): > def __init__(self,afile): > self.afile=afile > def __digi(self,astring): > y=[] > for x in astring: > y.append(ord(x)) > y=str(y) > > return y > def __undigi(self,astring): > > alist=ast.literal_eval(astring) > y=[] > for x in alist: > y.append(chr(x)) > astring=''.join(y) > return astring > def __gen_string(self): > s='' > nl=random.sample(string.ascii_letters,key) > for x in nl:s+=x > return s > > def __lengthen(self,astring): > s=list(astring) > ns='' > for x in s: > ns+=x > ns+=gen_string() > return ns > def __shorten(self,astring): > > s=list(astring) > ns='' > for x in range(0,len(s),key+1): > ns+=s[x] > return ns > def __compress(self,astring): > astring=zlib.compress(astring) > return astring > def __decompress(self,astring): > astring=zlib.decompress(astring) > return astring > def main(self): > sorce=open(self.afile,'r') > data=(sorce.readlines()) > dest=open ((os.path.split(self.afile)[0]+os.sep+'temp'),'w') > if data[:1]=='flag1\n': > ns='flag0\n' > data=data[1:] > for line in data: > nl=__compress((__digi(__lengthen(line.strip()))))+'\n' > ns+=nl > dest.write(ns) > elif data[:1]=='flag0\n': > ns='flag1\n' > data=data[1:] > for line in data: > nl=__decompress((__undigi(__shorten(line.strip()))))+'\n' > ns+=nl > dest.write(ns) > > sorce.close() > dest.close() > > os.remove(self.afile) > os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) > > > #======== > a=Cripto('C:/pp.txt') > a.main() > > > <\code> > > First problem is the indentation. It won't compile as it is. I'll assume that was somehow a pasting error. Next problem is where you're comparing for 'flag1' Your line if data[:1] == 'flag1\n' is comparing a list on the left side to a string on the right. If it were me, I'd replace that test, and the similar one below it, with if data[0].rstrip()=='flag1': The reason for the rstrip() is to make it easier for a test harness, where it may be a pain to get the newlines on each line. Also, it's harder to spot a whitespace error. Next problem/question is whether this is only going to be used for files that happen to begin with a line flag1. If so, it should be documented as part of the code, along with all the other missing documentation/docstrings. That's as far as I went; I did not test the actual encoding logic But some free advice for next time: When you ask a question, please supply a compilable program, and either test data, or enough description that we can build such. And please tell us what the symptom is. "it is not working." is not very descriptive. DaveA From goodpotatoes at yahoo.com Wed Jul 29 21:47:57 2009 From: goodpotatoes at yahoo.com (gpo) Date: Wed, 29 Jul 2009 12:47:57 -0700 (PDT) Subject: [Tutor] Issues with regex escaping on \{ In-Reply-To: <1e53c510907291218y4dd1ec30h506eea1b543763a9@mail.gmail.com> References: <24724060.post@talk.nabble.com> <1e53c510907291218y4dd1ec30h506eea1b543763a9@mail.gmail.com> Message-ID: <24726284.post@talk.nabble.com> Thanks! The ? got rid of the greediness! vince spicer wrote: > > On Wed, Jul 29, 2009 at 11:35 AM, gpo wrote: > > > your grouping (.+) appears to be greedy, you can make it non-greedy with a > question mark > > EX: > > pUserID=re.compile('UserID:\s+{(.+?)}',re.I) > > Vince > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Issues-with-regex-escaping-on-%5C%7B-tp24724060p24726284.html Sent from the Python - tutor mailing list archive at Nabble.com. From ironhawk at hickorytech.net Thu Jul 30 16:36:00 2009 From: ironhawk at hickorytech.net (Randy Seys) Date: Thu, 30 Jul 2009 09:36:00 -0500 Subject: [Tutor] Companion CD for Python Book Message-ID: <7E4C636A1E154FBF8DF7A66E004D22A7@prv1.mico.com> Hi, I recently purchased a used book with the title Python Programming for the Absolute Beginner, Second Edition, by Michael Dawson. The book is supposed include a companion CD, but the CD is broken. I've already contacted the publisher for a replacement, but they were not able to help me. If someone has this CD, would it be possible for me to receive a zip file of the CD contents? Any other ideas on how I could get a copy of this CD? Thank you for any help you can pass my way. Regards, Randy S Mankato, MN -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Thu Jul 30 18:32:17 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 30 Jul 2009 22:02:17 +0530 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <4A71B616.6050200@ieee.org> References: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> <4A71B616.6050200@ieee.org> Message-ID: <9e3fac840907300932v78690d6eke438f41acd62bfa6@mail.gmail.com> On 7/30/09, Dave Angel wrote: > > prasad rao wrote: > >> hello >> >> >"it is not working." is not very descriptive. >> >> >> DaveA >> > Hello! Sorry, I forgot to mention the problem. It simply wipes clean the file,resulting in empty file. Yes .I should compare with a string.Hope I will get it right with that correction. Thank you Wayne. I never know string module can be used for encryption. I will try all those methods(shown by you) in my module. Thank you all Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Jul 30 19:29:59 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 30 Jul 2009 13:29:59 -0400 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <9e3fac840907300932v78690d6eke438f41acd62bfa6@mail.gmail.com> References: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> <4A71B616.6050200@ieee.org> <9e3fac840907300932v78690d6eke438f41acd62bfa6@mail.gmail.com> Message-ID: <4A71D897.2010402@ieee.org> prasad rao wrote: > On 7/30/09, Dave Angel wrote: > >> prasad rao wrote: >> >> >>> hello >>> >>> >>>> "it is not working." is not very descriptive. >>>> >>> DaveA >>> >>> >> Hello! Sorry, I forgot to mention the problem. >> > It simply wipes clean the file,resulting in empty file. > Yes .I should compare with a string.Hope I will get it > right with that correction. > > That's due to another bug in the main() method. You have an if, elif, but no else clause when you're checking the first line. So if you have a file that does *not* begin with the magic string, it'll get truncated. Probably not part of your spec. DaveA From steve at alchemy.com Thu Jul 30 19:57:29 2009 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 30 Jul 2009 10:57:29 -0700 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <333efb450907300711n6fdc0a64jb66c2b3407ef7c30@mail.gmail.com> References: <9e3fac840907300139q5cd01e1es7c8dbff0f0952290@mail.gmail.com> <9e3fac840907300649v9335345s867474a2ae311b05@mail.gmail.com> <333efb450907300711n6fdc0a64jb66c2b3407ef7c30@mail.gmail.com> Message-ID: <20090730175729.GA91144@dragon.alchemy.com> On Thu, Jul 30, 2009 at 09:11:42AM -0500, Wayne wrote: > If you're only partially concerned (i.e. don't care about 'real' encryption) > you can use some of the string library encryptions. Please don't get used to calling these "encryption". They have nothing at all to do with encrypting data. (Well, ROT13 does, I suppose, but not seriously). They are for "encoding" which is simply representing data in a different FORMAT. They do not encrypt data. Yes, people have actually tried "encrypting" passwords sent between browsers and web apps using base64 and suchlike. BIG mistake. You do say that somewhat, but I think using the word "encryption" or implying that these represent a casual level of encryption, is just leading to trouble. These are things a lot of people can decode in their heads. Libraries like the Python Cryptography Toolkit provide real encryption very easily if you need encryption. > Of course any of these methods presume you're just trying to keep the casual > snoop from getting access to your data. Anyone with time/inclination/tools > can go ahead and break most encryptions. In one line of code, you can convert a string to base64 or hex and get a string that would take anyone caring to about 2 seconds to reverse, using tools as simple as most text editors, python itself, or for that matter some network monitoring programs which might pick up that data in flight would just automatically decode that for you. However, in only another line or so of code, you can encrypt your data using AES or Blowfish or whatever, which would require highly specialized tools, extremely expensive equipment, and if you were not either a major government, independently wealthy and very motivated to get that data, it's not going to be broken. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From pine508 at hotmail.com Thu Jul 30 20:18:05 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 30 Jul 2009 14:18:05 -0400 Subject: [Tutor] Currency conversion module in python In-Reply-To: References: Message-ID: Did you actually look at what happens when you click that link? (i.e. where you are brought to?). Because upon viewing this I achieved enlightenment! :D Date: Thu, 30 Jul 2009 10:02:39 +0200 From: zebra05 at gmail.com To: amit.pureenergy at gmail.com CC: tutor at python.org Subject: Re: [Tutor] Currency conversion module in python Hi Amit, this might be what you want..hopefully with a dollop of humor :) http://lmgtfy.com/?q=currency+conversion+module+in+python&l=1 Cheers On Thu, Jul 30, 2009 at 12:45 AM, Amit Sethi wrote: Hi , Does anybody know of any currency conversion module in python -- A-M-I-T S|S _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Lloyd Dube _________________________________________________________________ Windows Live? Hotmail?: Celebrate the moment with your favorite sports pics. Check it out. http://www.windowslive.com/Online/Hotmail/Campaign/QuickAdd?ocid=TXT_TAGLM_WL_QA_HM_sports_photos_072009&cat=sports -------------- next part -------------- An HTML attachment was scrubbed... URL: From marvboyes at gmail.com Thu Jul 30 21:19:55 2009 From: marvboyes at gmail.com (Marv Boyes) Date: Thu, 30 Jul 2009 15:19:55 -0400 Subject: [Tutor] Assigning each line of text to a separate variable Message-ID: <4A71F25B.5030208@gmail.com> Hello, all. This is probably embarrassingly basic, but I haven't been able to find something that works. I'm working on a script that needs to manipulate a list (not 'list' in the Python sense) of URLs returned in a server response. Right now, I'm stripping the XML tags from that response and assigning the resulting list of URLs to a variable so I can print it in the terminal. So when I do, say, 'print urls' I get something like this: http://server.com/thing1 http://server.com/thing2 http://server.com/thing3 And so on. What I would _like_ to do is assign each line of that list to a separate variable, so that I can format my output to be more explicit; something like this: Link to Thing1: http://server.com/thing1 Link to Thing2: http://server.com/thing2 And so on. I know this should be extremely easy, but I appear to be having some manner of mental block. Any and all guidance would be greatly appreciated; many thanks in advance. From vinces1979 at gmail.com Thu Jul 30 21:28:07 2009 From: vinces1979 at gmail.com (vince spicer) Date: Thu, 30 Jul 2009 13:28:07 -0600 Subject: [Tutor] Assigning each line of text to a separate variable In-Reply-To: <4A71F25B.5030208@gmail.com> References: <4A71F25B.5030208@gmail.com> Message-ID: <1e53c510907301228uee5b24crae0e823c6378ece0@mail.gmail.com> On Thu, Jul 30, 2009 at 1:19 PM, Marv Boyes wrote: > Hello, all. This is probably embarrassingly basic, but I haven't been able > to find something that works. > > I'm working on a script that needs to manipulate a list (not 'list' in the > Python sense) of URLs returned in a server response. Right now, I'm > stripping the XML tags from that response and assigning the resulting list > of URLs to a variable so I can print it in the terminal. So when I do, say, > 'print urls' I get something like this: > > http://server.com/thing1 > http://server.com/thing2 > http://server.com/thing3 > > And so on. What I would _like_ to do is assign each line of that list to a > separate variable, so that I can format my output to be more explicit; > something like this: > > Link to Thing1: http://server.com/thing1 > Link to Thing2: http://server.com/thing2 > > And so on. I know this should be extremely easy, but I appear to be having > some manner of mental block. Any and all guidance would be greatly > appreciated; many thanks in advance. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hello, you could use a dictionary to assign a key value and a descrption, but without seeing some data this is very rough data = {} for line in response: key, value = response.split(",") # line is "myname, http://blah.com" data[key] = value #then later for key, value in data.items(): print "Link To %s : %s" % key, value -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jul 30 21:39:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Jul 2009 15:39:47 -0400 Subject: [Tutor] Assigning each line of text to a separate variable In-Reply-To: <4A71F25B.5030208@gmail.com> References: <4A71F25B.5030208@gmail.com> Message-ID: <1c2a2c590907301239g52622080v9a13a0ae7304fdc8@mail.gmail.com> On Thu, Jul 30, 2009 at 3:19 PM, Marv Boyes wrote: > Hello, all. This is probably embarrassingly basic, but I haven't been able > to find something that works. > > I'm working on a script that needs to manipulate a list (not 'list' in the > Python sense) of URLs returned in a server response. Right now, I'm > stripping the XML tags from that response and assigning the resulting list > of URLs to a variable so I can print it in the terminal. So when I do, say, > 'print urls' I get something like this: > > ? ? ? ?http://server.com/thing1 > ? ? ? ?http://server.com/thing2 > ? ? ? ?http://server.com/thing3 > > And so on. What I would _like_ to do is assign each line of that list to a > separate variable, so that I can format my output to be more explicit; > something like this: > > ? ? ? ?Link to Thing1: http://server.com/thing1 > ? ? ? ?Link to Thing2: http://server.com/thing2 It looks like your "list" of URLs is a string containing one URL per line. If you put it in an actual list, you can process it more flexibly. Something like urlList = urls.splitlines() for i, url in enumerate(urlList): print "Link to Thing%s: %s" % (i, url) Kent From marvboyes at gmail.com Thu Jul 30 22:26:11 2009 From: marvboyes at gmail.com (Marv Boyes) Date: Thu, 30 Jul 2009 16:26:11 -0400 Subject: [Tutor] Assigning each line of text to a separate variable In-Reply-To: <1c2a2c590907301239g52622080v9a13a0ae7304fdc8@mail.gmail.com> References: <4A71F25B.5030208@gmail.com> <1c2a2c590907301239g52622080v9a13a0ae7304fdc8@mail.gmail.com> Message-ID: <4A7201E3.10209@gmail.com> I'm very sorry; I should have been more explicit in what it is I'm working with. The response from the server consists of a pair of hashes and a list of URLs for doing different things with the file the hashes represent. So the full response is like this: file_hash delete_hash http://server.com/file_hash.ext http://server.com/file_hashA.ext http://server.com/file_hashB.ext http://server.com/file_hashC.ext http://server.com/delete/deletehash I'm hoping to assign each line of that response to a separate variable so I can format the output on a case-by-case basis, e.g.: direct_link = print "Direct link to file: %s' % direct_link -or- delete_file = print "Delete the file: %s' % delete_file I've got seven lines worth of server response, their order is significant, and I need to be able to present each value in an arbitrary way. I won't necessarily be presenting these values to the user in the same order they come in the server response. Some of the values I'll need to use elsewhere in the script to do other things, but it won't be necessary to present those values to the user. I'm not sure I'm even making sense to myself. Kent Johnson wrote: > On Thu, Jul 30, 2009 at 3:19 PM, Marv Boyes wrote: >> Hello, all. This is probably embarrassingly basic, but I haven't been able >> to find something that works. >> >> I'm working on a script that needs to manipulate a list (not 'list' in the >> Python sense) of URLs returned in a server response. Right now, I'm >> stripping the XML tags from that response and assigning the resulting list >> of URLs to a variable so I can print it in the terminal. So when I do, say, >> 'print urls' I get something like this: >> >> http://server.com/thing1 >> http://server.com/thing2 >> http://server.com/thing3 >> >> And so on. What I would _like_ to do is assign each line of that list to a >> separate variable, so that I can format my output to be more explicit; >> something like this: >> >> Link to Thing1: http://server.com/thing1 >> Link to Thing2: http://server.com/thing2 > > It looks like your "list" of URLs is a string containing one URL per > line. If you put it in an actual list, you can process it more > flexibly. Something like > > urlList = urls.splitlines() > for i, url in enumerate(urlList): > print "Link to Thing%s: %s" % (i, url) > > Kent > From wescpy at gmail.com Thu Jul 30 22:36:40 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 30 Jul 2009 13:36:40 -0700 Subject: [Tutor] Currency conversion module in python In-Reply-To: References: Message-ID: <78b3a9580907301336l47fbe772qd7752fff58cff5a0@mail.gmail.com> On Thu, Jul 30, 2009 at 11:18 AM, Che M wrote: > Did you actually look at what happens when you click that > link?? (i.e. where you are brought to?). > > Because upon viewing this I achieved enlightenment!? :D lucky you... i achieved recursion. :-) From jeremy.d.hoon at gmail.com Thu Jul 30 22:45:39 2009 From: jeremy.d.hoon at gmail.com (Jeremy Hoon) Date: Thu, 30 Jul 2009 16:45:39 -0400 Subject: [Tutor] Assigning each line of text to a separate variable In-Reply-To: <4A7201E3.10209@gmail.com> References: <4A71F25B.5030208@gmail.com> <1c2a2c590907301239g52622080v9a13a0ae7304fdc8@mail.gmail.com> <4A7201E3.10209@gmail.com> Message-ID: <3c1c0ef50907301345y661b7596t11f004bcc78e0c07@mail.gmail.com> On Thu, Jul 30, 2009 at 4:26 PM, Marv Boyes wrote: > I'm very sorry; I should have been more explicit in what it is I'm working > with. > > The response from the server consists of a pair of hashes and a list of URLs > for doing different things with the file the hashes represent. So the full > response is like this: > > ? ? ? ?file_hash > ? ? ? ?delete_hash > ? ? ? ?http://server.com/file_hash.ext > ? ? ? ?http://server.com/file_hashA.ext > ? ? ? ?http://server.com/file_hashB.ext > ? ? ? ?http://server.com/file_hashC.ext > ? ? ? ?http://server.com/delete/deletehash > > I'm hoping to assign each line of that response to a separate variable so I > can format the output on a case-by-case basis, e.g.: > > ? ? ? ?direct_link = > ? ? ? ?print "Direct link to file: %s' % direct_link > > ? ? ? ?-or- > > ? ? ? ?delete_file = > ? ? ? ?print "Delete the file: %s' % delete_file > > I've got seven lines worth of server response, their order is significant, > and I need to be able to present each value in an arbitrary way. I won't > necessarily be presenting these values to the user in the same order they > come in the server response. Some of the values I'll need to use elsewhere > in the script to do other things, but it won't be necessary to present those > values to the user. > > I'm not sure I'm even making sense to myself. > > > Kent Johnson wrote: >> >> On Thu, Jul 30, 2009 at 3:19 PM, Marv Boyes wrote: >>> >>> Hello, all. This is probably embarrassingly basic, but I haven't been >>> able >>> to find something that works. >>> >>> I'm working on a script that needs to manipulate a list (not 'list' in >>> the >>> Python sense) of URLs returned in a server response. Right now, I'm >>> stripping the XML tags from that response and assigning the resulting >>> list >>> of URLs to a variable so I can print it in the terminal. So when I do, >>> say, >>> 'print urls' I get something like this: >>> >>> ? ? ? http://server.com/thing1 >>> ? ? ? http://server.com/thing2 >>> ? ? ? http://server.com/thing3 >>> >>> And so on. What I would _like_ to do is assign each line of that list to >>> a >>> separate variable, so that I can format my output to be more explicit; >>> something like this: >>> >>> ? ? ? Link to Thing1: http://server.com/thing1 >>> ? ? ? Link to Thing2: http://server.com/thing2 >> >> It looks like your "list" of URLs is a string containing one URL per >> line. If you put it in an actual list, you can process it more >> flexibly. Something like >> >> urlList = urls.splitlines() >> for i, url in enumerate(urlList): >> ?print "Link to Thing%s: %s" % (i, url) >> >> Kent >> > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi Marv, While I'm not convinced hard-coding variables to list items is the best solution here, you could achieve it with tuple unpacking: urllist = urls.split() # urllist should have three items in it, otherwise an exception is raised. # You will need to adapt this to the length of your list of urls. link_one,link_two,link_three = urllist print "the first link:", link_one print "the second link:", link_two Best, Jeremy From davea at ieee.org Thu Jul 30 23:13:22 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 30 Jul 2009 17:13:22 -0400 Subject: [Tutor] Assigning each line of text to a separate variable In-Reply-To: <4A71F25B.5030208@gmail.com> References: <4A71F25B.5030208@gmail.com> Message-ID: <4A720CF2.4070700@ieee.org> Marv Boyes wrote: >
Hello, > all. This is probably embarrassingly basic, but I haven't been able to > find something that works. > > I'm working on a script that needs to manipulate a list (not 'list' in > the Python sense) of URLs returned in a server response. Right now, > I'm stripping the XML tags from that response and assigning the > resulting list of URLs to a variable so I can print it in the > terminal. So when I do, say, 'print urls' I get something like this: > > http://server.com/thing1 > http://server.com/thing2 > http://server.com/thing3 > > And so on. What I would _like_ to do is assign each line of that list > to a separate variable, so that I can format my output to be more > explicit; something like this: > > Link to Thing1: http://server.com/thing1 > Link to Thing2: http://server.com/thing2 > > And so on. I know this should be extremely easy, but I appear to be > having some manner of mental block. Any and all guidance would be > greatly appreciated; many thanks in advance. > > Usually, when people say they want to assign items from a list to separate variables, it's because they don't understand lists. But I'll give you several (untested) fragments, and see if one of them comes close to what you really want. Assuming URLs is your current list, and that it has exactly 3 items in it. here, there, everwhere = URLs will give you those three variables, each assigned to one of the URL strings print "Link to Thing1", URLs[0] print "Link to Thing2", URLs[1] print "Link to Thing3", URLs[2] lets you print them out individually, without wasting any separate assignments, or giving them explicit names for index, item in enumerate(URLs): print "Link to Thing%s" % index, item will print out your original request, and even work if you change the list to have 4 or 5 items HTH DaveA From quasipedia at gmail.com Thu Jul 30 23:31:47 2009 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 30 Jul 2009 23:31:47 +0200 Subject: [Tutor] Troubles with the mailing list. Message-ID: <1248989507.13327.33.camel@jabbar> Hi all, having seen a few people in the past days sending "trial messages" on the list I figured it out that I must not be the only one to experience problems with it. I even set up the "notification" feature that sends you an acknowledgement message when your mail is received from the server, but as a matter of facts, I did not even got that back for my previous message. I was just wondering if the list-owners are aware of the problem or not, and if anything can be done to fix it. Mac. PS: I also notice that some messages (quoted in replies) are not reaching my mbox or are reaching it after I got a reply to them. This could be a problem on my side though. Anybody experiencing similar issues? (I am using gmail, btw). From eduardo.susan at gmail.com Thu Jul 30 23:47:27 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 30 Jul 2009 15:47:27 -0600 Subject: [Tutor] Problems understanding control flow Message-ID: <9356b9f30907301447v25fb5232i1c2f7d4a6172e241@mail.gmail.com> Hello, list. I can't understand why the print statement is not printed with the operator '==', but is printed when using 'in'. Here's the code: #=== import csv bv = """NAME,BVADDRTELNO1,BVADDREMAIL Company1, 1234567788, this at that.com CompanyA, 1231234455, that at this.com CompanyC, 1011011111, new at this.com CompanyD, 2222222222, old at olde.com """ site = """Company,Email,Phone "Company3","nothing at nada.com","1234560000" "CompanyD","old at olde.com","2222222222" "Company1","this at that.com","1234567788" """ bv = bv.upper() # This is just to make the data more homogeneous and detect duplicates more easily site = site.upper() bvreader = csv.DictReader(bv.splitlines()) sitelist = csv.DictReader(site.splitlines()) bvreaderone = list(bvreader) # this does not work: for row in sitelist: for line in bvreaderone: if row['EMAIL'] == line['BVADDREMAIL']: print line['NAME'], row['COMPANY'] # but this does work: for row in sitelist: for line in bvreaderone: if row['EMAIL'] in line['BVADDREMAIL']: print line['NAME'], row['COMPANY'] #== Regards, Eduardo From sinistaminista at gmail.com Thu Jul 30 23:45:16 2009 From: sinistaminista at gmail.com (Tommie) Date: Thu, 30 Jul 2009 15:45:16 -0600 Subject: [Tutor] Companion CD for Python Book Message-ID: <380c570b0907301445u593f0bafu28c485b45556dbd3@mail.gmail.com> >Randy S wrote: >Hi, >I recently purchased a used book with the title >Python Programming for the Absolute Beginner, >Second Edition, by Michael Dawson. The book is >supposed include a companion CD, but the CD is >broken. I've already contacted the publisher for a >replacement, but they were not able to help me. If >someone has this CD, would it be possible for me to >receive a zip file of the CD contents? Any other >ideas on how I could get a copy of this CD? >Thank you for any help you can pass my way. >Regards, >Randy S >Mankato, MN I recall reading in an Amazon review last week that someone had similar trouble with this title and was unable to get help from the publisher, but the author was able to help after an email through his website. You may want to look that avenue up.-- Tommie "Any fool can criticize, condemn and complain - and most fools do." --Dale Carnegie -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Jul 31 00:49:39 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 31 Jul 2009 00:49:39 +0200 Subject: [Tutor] Problems understanding control flow In-Reply-To: <9356b9f30907301447v25fb5232i1c2f7d4a6172e241@mail.gmail.com> References: <9356b9f30907301447v25fb5232i1c2f7d4a6172e241@mail.gmail.com> Message-ID: 2009/7/30 Eduardo Vieira : With == you are testing if the 2 values are exactly the same. So 'one' == 'one' will return True but 'one; == 'one two' will return False. With in you test if the value is part of a another value. So using the same value as above 'one' in 'one' will return True but 'one' in 'one two' will also return True as 'one' is part of the second string. The same logic applies to lists and dicts. 'one' == ['one', 'two'] will return False as the the 2 values are not exactly the same but 'one' in ['one', 'two'] will return True. > # this does not work: > for row in sitelist: > ? for line in bvreaderone: If you are getting unexpected results add in print statements to see what is the data that you are working with. I would add the below 2 print statements to see what you are now actually comparing. Same applies to the other working example. : print 'Value row['EMAIL'] is: %s' % row['EMAIL'] print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL'] > ? ? ? if row['EMAIL'] == line['BVADDREMAIL']: Here you are testing if the value of row['EMAIL'] is exactly the same as line['BVADDREMAIL']: which is not the case so the test returns False and the below print statement is not executed. > ? ? ? ? ? print line['NAME'], row['COMPANY'] > > # but this does work: > for row in sitelist: > ? for line in bvreaderone: > ? ? ? if row['EMAIL'] in line['BVADDREMAIL']: Here you test if the value row['E_MAIL'] is part of line['BVADDREMAIL']:which is True. > ? ? ? ? ? print line['NAME'], row['COMPANY'] Someone did a way better job writing this down some time a go but can't find the post online. I hope you see now what the difference is between the 2. Greets Sander From eduardo.susan at gmail.com Fri Jul 31 01:56:21 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 30 Jul 2009 17:56:21 -0600 Subject: [Tutor] Problems understanding control flow In-Reply-To: References: <9356b9f30907301447v25fb5232i1c2f7d4a6172e241@mail.gmail.com> Message-ID: <9356b9f30907301656r1772acfen37fbc2f3decd8dae@mail.gmail.com> On Thu, Jul 30, 2009 at 4:49 PM, Sander Sweers wrote: > 2009/7/30 Eduardo Vieira : > > With == you are testing if the 2 values are exactly the same. So 'one' > == 'one' will return True but 'one; == 'one two' will return False. > > With in you test if the value is part of a another value. So using the > same value as above 'one' in 'one' will return True but 'one' in 'one > two' will also return True as 'one' is part of the second string. > > The same logic applies to lists and dicts. 'one' == ['one', 'two'] > will return False as the the 2 values are not exactly the same but > 'one' in ['one', 'two'] will return True. > >> # this does not work: >> for row in sitelist: >> ? for line in bvreaderone: > > If you are getting unexpected results add in print statements to see > what is the data that you are working with. I would add the below 2 > print statements to see what you are now actually comparing. Same > applies to the other working example. > : > ? ?print 'Value row['EMAIL'] is: %s' % row['EMAIL'] > ? ?print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL'] > >> ? ? ? if row['EMAIL'] == line['BVADDREMAIL']: > > Here you are testing if the value of row['EMAIL'] is exactly the same > as line['BVADDREMAIL']: which is not the case so the test returns > False and the below print statement is not executed. > >> ? ? ? ? ? print line['NAME'], row['COMPANY'] >> >> # but this does work: >> for row in sitelist: >> ? for line in bvreaderone: >> ? ? ? if row['EMAIL'] in line['BVADDREMAIL']: > > Here you test if the value row['E_MAIL'] is part of > line['BVADDREMAIL']:which is True. > >> ? ? ? ? ? print line['NAME'], row['COMPANY'] > > Someone did a way better job writing this down some time a go but > can't find the post online. I hope you see now what the difference is > between the 2. Thanks for pointing out this, Sander. Yes, a print statement revealed the right after commas... In this case I should enable the option from the csv module to ignore such white spaces. Eduardo From eduardo.susan at gmail.com Fri Jul 31 01:57:41 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Thu, 30 Jul 2009 17:57:41 -0600 Subject: [Tutor] Problems understanding control flow In-Reply-To: <9356b9f30907301656r1772acfen37fbc2f3decd8dae@mail.gmail.com> References: <9356b9f30907301447v25fb5232i1c2f7d4a6172e241@mail.gmail.com> <9356b9f30907301656r1772acfen37fbc2f3decd8dae@mail.gmail.com> Message-ID: <9356b9f30907301657n1ce70896g5b1170dad08f6047@mail.gmail.com> On Thu, Jul 30, 2009 at 5:56 PM, Eduardo Vieira wrote: > On Thu, Jul 30, 2009 at 4:49 PM, Sander Sweers wrote: >> 2009/7/30 Eduardo Vieira : >> >> With == you are testing if the 2 values are exactly the same. So 'one' >> == 'one' will return True but 'one; == 'one two' will return False. >> >> With in you test if the value is part of a another value. So using the >> same value as above 'one' in 'one' will return True but 'one' in 'one >> two' will also return True as 'one' is part of the second string. >> >> The same logic applies to lists and dicts. 'one' == ['one', 'two'] >> will return False as the the 2 values are not exactly the same but >> 'one' in ['one', 'two'] will return True. >> >>> # this does not work: >>> for row in sitelist: >>> ? for line in bvreaderone: >> >> If you are getting unexpected results add in print statements to see >> what is the data that you are working with. I would add the below 2 >> print statements to see what you are now actually comparing. Same >> applies to the other working example. >> : >> ? ?print 'Value row['EMAIL'] is: %s' % row['EMAIL'] >> ? ?print 'Value of line['BVADDREMAIL'] is: %s' % line['BVADDREMAIL'] >> >>> ? ? ? if row['EMAIL'] == line['BVADDREMAIL']: >> >> Here you are testing if the value of row['EMAIL'] is exactly the same >> as line['BVADDREMAIL']: which is not the case so the test returns >> False and the below print statement is not executed. >> >>> ? ? ? ? ? print line['NAME'], row['COMPANY'] >>> >>> # but this does work: >>> for row in sitelist: >>> ? for line in bvreaderone: >>> ? ? ? if row['EMAIL'] in line['BVADDREMAIL']: >> >> Here you test if the value row['E_MAIL'] is part of >> line['BVADDREMAIL']:which is True. >> >>> ? ? ? ? ? print line['NAME'], row['COMPANY'] >> >> Someone did a way better job writing this down some time a go but >> can't find the post online. I hope you see now what the difference is >> between the 2. > Thanks for pointing out this, Sander. Yes, a print statement revealed > the right after commas... In this case I should enable the option from > the csv module to ignore such white spaces. > > Eduardo > I meant a print statement revealed the extra space right after commas... From davea at ieee.org Fri Jul 31 02:46:42 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 30 Jul 2009 20:46:42 -0400 Subject: [Tutor] Assigning each line of text to a separate variable In-Reply-To: <4A7201E3.10209@gmail.com> References: <4A71F25B.5030208@gmail.com> <1c2a2c590907301239g52622080v9a13a0ae7304fdc8@mail.gmail.com> <4A7201E3.10209@gmail.com> Message-ID: <4A723EF2.6070001@ieee.org> Marv Boyes wrote: >
I'm very > sorry; I should have been more explicit in what it is I'm working with. > > The response from the server consists of a pair of hashes and a list > of URLs for doing different things with the file the hashes represent. > So the full response is like this: > > file_hash > delete_hash > http://server.com/file_hash.ext > http://server.com/file_hashA.ext > http://server.com/file_hashB.ext > http://server.com/file_hashC.ext > http://server.com/delete/deletehash > > I'm hoping to assign each line of that response to a separate variable > so I can format the output on a case-by-case basis, e.g.: > > direct_link = > print "Direct link to file: %s' % direct_link > > -or- > > delete_file = > print "Delete the file: %s' % delete_file > > I've got seven lines worth of server response, their order is > significant, and I need to be able to present each value in an > arbitrary way. I won't necessarily be presenting these values to the > user in the same order they come in the server response. Some of the > values I'll need to use elsewhere in the script to do other things, > but it won't be necessary to present those values to the user. > > I'm not sure I'm even making sense to myself. > > Assuming the server response is in a single string, which consists of 7 strings separated by newlines. response = server_getdata(....) responseList = response.splitlines() file_hash, delete_hash, direct_link, other_link, other_link3, other_link4, delete_file = responseList DaveA From prasadaraon50 at gmail.com Fri Jul 31 06:29:54 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Fri, 31 Jul 2009 09:59:54 +0530 Subject: [Tutor] flag to call methods on objects? Message-ID: <9e3fac840907302129g76731d05s661441f3058972f1@mail.gmail.com> hello I removed the bugs.But still getting error report. >>import mcript Traceback (most recent call last): File "", line 1, in import mcript File "C:\Python26\mcript.py", line 78, in a.main() File "C:\Python26\mcript.py", line 58, in main nl=__compress(__digi(__lengthen(line.strip())))+'\n' NameError: global name '_Cripto__compress' is not defined There is no string '_Cripto__compress' any whare in the script. So I dont know what corrections Ineed to make in the script. I am giving my code below again again . #! usr/bin/env python import ast,random,os,zlib,string key=5 class Cripto(object): def __init__(self,afile): self.afile=afile def __digi(self,astring): y=[] for x in astring: y.append(ord(x)) y=str(y) return y def __undigi(self,astring): alist=ast.literal_eval(astring) y=[] for x in alist: y.append(chr(x)) astring=''.join(y) return astring def __gen_string(self): s='' nl=random.sample(string.ascii_letters,key) for x in nl:s+=x return s def __lengthen(self,astring): s=list(astring) ns='' for x in s: ns+=x ns+=gen_string() return ns def __shorten(self,astring): s=list(astring) ns='' for x in range(0,len(s),key+1): ns+=s[x] return ns def __compress(self,astring): astring=zlib.compress(astring) return astring def __decompress(self,astring): astring=zlib.decompress(astring) return astring def main(self): sorce=open(self.afile,'r') data=(sorce.readlines()) dest=open((os.path.split(self.afile)[0]+os.sep+'temp'),'w') if (data[0]).strip()=='flag1': ns='flag0\n' data=data[1:] for line in data: nl= __compress(__digi(__lengthen(line.strip())))+'\n' ns+=nl dest.write(ns) elif data[0].strip()=='flag0': ns='flag1\n' data=data[1:] for line in data: nl= __shorten((__undigi(__decompress(line.strip()))))+'\n' ns+=nl dest.write(ns) else:prind 'File does not begin with the flag' sorce.close() dest.close() os.remove(self.afile) os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) #======== a=Cripto('C:/pp.txt') a.main() <\code> -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Fri Jul 31 07:16:43 2009 From: srilyk at gmail.com (Wayne) Date: Fri, 31 Jul 2009 00:16:43 -0500 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <9e3fac840907302129g76731d05s661441f3058972f1@mail.gmail.com> References: <9e3fac840907302129g76731d05s661441f3058972f1@mail.gmail.com> Message-ID: <333efb450907302216u45fd1fdehceb6bfeb25b50d6e@mail.gmail.com> On Thu, Jul 30, 2009 at 11:29 PM, prasad rao wrote: > hello > I removed the bugs.But still getting error report. > > > >>import mcript > > Traceback (most recent call last): > File "", line 1, in > import mcript > File "C:\Python26\mcript.py", line 78, in > a.main() > File "C:\Python26\mcript.py", line 58, in main > That line tells you where the problem is > nl=__compress(__digi(__lengthen(line.strip())))+'\n' > That's the code that produced the error > NameError: global name '_Cripto__compress' is not defined > You're trying to call a method __compress which doesn't exist. self.__compress exists, but __compress doesn't. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Jul 31 12:26:55 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 31 Jul 2009 06:26:55 -0400 Subject: [Tutor] flag to call methods on objects? In-Reply-To: <9e3fac840907302129g76731d05s661441f3058972f1@mail.gmail.com> References: <9e3fac840907302129g76731d05s661441f3058972f1@mail.gmail.com> Message-ID: <4A72C6EF.4030506@ieee.org> prasad rao wrote: > hello > I removed the bugs.But still getting error report. > > > >>> import mcript >>> > > Traceback (most recent call last): > File "", line 1, in > import mcript > File "C:\Python26\mcript.py", line 78, in > a.main() > File "C:\Python26\mcript.py", line 58, in main > nl=__compress(__digi(__lengthen(line.strip())))+'\n' > NameError: global name '_Cripto__compress' is not defined > > There is no string '_Cripto__compress' any whare in the script. > > So I dont know what corrections Ineed to make in the script. > > I am giving my code below again again . > > > > #! usr/bin/env python > > import ast,random,os,zlib,string > key=5 > class Craipto(object): > def __init__(self,afile): > self.afile=afile > def __digi(self,astring): > y=[] > for x in astring: > y.append(ord(x)) > y=str(y) > > return y > def __undigi(self,astring): > > alist=ast.literal_eval(astring) > y=[] > for x in alist: > y.append(chr(x)) > astring=''.join(y) > return astring > def __gen_string(self): > s='' > nl=random.sample(string.ascii_letters,key) > for x in nl:s+=x > return s > > def __lengthen(self,astring): > s=list(astring) > ns='' > for x in s: > ns+=x > ns+=gen_string() > return ns > def __shorten(self,astring): > > s=list(astring) > ns='' > for x in range(0,len(s),key+1): > ns+=s[x] > return ns > def __compress(self,astring): > astring=zlib.compress(astring) > return astring > def __decompress(self,astring): > astring=zlib.decompress(astring) > return astring > def main(self): > sorce=open(self.afile,'r') > data=(sorce.readlines()) > dest=open((os.path.split(self.afile)[0]+os.sep+'temp'),'w') > if (data[0]).strip()=='flag1': > > ns='flag0\n' > data=data[1:] > for line in data: > nl= __compress(__digi(__lengthen(line.strip())))+'\n' > ns+=nl > dest.write(ns) > elif data[0].strip()=='flag0': > ns='flag1\n' > data=data[1:] > for line in data: > nl= __shorten((__undigi(__decompress(line.strip()))))+'\n' > ns+=nl > dest.write(ns) > else:prind 'File does not begin with the flag' > > sorce.close() > dest.close() > > os.remove(self.afile) > os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) > > > #======== > a=Cripto('C:/pp.txt') > a.main() > > <\code> > > I still see four problems. Your runtime error occurs because you omitted the "self" on the call to self.__compress(). In fact, you omit it nearly everywhere. Without it, Python will look for a global name, which doesn't exist. Second problem is that you spelled "print" as "prind" in your else clause. Third is that when you do detect that the file doesn't begin properly, you still truncate the file to nothing. The else clause should be roughly: else: print "File is malformed, no signature at beginning" sorce.close() dest.close() os.remove( the temp file ) return Fourth is that you're separating the "lines" of the encoded file with a newline character, but I suspect that zlib.compress makes no promises about avoiding that character(0a). If I'm right, you'll need another approach. Either escape the byte sequence in __compress(), or use a count instead of a separator. In either case, you'll need binary mode for that part of the file I/O, if you want to be able to run on Windows. There are a few other comments I could make about the code. First, why did you make it a class? Perhaps your last language was Java, which forces you into that particular paradigm? You never use self in any of the methods except for __init__() and main(). And once main() is finished, you now longer need the object. That should tell you that you could make them all regular functions, and pass the filename directly to main(). Next, why the double-underscore prefix on most of the methods? The only effect that has on execution is that the error message shows a "mangled" version of the function name. When it's a global, it mangles it with the module name (_Cripto__compress), and when it's a method, it uses the class name. DaveA From rdmoores at gmail.com Fri Jul 31 14:06:53 2009 From: rdmoores at gmail.com (Dick Moores) Date: Fri, 31 Jul 2009 05:06:53 -0700 Subject: [Tutor] How to use Python 2.6 with IDLE? In-Reply-To: References: <829301.66121.qm@web86707.mail.ird.yahoo.com> <4A6EC2D7.2080006@ieee.org> Message-ID: Finally, success! Thanks to help from the Ulipad list. Python is built on wxPython. I upgraded wxPython to v2.8. Then found that even with 2.8 I was getting an error saying that I didn't have the comtypes module. After downloading and installing comtypes I now have Ulipad's shell running 2.6.2 and also Ulipad running scripts within Ulipad written in 2.6.2. See , which shows the Ulipad's shell window on the left, executing correctly a bit of code using a new 2.6 feature, and also the "Messages" window showing the correct output of the script 26.py . I call Ulipad with a Win XP shortcut, . The contents of the "Target:" textbox is "E:\Python26\pythonw.exe E:\Programs\Ulipad3.7\Ulipad.pyw" (no quotes). Dick Moores From ldl08 at gmx.net Fri Jul 31 16:09:02 2009 From: ldl08 at gmx.net (David) Date: Fri, 31 Jul 2009 22:09:02 +0800 Subject: [Tutor] concerning help() function In-Reply-To: References: <4A6FEC57.10103@gmx.net> Message-ID: <4A72FAFE.70004@gmx.net> Thanks to you all -- good stuff, as always! David Alan Gauld wrote: >> help('operator') >> >> I figured this by trial and error, and I am keen to find out when the > > Oops, always try before posting! And don;t assume... > > I juast vdid and you are right, it does give help on an unimported > module! > > Sorry, how embarrassing! :-) > > Alan G > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From eduardo.susan at gmail.com Fri Jul 31 17:15:38 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 31 Jul 2009 09:15:38 -0600 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: References: <4A67FDB0.50502@gmx.net> Message-ID: <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> On Thu, Jul 23, 2009 at 1:24 PM, Che M wrote: > > >> Date: Thu, 23 Jul 2009 14:05:36 +0800 >> From: ldl08 at gmx.net >> To: Tutor at python.org >> Subject: [Tutor] mnemonics to better learn Python >> >> Dear List, >> >> in order to memorize which Python sequences are mutable or immutable, I >> focused on the SHAPE of the brackets that are associated with each type >> of sequence. >> >> For instance, a *list* is characterised by square brackets, []. >> My mnemonic device to memorize that lists are mutable is this: "the >> brackets have sharp edges, they could be trimmed, taking their edges off". >> >> The same thing happens with *dictionaries* (which, okay, are not >> sequences). Anyway, their brackets, {}, have sharp edges, hence they are >> mutable. >> >> *Tuples*, in turn, have perfectly 'round' brackets, (), and these >> brackets obviously can't be improved upon by taking anything off them. >> Hence: tuples are immutable. >> >> That leaves us with *strings*, which are also not mutable. Here we have >> no brackets, and this particular mnemonic device breaks down. >> >> What I am interested in is finding out whether you use similar >> techniques, and if so, which ones? How, for examples, do you make sense >> of all those special characters that make regular expressions powerful? >> Do you rely on rote learning, or do you employ some other technique? >> >> I reckon that if we could come up with some tips and techniques as to >> how to uncloud the thick information fog that any beginning programmer >> has to wade through, the very first steps in learning Python could be >> made more easy. >> >> What insights can you share? > Hello, would anybody have a good memorization technique for boolean results? Like when using 'or'/'and' what it returns when both are false, the last is false, etc? I find it so hard to remember that... Eduardo From alan.gauld at btinternet.com Fri Jul 31 18:09:48 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 31 Jul 2009 17:09:48 +0100 Subject: [Tutor] mnemonics to better learn Python References: <4A67FDB0.50502@gmx.net> <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote > Hello, would anybody have a good memorization technique for boolean > results? Like when using 'or'/'and' what it returns when both are > false, the last is false, etc? Hmm, I don't try to remember those, I just work it out based on the meaning. A and B is true only if both A and B are True A or B is true if either A or B is True. Thats it really, what's to remember? I guess for a non native English speaker it might be more difficult because you need to translate and/or into the native language? But I assume every language has an equivalent for both of those concepts? In hardware engineering its more complex because you have nand and nor gates to deal with too, but they don't apply in software - at least not directly. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.lummis at gmail.com Fri Jul 31 18:27:37 2009 From: robert.lummis at gmail.com (Robert Lummis) Date: Fri, 31 Jul 2009 12:27:37 -0400 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: References: <4A67FDB0.50502@gmx.net> <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> Message-ID: <71d330f00907310927s534f1030j40ebdaad3c970fd5@mail.gmail.com> Understand that "if A or B" is short for the phrase "if either A or B is true", or more fully "if A is true or B is true". When I add "is true" then the logic seems obvious to me without memorizing anything. Likewise, "if A and B" means "if A and B are both true", which is the same as "if A is true and B is true". On Fri, Jul 31, 2009 at 12:09 PM, Alan Gauld wrote: > > "Eduardo Vieira" wrote > >> Hello, would anybody have a good memorization technique for boolean >> results? Like when using 'or'/'and' what it returns when both are >> false, the last is false, etc? > > Hmm, I don't try to remember those, I just work it out based on the meaning. > A and B is true only if both A and B are True > A or B is true if either A or B is True. > > Thats it really, what's to remember? > > I guess for a non native English speaker it might be more difficult because > you need to translate and/or into the native language? > But I assume every language has an equivalent for both of those concepts? > > In hardware engineering its more complex because you have nand and nor gates > to deal with too, but they don't apply in software - at least not directly. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Robert Lummis From davea at ieee.org Fri Jul 31 19:51:30 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 31 Jul 2009 13:51:30 -0400 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> References: <4A67FDB0.50502@gmx.net> <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> Message-ID: <4A732F22.8090409@ieee.org> Eduardo Vieira wrote: > > > Hello, would anybody have a good memorization technique for boolean > results? Like when using 'or'/'and' what it returns when both are > false, the last is false, etc? > I find it so hard to remember that... > Eduardo > > I don't blame you for finding it hard to remember. The English language (and probably most others, but I wouldn't know) lets people abuse these meanings, but programming insists you get it right. If you think of 0 for False, and 1 for True, then or is plus a sum is nonzero if a is 1 or if b is 1 (or both) and is times a product is only nonzero if both a and b are 1 xor is minus a difference is zero only if a is the same as b (both True, or both False) In simple electrical circuitry, 'or' is switches in parallel, 'and' is switches in series. In programming terms, and is nested ifs, while or is two ifs at the same level, either of which does the same thing. def and(a, b): if a: if b: print "this is the and of the two" return True else: return False def or(a, b): if a: print "this is the or" return True if b: print "this is the or" return True return False DaveA From pine508 at hotmail.com Fri Jul 31 20:27:57 2009 From: pine508 at hotmail.com (Che M) Date: Fri, 31 Jul 2009 14:27:57 -0400 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: References: <4A67FDB0.50502@gmx.net> <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> Message-ID: > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Fri, 31 Jul 2009 17:09:48 +0100 > Subject: Re: [Tutor] mnemonics to better learn Python > > > "Eduardo Vieira" wrote > > > Hello, would anybody have a good memorization technique for boolean > > results? Like when using 'or'/'and' what it returns when both are > > false, the last is false, etc? > > Hmm, I don't try to remember those, I just work it out based on > the meaning. > > A and B is true only if both A and B are True > A or B is true if either A or B is True. > > Thats it really, what's to remember? I tend to agree, but since he asked for a mnemonic... What Python Needs to Return a Boolean AND: Both I demand! OR: One or more. So, if A and B are False: [think "Both I demand...are False") if A or B are False: [think "One or more...are False") if A and B are True: [think "Both I demand...are True") etc. Che _________________________________________________________________ Windows Live? SkyDrive?: Store, access, and share your photos. See how. http://windowslive.com/Online/SkyDrive?ocid=TXT_TAGLM_WL_CS_SD_photos_072009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Fri Jul 31 20:42:58 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 31 Jul 2009 12:42:58 -0600 Subject: [Tutor] mnemonics to better learn Python In-Reply-To: References: <4A67FDB0.50502@gmx.net> <9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> Message-ID: <9356b9f30907311142k3375c1a5t7702953014b4c5c6@mail.gmail.com> On Fri, Jul 31, 2009 at 12:27 PM, Che M wrote: > > >> To: tutor at python.org >> From: alan.gauld at btinternet.com >> Date: Fri, 31 Jul 2009 17:09:48 +0100 >> Subject: Re: [Tutor] mnemonics to better learn Python >> >> >> "Eduardo Vieira" wrote >> >> > Hello, would anybody have a good memorization technique for boolean >> > results? Like when using 'or'/'and' what it returns when both are >> > false, the last is false, etc? >> >> Hmm, I don't try to remember those, I just work it out based on >> the meaning. >> >> A and B is true only if both A and B are True >> A or B is true if either A or B is True. >> >> Thats it really, what's to remember? > > I tend to agree, but since he asked for a mnemonic... > > What Python Needs to Return a Boolean > AND:? Both I demand! > OR:??? One or more. > > So, > > if A and B are False: > ?[think "Both I demand...are False") > if A or B are False: > ?[think "One or more...are False") > if A and B are True: > ?[think "Both I demand...are True") > etc. > > Che > > > ________________________________ > Windows Live? SkyDrive?: Store, access, and share your photos. See how. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > It's not that it's so hard, but I still have to stop and think for a while... "humm, how's that?" Like in the IDLE 2 and 4 and 0 Result: 0 2 and 4 and 5 Result: 5 2 and 0 and 6 Result: 0 So, what I need to memorize is that with AND, if there's a false item, then that false is returned, otherwise the last one is returned With OR, the first one is returned if true, otherwise, the next "true" value is returned 2 or 3 or 0 Result: 2 2 or 0 or 3 Result: 2 0 or 2 or 3 Result: 2 0 or '' or 4 Result: 4 Do you see how this can demand a little more of brainwork? Eduardo From alan.gauld at btinternet.com Fri Jul 31 20:51:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 31 Jul 2009 19:51:10 +0100 Subject: [Tutor] mnemonics to better learn Python References: <4A67FDB0.50502@gmx.net><9356b9f30907310815r73b66b15h16fb539f71077088@mail.gmail.com> <9356b9f30907311142k3375c1a5t7702953014b4c5c6@mail.gmail.com> Message-ID: "Eduardo Vieira" wrote > Like in the IDLE > 2 and 4 and 0 > Result: 0 Ah! Now I see. Its the results of short-circuit evaluation you want a nmemonic for, not the and/or logic itself I agree thats much harder to figure out, you do kind of have to work through the tests until the first failure for and or the first success for or. It might be cute to have an aide d'memoire for that. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/
 Current:High:Low:Average:
Temperature: > > 73.6 °F > > > > 83.3 °F > > > > 64.2 °F > > > > 74.1 °F > >