From alan.gauld at btinternet.com Fri Feb 1 01:11:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Feb 2013 00:11:14 +0000 Subject: [Tutor] operator order In-Reply-To: References: Message-ID: On 31/01/13 18:36, heathen wrote: > why is this: > > >>> d = 2 > >>> d *= 3 + 4 > >>> d > 14 > > not this: > >>> d > 10 Others have answered but I'll add my two cents variation... d *= 3+4 works like d *= X -> d = d * X so what is X? Is it the 3 or the 3+4. Let's put some parentheses around things to make it unambiguous: where X=(3+4) (d = d * (3+4)) -> 14 that all works OK where X = 3 ((d = d * 3) + 4) which is a syntax error since assignment doesn't return a value in Python... So it has to be X = (3+4) to make any kind of sense. In these cases you have to think the way the computer thinks. How is Python going to interpret it? In the second case it can't. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From D.Wilder at F5.com Fri Feb 1 03:43:54 2013 From: D.Wilder at F5.com (Dave Wilder) Date: Fri, 1 Feb 2013 02:43:54 +0000 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E Message-ID: Hello, In a script I am writing, I would like to be able to accept the PAGE DOWN key as an input as well as the arrow keys. Is that possible w/ Python (I am using python 2.7.3 and Linux OS)? If so, could someone point me to documentation on how to do that? I have done things like this before in python. For example, I used the following to send the character. send (chr(27)) However, I have not been able to find the ascii code equivalent to use for PAGE DOWN and the up/down arrow keys. I'm not even sure this is even a python question. Thanks, Dave From davea at davea.name Fri Feb 1 03:55:53 2013 From: davea at davea.name (Dave Angel) Date: Thu, 31 Jan 2013 21:55:53 -0500 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: References: Message-ID: <510B2EB9.1090903@davea.name> On 01/31/2013 09:43 PM, Dave Wilder wrote: > Hello, > > In a script I am writing, I would like to be able to accept the PAGE DOWN key as an input as well as the arrow keys. > > Is that possible w/ Python (I am using python 2.7.3 and Linux OS)? If so, could someone point me to documentation on how to do that? > > I have done things like this before in python. For example, I used the following to send the character. > send (chr(27)) > > However, I have not been able to find the ascii code equivalent to use for PAGE DOWN and the up/down arrow keys. > > I'm not even sure this is even a python question. > So how are you taking this input in? If you're writing a terminal application, using raw_input(), it would be very difficult, as you'd probably have to modify the readline function. Perhaps you're using some GUI. Please tell us which one. -- DaveA From D.Wilder at F5.com Fri Feb 1 04:19:39 2013 From: D.Wilder at F5.com (Dave Wilder) Date: Fri, 1 Feb 2013 03:19:39 +0000 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: <510B2EB9.1090903@davea.name> References: <510B2EB9.1090903@davea.name> Message-ID: >> On 01/31/2013 09:43 PM, Dave Wilder wrote: >> Hello, >> >> In a script I am writing, I would like to be able to accept the PAGE DOWN key as an input as well as the arrow keys. >> >> Is that possible w/ Python (I am using python 2.7.3 and Linux OS)? If so, could someone point me to documentation on how to do that? >> >> I have done things like this before in python. For example, I used the following to send the character. >> send (chr(27)) >> >> However, I have not been able to find the ascii code equivalent to use for PAGE DOWN and the up/down arrow keys. >> >> I'm not even sure this is even a python question. >> > So how are you taking this input in? If you're writing a terminal application, using raw_input(), it would be very difficult, as you'd probably have to modify the readline function. > Perhaps you're using some GUI. Please tell us which one. >- DaveA I am using a terminal application and an application called pexpect (instead of raw_input) where I send something to the console and then look for a result, such as or UP/DOWN arrows. I'm not sure if pexpect is standard Python application. I thought I recalled someone on this list saying it wasn't. Dave From eryksun at gmail.com Fri Feb 1 04:51:34 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 31 Jan 2013 22:51:34 -0500 Subject: [Tutor] operator order In-Reply-To: References: Message-ID: On Thu, Jan 31, 2013 at 5:53 PM, Hugo Arts wrote: > >>>> a = ([], []) >>>> a[0] += [1] > TypeError: 'tuple' object does not support item assignment >>>> a > ([1], []) Yep, storing the result fails for a read-only subscript or attribute (e.g. a property without fset), but only after the in-place op executes. Solution: don't do that. ;) From davea at davea.name Fri Feb 1 04:55:23 2013 From: davea at davea.name (Dave Angel) Date: Thu, 31 Jan 2013 22:55:23 -0500 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: References: <510B2EB9.1090903@davea.name> Message-ID: <510B3CAB.3050702@davea.name> On 01/31/2013 10:19 PM, Dave Wilder wrote: > > >>> On 01/31/2013 09:43 PM, Dave Wilder wrote: >>> Hello, >>> >>> In a script I am writing, I would like to be able to accept the PAGE DOWN key as an input as well as the arrow keys. >>> >>> Is that possible w/ Python (I am using python 2.7.3 and Linux OS)? If so, could someone point me to documentation on how to do that? >>> >>> I have done things like this before in python. For example, I used the following to send the character. >>> send (chr(27)) >>> >>> However, I have not been able to find the ascii code equivalent to use for PAGE DOWN and the up/down arrow keys. >>> >>> I'm not even sure this is even a python question. >>> > >> So how are you taking this input in? If you're writing a terminal application, using raw_input(), it would be very difficult, as you'd probably have to modify the readline function. >> Perhaps you're using some GUI. Please tell us which one. >> - DaveA > > I am using a terminal application and an application called pexpect (instead of raw_input) where I send something to the console and then look for a result, such as or > UP/DOWN arrows. I'm not sure if pexpect is standard Python application. I thought I recalled someone on this list saying it wasn't. > I don't use pexpect. But there is both a pexpect in the stdlib, and at least one external library of the same name. So it may be relevant which one you're using. But it's still quite confusing to me whether you're writing the controlled app or the controlling app. And your wording is confusing me still further, by referring to pexpect as an application. Maybe somebody else can make sense out of it. Or maybe you should start over, using names and verbal diagrams. Who is sending what to whom? Which programs are you stuck with, which ones are you writing? If you're writing all of it, why would you use pexpect? -- DaveA From alan.gauld at btinternet.com Fri Feb 1 09:34:25 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Feb 2013 08:34:25 +0000 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: References: <510B2EB9.1090903@davea.name> Message-ID: On 01/02/13 03:19, Dave Wilder wrote: >> So how are you taking this input in? > > I am using a terminal application and an application called pexpect OK, We need to get the terminology a lot more exact. I'm guessing that what you mean is that you have an application that somebody else wrote running in a terminal session and that you are writing a program to communicate with that application using the pexpect module. Is that correct? > (instead of raw_input) where I send something to the console > and then look for a result, When you say you send "something" to the console I'm guessing you mean you send a command string to the external application via pexpect and then read the response from the application coming back via pexpect? Is that correct? > such as or UP/DOWN arrows. If I got the previous guesses right then this is, I suspect, impossible. Pagedown and page up are terminal control characters that are not part of the output that would be sent to pexpect. pexpect reads the monitored session's stdin/stdout. There are some exceptional cases where you might see those characters but in most cases they will be swallowed by the app before pexpect ever sees them. OTOH if you mean you want to send the page up/down/arrows as the "something" then its a different game and you can do it. In that case you need todo what you did with ESC. The character set your external app uses will determine the codes you send. Assuming its the same set as your local setup you can use the following program(untested!) to read the codes from your keyboard (assuming you are on Windows): import msvcrt print "Hit space to end..." print while True: ky = msvcrt.getch() length = len(ky) if length != 0: if ky == " ": # check for quit event print ord(ky) raise SystemExit else: if ky == '\x00' or ky == '\xe0': # non ASCII ky = msvcrt.getch() # fetch second character print ord(ky), There is also a curses version for Linux/MacOS on my tutor topic page for event driven programming... > I'm not sure if pexpect is standard Python application. It's not an application it's a module. If you are using an app called pexpect then its not part of Python (although it may still be written in Python!) hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Fri Feb 1 13:38:03 2013 From: davea at davea.name (Dave Angel) Date: Fri, 01 Feb 2013 07:38:03 -0500 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: References: <510B2EB9.1090903@davea.name> Message-ID: <510BB72B.90403@davea.name> On 02/01/2013 03:34 AM, Alan Gauld wrote: > > > > OTOH if you mean you want to send the page up/down/arrows as the > "something" then its a different game and you can do it. In that case > you need todo what you did with ESC. The character set your external app > uses will determine the codes you send. Assuming its the same set as > your local setup you can use the following program(untested!) to read > the codes from your keyboard (assuming you are on Windows): > > import msvcrt > > print "Hit space to end..." > print > > while True: > ky = msvcrt.getch() The OP is running Python 2.73 on Linux. -- DaveA From D.Wilder at F5.com Fri Feb 1 16:35:22 2013 From: D.Wilder at F5.com (Dave Wilder) Date: Fri, 1 Feb 2013 15:35:22 +0000 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: <510BB72B.90403@davea.name> References: <510B2EB9.1090903@davea.name> <510BB72B.90403@davea.name> Message-ID: -----Original Message----- From: Tutor [mailto:tutor-bounces+d.wilder=f5.com at python.org] On Behalf Of Dave Angel Sent: Friday, February 01, 2013 7:38 AM To: tutor at python.org Subject: Re: [Tutor] Need to be able to accept Page Down or CTRL-E On 02/01/2013 03:34 AM, Alan Gauld wrote: >> >> >> >> OTOH if you mean you want to send the page up/down/arrows as the >> "something" then its a different game and you can do it. In that case >> you need todo what you did with ESC. The character set your external >> app uses will determine the codes you send. Assuming its the same set >> as your local setup you can use the following program(untested!) to >> read the codes from your keyboard (assuming you are on Windows): >> >> import msvcrt >> >> print "Hit space to end..." >> print >> >> while True: >> ky = msvcrt.getch() > The OP is running Python 2.73 on Linux. Okay, thanks Alan and Dave. I will look into this a little more and if need be, email the list again but taking Dave's advice and start over w/ a clearer problem statement. Dave -- DaveA _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From simonyan at fedoraproject.org Fri Feb 1 18:11:12 2013 From: simonyan at fedoraproject.org (Simon Yan) Date: Sat, 2 Feb 2013 01:11:12 +0800 Subject: [Tutor] First Python Test In-Reply-To: References: Message-ID: On Fri, Feb 1, 2013 at 9:18 PM, Dustin Guerri wrote: > Thanks for replying, Simon. I have no particular reason to use Xcode - > what would you recommend instead ? > I would recommend start off from a simple text editor that has basic syntax highlighting features. There are a number of options out there. TextMate is a good choice, a little pricy. VIM, if you are a terminal guy Even Python IDLE is a good choice you wanted to edit just a few simple .py files. I would suggest give it a look in the Mac App Store and you will find a few other good ones too. > > > *Dustin Guerri* > Mobile : (+ 34) 625 857 967 > dustinguerri at gmail.com > [image: LinkedIn] > > Contact me: [image: Google Talk] dustinguerri [image: Skype] dustinguerri > Get a signature like this. > CLICK > HERE. > > > > On 1 February 2013 13:05, Simon Yan wrote: > >> >> >> >> On Thu, Jan 17, 2013 at 6:47 AM, Dustin Guerri wrote: >> >>> Hi there, >>> >>> I'm trying to create a plain text file called "hello.py" with the >>> following text : >>> >>> print('hello world') >>> raw_input('Press any key to continue') >>> >>> I'd then like to run this program with Python Launcher on a Mac. >>> >>> I'd lke to use Xcode as my text editor. Once I have Xcode open, which >>> template should I use to input the text ? >>> >> I don't think there is a file type of Python that you can create from >> Xcode. >> Just curious, why would you want to use XCode as a Python editor? >> >> >>> >>> Thanks, >>> >>> *Dustin Guerri* >>> Mobile : (+ 34) 625 857 967 >>> dustinguerri at gmail.com | www.vimeo.com/dustinguerri/pop >>> [image: LinkedIn] >>> Contact me: [image: Google Talk] dustinguerri [image: Skype]dustinguerri >>> Get a signature like this. >>> CLICK >>> HERE. >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> >> >> -- >> Regards, >> YeeYaa (Simon Yan) >> >> http://simonyan.fedorapeople.org/ >> > > -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From etanes.rm at gmail.com Fri Feb 1 21:09:23 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 1 Feb 2013 12:09:23 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. Message-ID: Hey all how're things? I'm hoping for some guidance on a problem I'm trying to work through. I know this has been previously covered on this list but I'm hoping it won't bother you guys to run through it again. My basic program I'm attempting to create is like this.. I want to read from a large, very large file. I want to find a certain string if it finds the string I would like to select the first 15-20 characters pre and proceeding the string and then output that new string to a new file along with the line the string was located on within the file. It seems fairly straight forward but I'm wondering if y'all can point me to a direction that would help me accomplish this.. Firstly I know I can read a file and search for the string with (a portion of this code was found on stackoverflow and is not mine and some of it is my own) with open('largeFile', 'r') as inF: for line in inF: myString = "The String" if 'myString' in line: f = open(thenewfile', 'w') f.write(myString) f.close() I guess what I'm looking for then is tips on A)My stated goal of also writing the 15-20 characters before and after myString to the new file and B)finding the line number and writing that to the file as well. Any information you can give me or pointers would be awesome, thanks in advance. I'm on Ubuntu 12.10 running LXDE and working with Python 2.7 Scott From pacificmorrowind at gmail.com Fri Feb 1 21:31:07 2013 From: pacificmorrowind at gmail.com (Nick W) Date: Fri, 1 Feb 2013 12:31:07 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: Message-ID: quite easy to do; just use enumerate - as so: myString = "The String" with open('largeFile', 'r') as inF: for index, line in enumerate(inF): #myString = "The String" ##Not here because otherwise this gets run for every single line of the large file (which is nasty waste of resources) if 'myString' in line: with open(thenewfile', 'w') as f: f.write("Line #%d has string: %s" (index, line)) That will print the whole line into the new file, If you only want the characters before that use find and take a slice of the line instead. HTH Nick On Fri, Feb 1, 2013 at 12:09 PM, Scurvy Scott wrote: > Hey all how're things? > > I'm hoping for some guidance on a problem I'm trying to work through. > I know this has been previously covered on this list but I'm hoping it > won't bother you guys to run through it again. > > My basic program I'm attempting to create is like this.. > > I want to read from a large, very large file. > I want to find a certain string > if it finds the string I would like to select the first 15-20 > characters pre and proceeding the string and then output that new > string to a new file along with the line the string was located on > within the file. > > It seems fairly straight forward but I'm wondering if y'all can point > me to a direction that would help me accomplish this.. > > Firstly I know I can read a file and search for the string with (a > portion of this code was found on stackoverflow and is not mine and > some of it is my own) > > with open('largeFile', 'r') as inF: > for line in inF: > myString = "The String" > if 'myString' in line: > f = open(thenewfile', 'w') > f.write(myString) > f.close() > > I guess what I'm looking for then is tips on A)My stated goal of also > writing the 15-20 characters before and after myString to the new file > and > B)finding the line number and writing that to the file as well. > > Any information you can give me or pointers would be awesome, thanks in > advance. > > I'm on Ubuntu 12.10 running LXDE and working with Python 2.7 > > Scott > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Feb 1 21:36:43 2013 From: davea at davea.name (Dave Angel) Date: Fri, 01 Feb 2013 15:36:43 -0500 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: Message-ID: <510C275B.7060200@davea.name> On 02/01/2013 03:09 PM, Scurvy Scott wrote: > Hey all how're things? > > I'm hoping for some guidance on a problem I'm trying to work through. > I know this has been previously covered on this list but I'm hoping it > won't bother you guys to run through it again. > > My basic program I'm attempting to create is like this.. > > I want to read from a large, very large file. > I want to find a certain string > if it finds the string I would like to select the first 15-20 > characters pre and proceeding the string and then output that new > string to a new file along with the line the string was located on > within the file. Why not just use grep ? > > It seems fairly straight forward but I'm wondering if y'all can point > me to a direction that would help me accomplish this.. > > Firstly I know I can read a file and search for the string with (a > portion of this code was found on stackoverflow and is not mine and > some of it is my own) > First, you probably want to do something to quit when you get your first match. If you do want to continue finding matches, then you'd have to change the location of that open() on the newfile. Currently, it'll throw out any earlier contents, and just write the match. The linenum is easy, using enumerate. > with open('largeFile', 'r') as inF: > for line in inF: for linenum, line in enumerate(inF): > myString = "The String" This should be moved to a location before the loop; it's a waste reassigning it every time through the loop. > if 'myString' in line: > f = open(thenewfile', 'w') > f.write(myString) > f.close() break #quit upon first match > > I guess what I'm looking for then is tips on A)My stated goal of also > writing the 15-20 characters before and after myString to the new file > and > B)finding the line number and writing that to the file as well. > > Any information you can give me or pointers would be awesome, thanks in advance. > > I'm on Ubuntu 12.10 running LXDE and working with Python 2.7 > About giving the 15 characters before and after the match: Is it sufficient to truncate that spec at the line boundaries? What I mean is that if the match occurs at column 10, do you really need the last 5 characters of the previous line? Likewise, if it occurs near the end of the line, do you need some from the next line(s) ? If you never need to show more than the current line, then you can parse the line (write a separate function). If you have to go 15 characters earlier in the file, then consider using file.seek http://docs.python.org/2/library/stdtypes.html?highlight=seek#file.seek The catch to that is that it messes up the position in the file, so if you do want multiple matches, you'll need to use file.tell to save and restore the location to continue reading lines. Lots of other options, but it all depends on what you REALLY want. -- DaveA From etanes.rm at gmail.com Fri Feb 1 22:03:53 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 1 Feb 2013 13:03:53 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: <510C275B.7060200@davea.name> References: <510C275B.7060200@davea.name> Message-ID: > > Why not just use grep ? > Honestly this seemed like a good excuse to write some code and learn some stuff, secondly, it honestly just didn't dawn on me. Also, the code y'all both showed me was exactly what I was looking for and I'm planning on using Nicks code as a template to improve upon. As always, thank you guys a lot, it usually only takes a couple of emails from y'all to get my brain working correctly. Be safe, Scott From etanes.rm at gmail.com Fri Feb 1 22:24:31 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 1 Feb 2013 13:24:31 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> Message-ID: One last question on this topic.. I'd like to call the files and the string form the command line like Python whatever.py STRINGTOSEARCH NEWFILE FILETOOPEN My understanding is that it would be accomplished as such import sys myString = sys.argv[1] filetoopen = sys.argv[2] newfile = sys.argv[3] ETC ETC CODE HERE Is this correct/pythonic? Is there a more recommended way? Am I retarded? Thanks again in advance, Scott From davea at davea.name Fri Feb 1 23:22:49 2013 From: davea at davea.name (Dave Angel) Date: Fri, 01 Feb 2013 17:22:49 -0500 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> Message-ID: <510C4039.901@davea.name> On 02/01/2013 04:24 PM, Scurvy Scott wrote: > One last question on this topic.. > > I'd like to call the files and the string form the command line like > > Python whatever.py STRINGTOSEARCH NEWFILE FILETOOPEN > > My understanding is that it would be accomplished as such > > import sys > > myString = sys.argv[1] > filetoopen = sys.argv[2] > newfile = sys.argv[3] Notice that you have 2 and 3 reversed from your description above. Neither one is wrong, but you have to pick one of them. If it were my utility, I'd not specify any outfile on the commandline, but use redirection as is normal in Linux/Unix/Windows. In other words, just use print as your output, and don't have an argument for the output file. > > > ETC ETC CODE HERE > If it were my code, I'd be first checking the number of arguments ( len(sys.argv) ). If the number isn't exactly right, print a usage string and exit the program. If your commandline gets any more complex, consider using the argparse module. http://docs.python.org/2/library/argparse.html?highlight=argparse#argparse -- DaveA From simonyan at fedoraproject.org Fri Feb 1 13:05:01 2013 From: simonyan at fedoraproject.org (Simon Yan) Date: Fri, 1 Feb 2013 20:05:01 +0800 Subject: [Tutor] First Python Test In-Reply-To: References: Message-ID: On Thu, Jan 17, 2013 at 6:47 AM, Dustin Guerri wrote: > Hi there, > > I'm trying to create a plain text file called "hello.py" with the > following text : > > print('hello world') > raw_input('Press any key to continue') > > I'd then like to run this program with Python Launcher on a Mac. > > I'd lke to use Xcode as my text editor. Once I have Xcode open, which > template should I use to input the text ? > I don't think there is a file type of Python that you can create from Xcode. Just curious, why would you want to use XCode as a Python editor? > > Thanks, > > *Dustin Guerri* > Mobile : (+ 34) 625 857 967 > dustinguerri at gmail.com | www.vimeo.com/dustinguerri/pop > [image: LinkedIn] > Contact me: [image: Google Talk] dustinguerri [image: Skype] dustinguerri > Get a signature like this. > CLICK > HERE. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 2 00:15:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Feb 2013 23:15:58 +0000 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: <510BB72B.90403@davea.name> References: <510B2EB9.1090903@davea.name> <510BB72B.90403@davea.name> Message-ID: On 01/02/13 12:38, Dave Angel wrote: >> your local setup you can use the following program(untested!) to read >> the codes from your keyboard (assuming you are on Windows): >> >> import msvcrt >> > > The OP is running Python 2.73 on Linux. OK, I didn't notice that. In that case the Linux variant on my tutor page will work for him. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Feb 2 00:24:49 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 02 Feb 2013 10:24:49 +1100 Subject: [Tutor] Need to be able to accept Page Down or CTRL-E In-Reply-To: <510BB72B.90403@davea.name> References: <510B2EB9.1090903@davea.name> <510BB72B.90403@davea.name> Message-ID: <510C4EC1.1020500@pearwood.info> On 01/02/13 23:38, Dave Angel wrote: > On 02/01/2013 03:34 AM, Alan Gauld wrote: >> >> >> >> OTOH if you mean you want to send the page up/down/arrows as the >> "something" then its a different game and you can do it. In that case >> you need todo what you did with ESC. The character set your external app >> uses will determine the codes you send. Assuming its the same set as >> your local setup you can use the following program(untested!) to read >> the codes from your keyboard (assuming you are on Windows): >> >> import msvcrt >> >> print "Hit space to end..." >> print >> >> while True: >> ky = msvcrt.getch() > > The OP is running Python 2.73 on Linux. You can use getch under Linux. http://code.activestate.com/recipes/577977/ Using that recipe, I see that PageUp sends the following four bytes: '\x1b[5~' PageDown also sends four bytes: '\x1b[6~' and Ctrl-E sends a single byte: '\x05' -- Steven From alan.gauld at btinternet.com Sat Feb 2 00:26:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Feb 2013 23:26:28 +0000 Subject: [Tutor] First Python Test In-Reply-To: References: Message-ID: On 01/02/13 12:05, Simon Yan wrote: > I'd lke to use Xcode as my text editor. Once I have Xcode open, > which template should I use to input the text ? > I don;t know about templates but there are instructions on the MacPython pages that tell you how to set up XCode. I used it for some experiments in Cocoa programming on my Mac. But it was a while ago. > Just curious, why would you want to use XCode as a Python editor? Lots of possible reasons: 1) He is already using XCode for other Mac projects and wants a familiar tool 2) XCode is a better editor than IDLE 3) He wants to do Cocoa (Mac GUI) programming and XCode provides integration with the MacOS GUI creator 4) He wants to have a mixed language program using Objective C and Python in the same project. Any and all are perfectly reasonable and valid. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Feb 2 02:00:09 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 02 Feb 2013 12:00:09 +1100 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> Message-ID: <510C6519.5040502@pearwood.info> On 02/02/13 08:24, Scurvy Scott wrote: > One last question on this topic.. > > I'd like to call the files and the string form the command line like > > Python whatever.py STRINGTOSEARCH NEWFILE FILETOOPEN > > My understanding is that it would be accomplished as such > > import sys > > myString = sys.argv[1] > filetoopen = sys.argv[2] > newfile = sys.argv[3] > > > ETC ETC CODE HERE > > Is this correct/pythonic? Is there a more recommended way? Am I retarded? Best practice is to check if your program is being run as a script before doing anything. That way you can still import the module for testing or similar: def main(mystring, infile, outfile): # do stuff here if __name__ == '__main__': # Running as a script. import sys mystring = sys.argv[1] infile = sys.argv[2] outfile = sys.argv[3] main(mystring, infile, outfile) Best practice for scripts (not just Python scripts, but *any* script) is to provide help when asked. Insert this after the "import sys" line, before you start processing: if '-h' in sys.argv or '--help' in sys.argv: print(help_text) sys.exit() If your argument processing is more complicated that above, you should use one of the three argument parsing modules that Python provides: http://docs.python.org/2/library/getopt.html http://docs.python.org/2/library/optparse.html (deprecated -- do not use this for new code) http://docs.python.org/2/library/argparse.html getopt is (in my opinion) the simplest to get started, but the weakest. There are also third-party argument parsers that you could use. Here's one which I have never used but am intrigued by: http://docopt.org/ -- Steven From jacklittlemc at yahoo.com Sat Feb 2 02:47:46 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Fri, 1 Feb 2013 17:47:46 -0800 (PST) Subject: [Tutor] Help Message-ID: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> I get this error Traceback (most recent call last): ? File "C:\Users\Jack\Desktop\python\g.py", line 56, in ? ? path1pt1() NameError: name 'path1pt1' is not defined With this amount of code: def simpstart(): ? global ammo1 ? global ammo2 ? global ammo3 ? global health ? global tech_parts ? global exp ? global radio_parts ? ammo1=10 ? ammo2=0 ? ammo3=0 ? health=100 ? tech_parts=0 ? exp=0 ? radio_parts=0 print "You awake in a haze. A crate,a door and a radio." g1 = raw_input("Which do you choose ?") if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": ? ? ? ? print "There is a pack of ammo,some food and an odd microchip" ? ? ? ? ammo1=ammo1 + 6 ? ? ? ? health=health + 10 ? ? ? ? tech_parts=tech_parts + 1 elif g1 =="DOOR" or g1 == "Door" or g1 == "door": ? ? ? print "You are outside" elif g1 == "RADIO" or g1 == "Radio" or g1 == "radio": ? ? ? print "It's only a few parts" ? ? ? radio_parts=radio_parts+3 g2 = raw_input("So this is NYC.Ten years after.There are a few streets.Go west or north ?") if g2 == "WEST" or g2 == "West" or g2 == "west": ? ? ? path2_pt1() elif g2 == "NORTH" or g2 == "North" or g2 == "north": ? ? ? path1pt1() ? ? ?? def path1pt1(): ? ? print "This is where it all started. Freedom Tower. A biotech firm called Aesthos Biotechnology. Based here." ? ? print "I worked there." -------------- next part -------------- An HTML attachment was scrubbed... URL: From btiqui at gmail.com Sat Feb 2 03:01:15 2013 From: btiqui at gmail.com (Brandon) Date: Fri, 1 Feb 2013 18:01:15 -0800 Subject: [Tutor] Help In-Reply-To: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: You get the error because you call path1pt1() before it is defined. Define your path1pt1() method at the top of your code before simpstart(). Brandon On Fri, Feb 1, 2013 at 5:47 PM, Jack Little wrote: > I get this error > > Traceback (most recent call last): > File "C:\Users\Jack\Desktop\python\g.py", line 56, in > path1pt1() > NameError: name 'path1pt1' is not defined > > With this amount of code: > > > def simpstart(): > global ammo1 > global ammo2 > global ammo3 > global health > global tech_parts > global exp > global radio_parts > ammo1=10 > ammo2=0 > ammo3=0 > health=100 > tech_parts=0 > exp=0 > radio_parts=0 > print "You awake in a haze. A crate,a door and a radio." > g1 = raw_input("Which do you choose ") > if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": > print "There is a pack of ammo,some food and an odd microchip" > ammo1=ammo1 + 6 > health=health + 10 > tech_parts=tech_parts + 1 > elif g1 =="DOOR" or g1 == "Door" or g1 == "door": > print "You are outside" > elif g1 == "RADIO" or g1 == "Radio" or g1 == "radio": > print "It's only a few parts" > radio_parts=radio_parts+3 > g2 = raw_input("So this is NYC.Ten years after.There are a few streets.Go > west or north ") > if g2 == "WEST" or g2 == "West" or g2 == "west": > path2_pt1() > elif g2 == "NORTH" or g2 == "North" or g2 == "north": > path1pt1() > > > def path1pt1(): > print "This is where it all started. Freedom Tower. A biotech firm > called Aesthos Biotechnology. Based here." > print "I worked there." > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sat Feb 2 03:07:36 2013 From: davea at davea.name (Dave Angel) Date: Fri, 01 Feb 2013 21:07:36 -0500 Subject: [Tutor] Help In-Reply-To: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: <510C74E8.6050508@davea.name> On 02/01/2013 08:47 PM, Jack Little wrote: > I get this error > > Traceback (most recent call last): > File "C:\Users\Jack\Desktop\python\g.py", line 56, in > path1pt1() > NameError: name 'path1pt1' is not defined > > With this amount of code: > > > def simpstart(): > global ammo1 > global ammo2 > global ammo3 > global health > global tech_parts > global exp > global radio_parts > ammo1=10 > ammo2=0 > ammo3=0 > health=100 > tech_parts=0 > exp=0 > radio_parts=0 You've stopped defining that function, and now are doing top-level code This following stuff belongs in a function, probably called main() > print "You awake in a haze. A crate,a door and a radio." > g1 = raw_input("Which do you choose ") > if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": > print "There is a pack of ammo,some food and an odd microchip" > ammo1=ammo1 + 6 > health=health + 10 > tech_parts=tech_parts + 1 > elif g1 =="DOOR" or g1 == "Door" or g1 == "door": > print "You are outside" > elif g1 == "RADIO" or g1 == "Radio" or g1 == "radio": > print "It's only a few parts" > radio_parts=radio_parts+3 > g2 = raw_input("So this is NYC.Ten years after.There are a few streets.Go west or north ") > if g2 == "WEST" or g2 == "West" or g2 == "west": > path2_pt1() > elif g2 == "NORTH" or g2 == "North" or g2 == "north": > path1pt1() Now, in top-level code, you're trying to call a function that hasn't been defined yet. If you want to have complete freedom of order when you define your functions, don't put any top-level code except a tiny block at the end of the script. No function may be called before it has been defined. But inside a function, the call won't be made till the function is called. So if the only calls happen at the end of the script, there'll never be such a problem. > > > def path1pt1(): > print "This is where it all started. Freedom Tower. A biotech firm called Aesthos Biotechnology. Based here." > print "I worked there." > This should be the only non-trivial top-level code, and it should be at the end of the script. if __name__ == "__main__": simpstart() main() -- DaveA From etanes.rm at gmail.com Sat Feb 2 05:31:49 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 1 Feb 2013 20:31:49 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: <510C6519.5040502@pearwood.info> References: <510C275B.7060200@davea.name> <510C6519.5040502@pearwood.info> Message-ID: > Best practice is to check if your program is being run as a script before > doing anything. That way you can still import the module for testing or > similar: > > > def main(mystring, infile, outfile): > # do stuff here > > > if __name__ == '__main__': > # Running as a script. > import sys > mystring = sys.argv[1] > infile = sys.argv[2] > outfile = sys.argv[3] > main(mystring, infile, outfile) > > > > Best practice for scripts (not just Python scripts, but *any* script) is to > provide help when asked. Insert this after the "import sys" line, before you > start processing: > > if '-h' in sys.argv or '--help' in sys.argv: > print(help_text) > sys.exit() > > > > If your argument processing is more complicated that above, you should use > one of the three argument parsing modules that Python provides: > > http://docs.python.org/2/library/getopt.html > http://docs.python.org/2/library/optparse.html (deprecated -- do not use > this for new code) > http://docs.python.org/2/library/argparse.html > > > getopt is (in my opinion) the simplest to get started, but the weakest. > > There are also third-party argument parsers that you could use. Here's one > which I have never used but am intrigued by: > > http://docopt.org/ > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Steve- thanks a lot for showing me the if __name__ = main part I've often wondered how it was used and it didn't make sense until I saw it in my own code if that makes any sense. Also appreciate the help on the "instructional" side of things. One question related to the instruction aspect- does this make sense to you? If len(sys.argv) == 0: print "usage: etc etc etc" Nick, Dave, and Steve, again, you guys are awesome. Thanks for all your help. Scott From msirenef at lightbird.net Sat Feb 2 05:54:34 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 01 Feb 2013 23:54:34 -0500 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> <510C6519.5040502@pearwood.info> Message-ID: <510C9C0A.8040705@lightbird.net> On 02/01/2013 11:31 PM, Scurvy Scott wrote: > > Steve- > thanks a lot for showing me the if __name__ = main part > I've often wondered how it was used and it didn't make sense until I > saw it in my own code if that makes any sense. > Also appreciate the help on the "instructional" side of things. > > One question related to the instruction aspect- does this make sense to you? > > If len(sys.argv) == 0: > print "usage: etc etc etc" If should not be capitalized; sys.argv always has the name of the script as the first item. So you need to do something like: if len(sys.argv) != 3: print "usage: ..." HTH! -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Emotion is primarily about nothing and much of it remains about nothing to the end. George Santayana From etanes.rm at gmail.com Sat Feb 2 05:57:41 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Fri, 1 Feb 2013 20:57:41 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> <510C6519.5040502@pearwood.info> Message-ID: And just for the records sake, this is what I've gotten and you guys should see obviously that you helped a lot and I learned a thing or two so I won't have to ask the same silly questions next time: def main(mystring, infile, outfile): with open('infile', 'r') as inF: for index, line in enumerate(inF): if myString in line: newfile.write("string %s found on line #%d" (line, index)) print "complete." if __name__ == '__main__': import sys newfile = open('outfile', 'w') help_text = "usage: python scanfile.py STRINGTOSEARCH IMPORTFILENAME OUTPUTFILENAME" if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) == 0: print (help_text) sys.exit() myString = sys.argv[1] infile = sys.argv[2] outfile = sys.argv[3] main(mystring, infile, outfile) Look right to you? Looks okay to me, except maybe the three ORs in the information line, is there a more pythonic way to accomplish that task? Scott On Fri, Feb 1, 2013 at 8:31 PM, Scurvy Scott wrote: >> Best practice is to check if your program is being run as a script before >> doing anything. That way you can still import the module for testing or >> similar: >> >> >> def main(mystring, infile, outfile): >> # do stuff here >> >> >> if __name__ == '__main__': >> # Running as a script. >> import sys >> mystring = sys.argv[1] >> infile = sys.argv[2] >> outfile = sys.argv[3] >> main(mystring, infile, outfile) >> >> >> >> Best practice for scripts (not just Python scripts, but *any* script) is to >> provide help when asked. Insert this after the "import sys" line, before you >> start processing: >> >> if '-h' in sys.argv or '--help' in sys.argv: >> print(help_text) >> sys.exit() >> >> >> >> If your argument processing is more complicated that above, you should use >> one of the three argument parsing modules that Python provides: >> >> http://docs.python.org/2/library/getopt.html >> http://docs.python.org/2/library/optparse.html (deprecated -- do not use >> this for new code) >> http://docs.python.org/2/library/argparse.html >> >> >> getopt is (in my opinion) the simplest to get started, but the weakest. >> >> There are also third-party argument parsers that you could use. Here's one >> which I have never used but am intrigued by: >> >> http://docopt.org/ >> >> >> >> -- >> Steven >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Steve- > thanks a lot for showing me the if __name__ = main part > I've often wondered how it was used and it didn't make sense until I > saw it in my own code if that makes any sense. > Also appreciate the help on the "instructional" side of things. > > One question related to the instruction aspect- does this make sense to you? > > If len(sys.argv) == 0: > print "usage: etc etc etc" > > > > Nick, Dave, and Steve, again, you guys are awesome. Thanks for all your help. > > Scott From steve at pearwood.info Sat Feb 2 08:54:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 02 Feb 2013 18:54:33 +1100 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> <510C6519.5040502@pearwood.info> Message-ID: <510CC639.2090200@pearwood.info> On 02/02/13 15:31, Scurvy Scott wrote: > One question related to the instruction aspect- does this make sense to you? > > If len(sys.argv) == 0: > print "usage: etc etc etc" Right idea, but not quite correct. sys.argv always includes at least one item, the name of the script being called. This is why you will often see code like this, to extract the actual arguments: argv = sys.argv[1:] # slice excluding the first item if len(argv) == 0: usage() else: main(argv) or similar. -- Steven From alan.gauld at btinternet.com Sat Feb 2 09:29:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Feb 2013 08:29:29 +0000 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> <510C6519.5040502@pearwood.info> Message-ID: On 02/02/13 04:57, Scurvy Scott wrote: It may just be an email thing but... > def main(mystring, infile, outfile): > with open('infile', 'r') as inF: > for index, line in enumerate(inF): > if myString in line: > newfile.write("string %s found on line #%d" (line, index)) > print "complete." The print should be inside the function not outside. And main is probably not the best name. You could call it printFoundString or somesuch... 'main' is usually used to collect all the program driver code that you currently have under the if name... test. The stuff you wouldn't ever use if importing as a module. Your way works fine too, a main is not obligatory. :-) > if __name__ == '__main__': > import sys > newfile = open('outfile', 'w') > help_text = "usage: python scanfile.py STRINGTOSEARCH > IMPORTFILENAME OUTPUTFILENAME" > if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) == 0: The last test should be == 1 since the program name will always be there. But in fact you need the string and file args too so it should really be: len(sys.argv) < 4 anything less than 4 args and your code breaks... > myString = sys.argv[1] > infile = sys.argv[2] > outfile = sys.argv[3] HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 2 09:35:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Feb 2013 08:35:01 +0000 Subject: [Tutor] Help In-Reply-To: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> References: <1359769666.32784.YahooMailNeo@web124501.mail.ne1.yahoo.com> Message-ID: On 02/02/13 01:47, Jack Little wrote: > def simpstart(): > global ammo1 > global ammo2 > global ammo3 > global health > global tech_parts > global exp > global radio_parts > ammo1=10 > ammo2=0 > ammo3=0 > health=100 > tech_parts=0 > exp=0 > radio_parts=0 This function is completely pointless, you might as well just define the variables at the top level. > print "You awake in a haze. A crate,a door and a radio." > g1 = raw_input("Which do you choose ") > if g1 == "CRATE" or g1 == "Crate" or g1 == "crate": ... > elif g1 =="DOOR" or g1 == "Door" or g1 == "door": > print "You are outside" > elif g1 == "RADIO" or g1 == "Radio" or g1 == "radio": ... > g2 = raw_input("So this is NYC.Ten years after.There are a few > streets.Go west or north ") > if g2 == "WEST" or g2 == "West" or g2 == "west": > path2_pt1() > elif g2 == "NORTH" or g2 == "North" or g2 == "north": > path1pt1() The block above is at top level so Python will execute it as it reads the file. And at this stage pathpt1 does not exist so it fails. You need to move this block into a function (maybe it was intended to be part of the one above but you messed up the indent?). Alternatively you need to move the definition of pathpt1 above this block. > def path1pt1(): > print "This is where it all started. Freedom Tower. A biotech firm > called Aesthos Biotechnology. Based here." > print "I worked there." HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jamie at kode5.net Sat Feb 2 10:31:18 2013 From: jamie at kode5.net (Jamie Griffin) Date: Sat, 2 Feb 2013 09:31:18 +0000 Subject: [Tutor] First Python Test In-Reply-To: References: Message-ID: <20130202093118.GB6079@kontrol.kode5.net> * Simon Yan [2013-02-02 01:11:12 +0800]: > I would recommend start off from a simple text editor that has basic syntax > highlighting features. There are a number of options out there. > TextMate is a good choice, a little pricy. > VIM, if you are a terminal guy > Even Python IDLE is a good choice you wanted to edit just a few simple .py > files. > > I would suggest give it a look in the Mac App Store and you will find a few > other good ones too. I believe the editor of choice on Mac OS X these days is BBEdit - again, a bit expensive. TextMate used to be good but there are better ones out there now. Personally, I prefer the commandline editors, vi or vim which is already installed on Mac OS X. I haven't used the Xcode editor before but if it's what you're comfortable with then it's probably best to stick with it. Primary Key: 4096R/1D31DC38 2011-12-03 Key Fingerprint: A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 From aurelien at cwb.io Sat Feb 2 10:54:51 2013 From: aurelien at cwb.io (=?utf-8?Q?Aur=C3=A9lien_DESBRI=C3=88RES?=) Date: Sat, 02 Feb 2013 10:54:51 +0100 Subject: [Tutor] First Python Test In-Reply-To: <20130202093118.GB6079@kontrol.kode5.net> (Jamie Griffin's message of "Sat, 2 Feb 2013 09:31:18 +0000") References: <20130202093118.GB6079@kontrol.kode5.net> Message-ID: <87ehgz82hg.fsf@pbot.home> hmm ... you should use GNU Emacs, it's Free in price and license! Extensible Text Editor with a cool Python-mode ;-) Jamie Griffin writes: > * Simon Yan [2013-02-02 01:11:12 +0800]: > >> I would recommend start off from a simple text editor that has basic syntax >> highlighting features. There are a number of options out there. >> TextMate is a good choice, a little pricy. >> VIM, if you are a terminal guy >> Even Python IDLE is a good choice you wanted to edit just a few simple .py >> files. >> >> I would suggest give it a look in the Mac App Store and you will find a few >> other good ones too. > > I believe the editor of choice on Mac OS X these days is BBEdit - > again, a bit expensive. TextMate used to be good but there are > better ones out there now. Personally, I prefer the commandline > editors, vi or vim which is already installed on Mac OS X. I haven't > used the Xcode editor before but if it's what you're comfortable > with then it's probably best to stick with it. > > > Primary Key: 4096R/1D31DC38 2011-12-03 > Key Fingerprint: A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Aur?lien DESBRI?RES Ride free! Ride GNU.ORG From sydney.shall at kcl.ac.uk Sat Feb 2 13:45:15 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sat, 2 Feb 2013 12:45:15 +0000 Subject: [Tutor] First Python Test In-Reply-To: References: Message-ID: <510D0A5B.4060809@kcl.ac.uk> Two free good text editors for the MAC are; 1. Komodo 2. Text Wrangler. hth Sydney On 01/02/2013 17:11, Simon Yan wrote: > > > > On Fri, Feb 1, 2013 at 9:18 PM, Dustin Guerri > wrote: > > Thanks for replying, Simon. I have no particular reason to use > Xcode - what would you recommend instead ? > > I would recommend start off from a simple text editor that has basic > syntax highlighting features. There are a number of options out there. > TextMate is a good choice, a little pricy. > VIM, if you are a terminal guy > Even Python IDLE is a good choice you wanted to edit just a few simple > .py files. > > I would suggest give it a look in the Mac App Store and you will find > a few other good ones too. > > > > *Dustin Guerri* > Mobile : (+ 34) 625 857 967 > dustinguerri at gmail.com > > LinkedIn > > > Contact me: Google Talk dustinguerri Skype dustinguerri > Get a signature like this. > > CLICK HERE. > > > > > On 1 February 2013 13:05, Simon Yan > wrote: > > > > > On Thu, Jan 17, 2013 at 6:47 AM, Dustin Guerri > > wrote: > > Hi there, > > I'm trying to create a plain text file called "hello.py" > with the following text : > > print('hello world') > raw_input('Press any key to continue') > > I'd then like to run this program with Python Launcher on > a Mac. > > I'd lke to use Xcode as my text editor. Once I have Xcode > open, which template should I use to input the text ? > > I don't think there is a file type of Python that you can > create from Xcode. > Just curious, why would you want to use XCode as a Python editor? > > > Thanks, > > *Dustin Guerri* > Mobile : (+ 34) 625 857 967 > > dustinguerri at gmail.com | > www.vimeo.com/dustinguerri/pop > > > LinkedIn > > Contact me: Google Talk dustinguerri Skype dustinguerri > Get a signature like this. > > CLICK HERE. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Regards, > YeeYaa (Simon Yan) > > http://simonyan.fedorapeople.org/ > > > > > > -- > Regards, > YeeYaa (Simon Yan) > > http://simonyan.fedorapeople.org/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From sydney.shall at kcl.ac.uk Sat Feb 2 13:53:26 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sat, 2 Feb 2013 12:53:26 +0000 Subject: [Tutor] First Python Test In-Reply-To: <20130202093118.GB6079@kontrol.kode5.net> References: <20130202093118.GB6079@kontrol.kode5.net> Message-ID: <510D0C46.3000600@kcl.ac.uk> Text Wrangler is a free, cut-down version of BB-Edit, I think. Sydney On 02/02/2013 09:31, Jamie Griffin wrote: > * Simon Yan [2013-02-02 01:11:12 +0800]: > >> I would recommend start off from a simple text editor that has basic syntax >> highlighting features. There are a number of options out there. >> TextMate is a good choice, a little pricy. >> VIM, if you are a terminal guy >> Even Python IDLE is a good choice you wanted to edit just a few simple .py >> files. >> >> I would suggest give it a look in the Mac App Store and you will find a few >> other good ones too. > I believe the editor of choice on Mac OS X these days is BBEdit - > again, a bit expensive. TextMate used to be good but there are > better ones out there now. Personally, I prefer the commandline > editors, vi or vim which is already installed on Mac OS X. I haven't > used the Xcode editor before but if it's what you're comfortable > with then it's probably best to stick with it. > > > Primary Key: 4096R/1D31DC38 2011-12-03 > Key Fingerprint: A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From sydney.shall at kcl.ac.uk Sat Feb 2 13:57:02 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sat, 2 Feb 2013 12:57:02 +0000 Subject: [Tutor] First Python Test In-Reply-To: <87ehgz82hg.fsf@pbot.home> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> Message-ID: <510D0D1E.9010903@kcl.ac.uk> Dear Aurelien, Would you please explain how one installs GNU Emacs on a MAC using OS X v10.6. I cannot find a binary package. The GNU site seems to me to have only source code packages. Mille fois merci. Sydney On 02/02/2013 09:54, Aur?lien DESBRI?RES wrote: > hmm ... you should use GNU Emacs, it's Free in price and license! > > Extensible Text Editor with a cool Python-mode ;-) > > Jamie Griffin writes: > >> * Simon Yan [2013-02-02 01:11:12 +0800]: >> >>> I would recommend start off from a simple text editor that has basic syntax >>> highlighting features. There are a number of options out there. >>> TextMate is a good choice, a little pricy. >>> VIM, if you are a terminal guy >>> Even Python IDLE is a good choice you wanted to edit just a few simple .py >>> files. >>> >>> I would suggest give it a look in the Mac App Store and you will find a few >>> other good ones too. >> I believe the editor of choice on Mac OS X these days is BBEdit - >> again, a bit expensive. TextMate used to be good but there are >> better ones out there now. Personally, I prefer the commandline >> editors, vi or vim which is already installed on Mac OS X. I haven't >> used the Xcode editor before but if it's what you're comfortable >> with then it's probably best to stick with it. >> >> >> Primary Key: 4096R/1D31DC38 2011-12-03 >> Key Fingerprint: A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From aurelien at cwb.io Sat Feb 2 14:23:24 2013 From: aurelien at cwb.io (=?utf-8?Q?Aur=C3=A9lien_DESBRI=C3=88RES?=) Date: Sat, 02 Feb 2013 14:23:24 +0100 Subject: [Tutor] First Python Test In-Reply-To: <510D0D1E.9010903@kcl.ac.uk> (Sydney Shall's message of "Sat, 2 Feb 2013 12:57:02 +0000") References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> Message-ID: <874nhu97eb.fsf@pbot.home> Join #emacs on irc.freenode.net and ask them. I do not bring any support for non free Operating System nor BrainWashing ones ;-) "Shall, Sydney" writes: > Dear Aurelien, > Would you please explain how one installs GNU Emacs on a MAC using OS > X v10.6. > I cannot find a binary package. The GNU site seems to me to have only > source code packages. > Mille fois merci. > Sydney > > > On 02/02/2013 09:54, Aur?lien DESBRI?RES wrote: >> hmm ... you should use GNU Emacs, it's Free in price and license! >> >> Extensible Text Editor with a cool Python-mode ;-) >> >> Jamie Griffin writes: >> >>> * Simon Yan [2013-02-02 01:11:12 +0800]: >>> >>>> I would recommend start off from a simple text editor that has basic syntax >>>> highlighting features. There are a number of options out there. >>>> TextMate is a good choice, a little pricy. >>>> VIM, if you are a terminal guy >>>> Even Python IDLE is a good choice you wanted to edit just a few simple .py >>>> files. >>>> >>>> I would suggest give it a look in the Mac App Store and you will find a few >>>> other good ones too. >>> I believe the editor of choice on Mac OS X these days is BBEdit - >>> again, a bit expensive. TextMate used to be good but there are >>> better ones out there now. Personally, I prefer the commandline >>> editors, vi or vim which is already installed on Mac OS X. I haven't >>> used the Xcode editor before but if it's what you're comfortable >>> with then it's probably best to stick with it. >>> >>> >>> Primary Key: 4096R/1D31DC38 2011-12-03 >>> Key Fingerprint: A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor -- Aur?lien DESBRI?RES Ride free! Ride GNU.ORG From pacificmorrowind at gmail.com Sat Feb 2 15:29:13 2013 From: pacificmorrowind at gmail.com (Nick W) Date: Sat, 2 Feb 2013 06:29:13 -0800 Subject: [Tutor] Read from large text file, parse, find string, print string + line number to second text file. In-Reply-To: References: <510C275B.7060200@davea.name> <510C6519.5040502@pearwood.info> Message-ID: I'd suggest having the newfile open after outfile is defined also a close statement on newfile - or use it with 'with' such as: ... and replace the last line like so: with open(outfile, 'w') as newfile: main(mystring, infile, newfile) (and looking muchly improved, well done) Nick On Fri, Feb 1, 2013 at 8:57 PM, Scurvy Scott wrote: > And just for the records sake, this is what I've gotten and you guys > should see obviously that you helped a lot and I learned a thing or > two so I won't have to ask the same silly questions next time: > > > > > def main(mystring, infile, outfile): > with open('infile', 'r') as inF: > for index, line in enumerate(inF): > if myString in line: > newfile.write("string %s found on line > #%d" (line, index)) > print "complete." > > > if __name__ == '__main__': > import sys > newfile = open('outfile', 'w') > help_text = "usage: python scanfile.py STRINGTOSEARCH > IMPORTFILENAME OUTPUTFILENAME" > if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) == 0: > print (help_text) > sys.exit() > myString = sys.argv[1] > infile = sys.argv[2] > outfile = sys.argv[3] > main(mystring, infile, outfile) > > Look right to you? Looks okay to me, except maybe the three ORs in the > information line, is there a more pythonic way to accomplish that > task? > > Scott > > On Fri, Feb 1, 2013 at 8:31 PM, Scurvy Scott wrote: > >> Best practice is to check if your program is being run as a script > before > >> doing anything. That way you can still import the module for testing or > >> similar: > >> > >> > >> def main(mystring, infile, outfile): > >> # do stuff here > >> > >> > >> if __name__ == '__main__': > >> # Running as a script. > >> import sys > >> mystring = sys.argv[1] > >> infile = sys.argv[2] > >> outfile = sys.argv[3] > >> main(mystring, infile, outfile) > >> > >> > >> > >> Best practice for scripts (not just Python scripts, but *any* script) > is to > >> provide help when asked. Insert this after the "import sys" line, > before you > >> start processing: > >> > >> if '-h' in sys.argv or '--help' in sys.argv: > >> print(help_text) > >> sys.exit() > >> > >> > >> > >> If your argument processing is more complicated that above, you should > use > >> one of the three argument parsing modules that Python provides: > >> > >> http://docs.python.org/2/library/getopt.html > >> http://docs.python.org/2/library/optparse.html (deprecated -- do not > use > >> this for new code) > >> http://docs.python.org/2/library/argparse.html > >> > >> > >> getopt is (in my opinion) the simplest to get started, but the weakest. > >> > >> There are also third-party argument parsers that you could use. Here's > one > >> which I have never used but am intrigued by: > >> > >> http://docopt.org/ > >> > >> > >> > >> -- > >> Steven > >> > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > > > > Steve- > > thanks a lot for showing me the if __name__ = main part > > I've often wondered how it was used and it didn't make sense until I > > saw it in my own code if that makes any sense. > > Also appreciate the help on the "instructional" side of things. > > > > One question related to the instruction aspect- does this make sense to > you? > > > > If len(sys.argv) == 0: > > print "usage: etc etc etc" > > > > > > > > Nick, Dave, and Steve, again, you guys are awesome. Thanks for all your > help. > > > > Scott > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sydney.shall at kcl.ac.uk Sat Feb 2 16:27:17 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sat, 2 Feb 2013 15:27:17 +0000 Subject: [Tutor] First Python Test In-Reply-To: <874nhu97eb.fsf@pbot.home> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <874nhu97eb.fsf@pbot.home> Message-ID: <510D3055.4020703@kcl.ac.uk> You are correct, of course. OK. So Bluefish is the Free open-source GNU editor and it is suitable for Python. We will have a complete menagerie soon. Thanks. Sydney On 02/02/2013 13:23, Aur?lien DESBRI?RES wrote: > Join #emacs on irc.freenode.net and ask them. > > I do not bring any support for non free Operating System nor > BrainWashing ones ;-) > > "Shall, Sydney" writes: > >> Dear Aurelien, >> Would you please explain how one installs GNU Emacs on a MAC using OS >> X v10.6. >> I cannot find a binary package. The GNU site seems to me to have only >> source code packages. >> Mille fois merci. >> Sydney >> >> >> On 02/02/2013 09:54, Aur?lien DESBRI?RES wrote: >>> hmm ... you should use GNU Emacs, it's Free in price and license! >>> >>> Extensible Text Editor with a cool Python-mode ;-) >>> >>> Jamie Griffin writes: >>> >>>> * Simon Yan [2013-02-02 01:11:12 +0800]: >>>> >>>>> I would recommend start off from a simple text editor that has basic syntax >>>>> highlighting features. There are a number of options out there. >>>>> TextMate is a good choice, a little pricy. >>>>> VIM, if you are a terminal guy >>>>> Even Python IDLE is a good choice you wanted to edit just a few simple .py >>>>> files. >>>>> >>>>> I would suggest give it a look in the Mac App Store and you will find a few >>>>> other good ones too. >>>> I believe the editor of choice on Mac OS X these days is BBEdit - >>>> again, a bit expensive. TextMate used to be good but there are >>>> better ones out there now. Personally, I prefer the commandline >>>> editors, vi or vim which is already installed on Mac OS X. I haven't >>>> used the Xcode editor before but if it's what you're comfortable >>>> with then it's probably best to stick with it. >>>> >>>> >>>> Primary Key: 4096R/1D31DC38 2011-12-03 >>>> Key Fingerprint: A4B9 E875 A18C 6E11 F46D B788 BEE6 1251 1D31 DC38 >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From alan.gauld at btinternet.com Sat Feb 2 18:49:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Feb 2013 17:49:14 +0000 Subject: [Tutor] First Python Test In-Reply-To: <510D0D1E.9010903@kcl.ac.uk> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> Message-ID: On 02/02/13 12:57, Shall, Sydney wrote: > Dear Aurelien, > Would you please explain how one installs GNU Emacs on a MAC using OS X > v10.6. Last time I looked it was already installed. Just type emacs at a Terminal prompt. You can also get a Cocoa version that run in a separate Window, try Google for Cocoa emacs... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 2 18:50:47 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Feb 2013 17:50:47 +0000 Subject: [Tutor] First Python Test In-Reply-To: <510D3055.4020703@kcl.ac.uk> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <874nhu97eb.fsf@pbot.home> <510D3055.4020703@kcl.ac.uk> Message-ID: On 02/02/13 15:27, Shall, Sydney wrote: > OK. So Bluefish is the Free open-source GNU editor and it is suitable > for Python. No thats emacs. Bluefish is an open source web editor(HTML, CSS etc). It may support Python but its not an ideal IDE. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sydney.shall at kcl.ac.uk Sat Feb 2 19:09:37 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sat, 2 Feb 2013 18:09:37 +0000 Subject: [Tutor] First Python Test In-Reply-To: References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <874nhu97eb.fsf@pbot.home> <510D3055.4020703@kcl.ac.uk> Message-ID: <510D5661.7090909@kcl.ac.uk> Thanks for both your comments, Alan. I am wiser now. Sydney On 02/02/2013 17:50, Alan Gauld wrote: > On 02/02/13 15:27, Shall, Sydney wrote: > >> OK. So Bluefish is the Free open-source GNU editor and it is suitable >> for Python. > > > No thats emacs. > Bluefish is an open source web editor(HTML, CSS etc). > > It may support Python but its not an ideal IDE. > > -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From david at graniteweb.com Sat Feb 2 20:25:33 2013 From: david at graniteweb.com (David Rock) Date: Sat, 2 Feb 2013 13:25:33 -0600 Subject: [Tutor] First Python Test In-Reply-To: References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> Message-ID: <20130202192533.GA2129@wdfs.bad> * Alan Gauld [2013-02-02 17:49]: > On 02/02/13 12:57, Shall, Sydney wrote: > > Dear Aurelien, > > Would you please explain how one installs GNU Emacs on a MAC using OS X > > v10.6. > > Last time I looked it was already installed. Just type emacs at a > Terminal prompt. Verified on 10.6.8 -- David Rock david at graniteweb.com From sydney.shall at kcl.ac.uk Sun Feb 3 13:20:43 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sun, 3 Feb 2013 12:20:43 +0000 Subject: [Tutor] First Python Test In-Reply-To: References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> Message-ID: <510E561B.6070003@kcl.ac.uk> Dear Alan, I installed Cocoa emacs successfully. But it does not run on OS X 10.6.8. The notes with it say that it was built for 10.4. Where may I look for an update, please? With many thanks for your help. Sydney On 02/02/2013 17:49, Alan Gauld wrote: > On 02/02/13 12:57, Shall, Sydney wrote: >> Dear Aurelien, >> Would you please explain how one installs GNU Emacs on a MAC using OS X >> v10.6. > > Last time I looked it was already installed. Just type emacs at a > Terminal prompt. > > You can also get a Cocoa version that run in a separate Window, try > Google for Cocoa emacs... > > > -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From jguadamuz at gmail.com Sun Feb 3 14:13:44 2013 From: jguadamuz at gmail.com (=?ISO-8859-1?Q?Jonat=E1n_Guadamuz?=) Date: Sun, 3 Feb 2013 07:13:44 -0600 Subject: [Tutor] First Python Test In-Reply-To: <510E561B.6070003@kcl.ac.uk> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <510E561B.6070003@kcl.ac.uk> Message-ID: <7583509039403960590@unknownmsgid> El 03/02/2013, a las 06:53 a.m., "Shall, Sydney" escribi?: > Dear Alan, > I installed Cocoa emacs successfully. > But it does not run on OS X 10.6.8. > The notes with it say that it was built for 10.4. > Where may I look for an update, please? > With many thanks for your help. > Sydney Maybe you can look here aquamacs.org From sydney.shall at kcl.ac.uk Sun Feb 3 17:47:26 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Sun, 3 Feb 2013 16:47:26 +0000 Subject: [Tutor] First Python Test In-Reply-To: <7583509039403960590@unknownmsgid> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <510E561B.6070003@kcl.ac.uk> <7583509039403960590@unknownmsgid> Message-ID: <510E949E.7010506@kcl.ac.uk> Thanks Jonatan. Sydney On 03/02/2013 13:13, Jonat?n Guadamuz wrote: > El 03/02/2013, a las 06:53 a.m., "Shall, Sydney" > escribi?: > >> Dear Alan, >> I installed Cocoa emacs successfully. >> But it does not run on OS X 10.6.8. >> The notes with it say that it was built for 10.4. >> Where may I look for an update, please? >> With many thanks for your help. >> Sydney > Maybe you can look here > > aquamacs.org > -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From jmz.griffin at kode5.net Sun Feb 3 17:53:48 2013 From: jmz.griffin at kode5.net (James Griffin) Date: Sun, 3 Feb 2013 16:53:48 +0000 Subject: [Tutor] First Python Test In-Reply-To: <510D0A5B.4060809@kcl.ac.uk> References: <510D0A5B.4060809@kcl.ac.uk> Message-ID: <20130203165348.GB30919@kontrol.kode5.net> --> Shall, Sydney [2013-02-02 12:45:15 +0000]: > Two free good text editors for the MAC are; > 1. Komodo > 2. Text Wrangler. > hth > Sydney aquamacs is the correct gui version to use. There is also a gvim binary available. Both emacs and vim are installed already on Mac OS X but in text only versions, no GUI. I have never used Komodo or Text Wrangler, or any other GUI editor for that matter so I cannot comment on how good they are. I tend to spend about 90% of my time using the command-line on my Mac, but that's just my preference. Some people prefer GUI editors. From alan.gauld at btinternet.com Sun Feb 3 18:11:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 03 Feb 2013 17:11:48 +0000 Subject: [Tutor] First Python Test In-Reply-To: <510E561B.6070003@kcl.ac.uk> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <510E561B.6070003@kcl.ac.uk> Message-ID: On 03/02/13 12:20, Shall, Sydney wrote: > Dear Alan, > I installed Cocoa emacs successfully. > But it does not run on OS X 10.6.8. > The notes with it say that it was built for 10.4. Sofware built for 10.4 should run fine on 10.6. But I only have 10.4 so can't do any testing... Not sure why its broke, but thee are several variants to choose from, somebody said aquamacs, there are others too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jacklittlemc at yahoo.com Sun Feb 3 20:15:42 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Sun, 3 Feb 2013 11:15:42 -0800 (PST) Subject: [Tutor] More Help Message-ID: <1359918942.19290.YahooMailNeo@web124503.mail.ne1.yahoo.com> So I have gotten responses to my previous email sent 3 days ago, all saying define path1pt1() before simpstart, but I do not know how. Help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Sun Feb 3 20:26:05 2013 From: s.charonis at gmail.com (Spyros Charonis) Date: Sun, 3 Feb 2013 19:26:05 +0000 Subject: [Tutor] pickle.dump yielding awkward output Message-ID: Hello Pythoners, I am experiencing a strange result with the pickle module when using it to write certain results to a separate file. In short, I have a program that reads a file, finds lines which satisfy some criteria, and extracts those lines, storing them in a list. I am trying to write this list to a separate file. The list of extracted lines looks like this: ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 N ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51 C ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13 C The output stored from the call to the pickle.dump method, however, looks like this: (lp0 S'ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 N \r\n' p1 aS'ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51 C \r\n' p2 aS'ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13 C \r\n' The code I am using to write the output to an external file goes as follows: def export_antibody_chains(): ''' EXPORT LIST OF EXTRACTED CHAINS TO FILE ''' chains_file = open(query + '_Chains', 'wb') pickle.dump(ab_chains, chains_file) # ab_chains is global chains_file.close() return Does anyone know why the strings lp0, S', aS' are showing up? -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Feb 3 20:29:44 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 3 Feb 2013 14:29:44 -0500 Subject: [Tutor] More Help In-Reply-To: <1359918942.19290.YahooMailNeo@web124503.mail.ne1.yahoo.com> References: <1359918942.19290.YahooMailNeo@web124503.mail.ne1.yahoo.com> Message-ID: Move the code that defines path1pt1 above the function that calls it. Also, don't start of new thread -- you are making it impossible for someone to know the context of your question. Also, Use a better subject line On Sun, Feb 3, 2013 at 2:15 PM, Jack Little wrote: > So I have gotten responses to my previous email sent 3 days ago, all > saying define path1pt1() before simpstart, but I do not know how. Help? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Sun Feb 3 20:54:26 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 3 Feb 2013 14:54:26 -0500 Subject: [Tutor] More Help In-Reply-To: References: <1359918942.19290.YahooMailNeo@web124503.mail.ne1.yahoo.com> Message-ID: On Sun, Feb 3, 2013 at 2:29 PM, Joel Goldstick wrote: > Move the code that defines path1pt1 above the function that calls it. > > Also, don't start of new thread -- you are making it impossible for > someone to know the context of your question. Also, Use a better subject > line > > > On Sun, Feb 3, 2013 at 2:15 PM, Jack Little wrote: > >> So I have gotten responses to my previous email sent 3 days ago, all >> saying define path1pt1() before simpstart, but I do not know how. Help? >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> I was curious about this post, and so I looked back through your previous posts. They all seem to be about getting this game code to work. I'm guessing that you copied it from somewhere -- or mostly copied it. You don't seem to have a grasp of basic concepts of programming in python. This seems to be a good example of cargo cult programming http://en.wikipedia.org/wiki/Cargo_cult_programming I suggest you set aside this project and go to the python online tutorial, or use Alan's book http://www.alan-g.me.uk/ , or google for Leaning Python the hard way, and get some basic concepts together in your mind. Also, set your mail client to text -- not rich text or html. Since indentation in python is essential to the meaning of the code, using rich text which often mangles indentation makes your examples impossible to decipher. When you've done that you will be able to ask question here that will help you learn more and raise your skill level. > > > -- > Joel Goldstick > http://joelgoldstick.com > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Feb 3 23:36:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 04 Feb 2013 09:36:16 +1100 Subject: [Tutor] More Help In-Reply-To: <1359918942.19290.YahooMailNeo@web124503.mail.ne1.yahoo.com> References: <1359918942.19290.YahooMailNeo@web124503.mail.ne1.yahoo.com> Message-ID: <510EE660.3090802@pearwood.info> On 04/02/13 06:15, Jack Little wrote: > So I have gotten responses to my previous email sent 3 days ago, all saying >define path1pt1() before simpstart, but I do not know how. Help? You have something like this: ...code... ...more code... path1pt1() ... ... def path1pt1(): definition goes here Select the text starting with "def path1pt1" in your text editor, and ending with the end of the function. Then cut the text (Ctrl-X), move the cursor to the top of the file, and paste it (Ctrl-V). Clean up any extra blank lines needed. Your code should then look like this: def path1pt1(): definition goes here ...code... ...more code... path1pt1() ... ... -- Steven From davea at davea.name Mon Feb 4 00:07:15 2013 From: davea at davea.name (Dave Angel) Date: Sun, 03 Feb 2013 18:07:15 -0500 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: Message-ID: <510EEDA3.2050205@davea.name> On 02/03/2013 02:26 PM, Spyros Charonis wrote: > Hello Pythoners, > > I am experiencing a strange result with the pickle module when using it to > write certain results to a separate file. > > In short, I have a program that reads a file, finds lines which satisfy > some criteria, and extracts those lines, storing them in a list. I am > trying to write this list to a separate file. > > The list of extracted lines looks like this: > > ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 > N > > ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51 > C > > ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13 > C > > The output stored from the call to the pickle.dump method, however, looks > like this: > > (lp0 > S'ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 > N \r\n' > p1 > aS'ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51 > C \r\n' > p2 > aS'ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13 > C \r\n' > > The code I am using to write the output to an external file goes as follows: > > def export_antibody_chains(): > ''' EXPORT LIST OF EXTRACTED CHAINS TO FILE ''' > chains_file = open(query + '_Chains', 'wb') > pickle.dump(ab_chains, chains_file) # ab_chains is global > chains_file.close() > return > > Does anyone know why the strings lp0, S', aS' are showing up? > > Pickle stores the type of each variable, as well as the value, and stores it in a way as to make it easy to "unpickle" it. -- DaveA From davea at davea.name Mon Feb 4 00:48:35 2013 From: davea at davea.name (Dave Angel) Date: Sun, 03 Feb 2013 18:48:35 -0500 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: <510EEDA3.2050205@davea.name> Message-ID: <510EF753.4090804@davea.name> (top-posting and offline response fixed) On Sun, Feb 3, 2013 at 11:07 PM, Dave Angel wrote: >> On 02/03/2013 02:26 PM, Spyros Charonis wrote: >> >>> Hello Pythoners, >>> >>> I am experiencing a strange result with the pickle module when using it to >>> write certain results to a separate file. >>> >>> In short, I have a program that reads a file, finds lines which satisfy >>> some criteria, and extracts those lines, storing them in a list. I am >>> trying to write this list to a separate file. >>> >>> The list of extracted lines looks like this: >>> >>> ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 >>> N >>> >>> ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51 >>> C >>> >>> ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13 >>> C >>> >>> The output stored from the call to the pickle.dump method, however, looks >>> like this: >>> >>> (lp0 >>> S'ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 >>> N \r\n' >>> p1 >>> aS'ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51 >>> C \r\n' >>> p2 >>> aS'ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13 >>> C \r\n' >>> >>> The code I am using to write the output to an external file goes as >>> follows: >>> >>> def export_antibody_chains(): >>> ''' EXPORT LIST OF EXTRACTED CHAINS TO FILE ''' >>> chains_file = open(query + '_Chains', 'wb') >>> pickle.dump(ab_chains, chains_file) # ab_chains is global >>> chains_file.close() >>> return >>> >>> Does anyone know why the strings lp0, S', aS' are showing up? >>> >>> >>> >> Pickle stores the type of each variable, as well as the value, and stores >> it in a way as to make it easy to "unpickle" it. >> >> On 02/03/2013 06:17 PM, Spyros Charonis wrote: > Thank you Dave, > > Is there any way to circumvent this so that I get the list rendered > normally? Many thanks. > You'd better define "normally." Pickle's output is normal for pickle. Perhaps you want the values to be human readable instead. One possibility of many: If you know that all the values in the list are strings, and you want to produce a text file, with one such string per line, then try: outfile = open( "filename.txt", 'wt") for line in mylist: outfile.write( line + "\n") outfile.close() There are ways to clean that up, but since you haven't specified your python version, that'll do for a first attempt. -- DaveA From steve at pearwood.info Mon Feb 4 01:17:13 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 04 Feb 2013 11:17:13 +1100 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: Message-ID: <510EFE09.7070002@pearwood.info> On 04/02/13 06:26, Spyros Charonis wrote: > The output stored from the call to the pickle.dump method, however, looks > like this: [...] > Does anyone know why the strings lp0, S', aS' are showing up? Why do you care? Pickle is not a human-readable format. It may use plain text (optionally, there are also binary pickle formats) but it is not intended for humans to read or write. Pickle will write whatever information it needs in order to be able to reconstruct the data that you give it. My guess is that the things you see tell pickle which protocol is being used, and that the data you are writing is a list of strings. Unless you are creating a tool for analyzing pickle files, all you need care is that you can round-trip data into and out of pickle files. f = open('filename', 'wb') pickle.dump(data, f) f.close() f = open('filename', 'rb') newdata = pickle.load(f) f.close() assert data == newdata If you're looking for a storage format that is human-editable, check out the json or plist modules, or the third-party pyyaml module. http://docs.python.org/2/library/json.html http://docs.python.org/2/library/plistlib.html http://pyyaml.org/ -- Steven From alan.gauld at btinternet.com Mon Feb 4 02:03:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Feb 2013 01:03:45 +0000 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: Message-ID: On 03/02/13 19:26, Spyros Charonis wrote: > I am experiencing a strange result with the pickle module when using it > to write certain results to a separate file. The only strangec results using pickle would be if the uinpickle failed to bring back that which was pickled. Pickle is a storage format not a display format. > In short, I have a program that reads a file, finds lines which satisfy > some criteria, and extracts those lines, storing them in a list. Extracting them with pickle I hope? That's the only thing that should be used to unpickle a pickled file. > The list of extracted lines looks like this: > > ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 > N > > The output stored from the call to the pickle.dump method, however, > looks like this: > > (lp0 > S'ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 > N \r\n' Yep, I'm sure pickle can make sense of it. > Does anyone know why the strings lp0, S', aS' are showing up? Because that's what pickle puts in there to help it unpickle it later. Why do you care? You shouldn't be looking at it (unless you want to understand how pickle works). pickle, as the name suggests, is intended for storing python objects for later use. This is often called object persistence in programming parlance. It is not designed for anything else. If you want cleanly formatted data in a file that you can read in a text editor or similar you need to do the formatting yourself or use another recognised format such as CSV or configparser (aka ini file). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From gayathri.s112 at gmail.com Mon Feb 4 07:24:35 2013 From: gayathri.s112 at gmail.com (Gayathri S) Date: Mon, 4 Feb 2013 11:54:35 +0530 Subject: [Tutor] Help- Regarding python Message-ID: Hi All....! If i have data set like this means... 3626,5000,2918,5000,2353,2334,2642,1730,1687,1695,1717,1744,593,502,493,504,449,431,444,444,429,10 438,498,3626,3629,5000,2918,5000,2640,2334,2639,1696,1687,1695,1717,1744,592,502,493,504,449,431,444,441,429,10 439,498,3626,3629,5000,2918,5000,2633,2334,2645,1705,1686,1694,1719,1744,589,502,493,504,446,431,444,444,430,10 440,5000,3627,3628,5000,2919,3028,2346,2330,2638,1727,1684,1692,1714,1745,588,501,492,504,451,433,446,444,432,10 444,5021,3631,3634,5000,2919,5000,2626,2327,2638,1698,1680,1688,1709,1740,595,500,491,503,453,436,448,444,436,10 451,5025,3635,3639,5000,2920,3027,2620,2323,2632,1706,1673,1681,1703,753,595,499,491,502,457,440,453,454,442,20 458,5022,3640,3644,5000,2922,5000,2346,2321,2628,1688,1666,1674,1696,744,590,496. How to do PCA on this data? if it is in array how to do that? and also how to use princomp() in PCA? Shall i use the following code for doing PCA on given input? could you tell me? from numpy import mean,cov,double,cumsum,dot,linalg,array,rank from pylab import plot,subplot,axis,stem,show,figure A = array([ [2.4,0.7,2.9,2.2,3.0,2.7,1.6,1.1,1.6,0.9], [2.5,0.5,2.2,1.9,3.1,2.3,2,1,1.5,1.1] ]) M = (A-mean(A.T,axis=1)).T[latent,coeff] = linalg.eig(cov(M)) score = dot(coeff.T,M) return coeff,score,latent princomp(A): coeff, score, latent = princomp(A.T) figure() subplot(121) m = mean(A,axis=1) plot([0, -coeff[0,0]*2]+m[0], [0, -coeff[0,1]*2]+m[1],'--k') plot([0, coeff[1,0]*2]+m[0], [0, coeff[1,1]*2]+m[1],'--k') plot(A[0,:],A[1,:],'ob') # the data axis('equal') subplot(122) plot(score[0,:],score[1,:],'*g') axis('equal') plt.show() Thanks....! Regards, Gayathri. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 4 09:45:10 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Feb 2013 08:45:10 +0000 Subject: [Tutor] Help- Regarding python In-Reply-To: References: Message-ID: On 04/02/13 06:24, Gayathri S wrote: > Hi All....! > If i have data set like this means... > > 3626,5000,2918,5000,2353,2334,2642,1730,1687,1695,1717,1744,593,502,493,504,449,431,444,444,429,10 ... > 458,5022,3640,3644,5000,2922,5000,2346,2321,2628,1688,1666,1674,1696,744,590,496. > > How to do PCA on this data? if it is in array how to do that? and also > how to use princomp() in PCA? No idea. I don't know what pca or princomp are. It looks like they might be numpy or pylab functions in which case you probably will get better results posting on a forum for those modules. This list is for learning the core language and standard library. Having said that it looks like you could use some time learning the basics before delving into numpy etc. comments below... > from numpy import mean,cov,double,cumsum,dot,linalg,array,rank > from pylab import plot,subplot,axis,stem,show,figure > A = array([ [2.4,0.7,2.9,2.2,3.0,2.7,1.6,1.1,1.6,0.9], > [2.5,0.5,2.2,1.9,3.1,2.3,2,1,1.5,1.1] ]) > M = (A-mean(A.T,axis=1)).T[latent,coeff] = linalg.eig(cov(M)) > score = dot(coeff.T,M) > return coeff,score,latent You have a return that is not inside a function. That makes no sense and in fact I get a syntax error so presumably you haven't actually tried running this code. > princomp(A): This calls princomp() but does nothing with the return values > coeff, score, latent = princomp(A.T) This calls princomp() and stores 3 return values. Its unusual for a function to have such different semantics. Which is correct? > figure() > subplot(121) Again calling functions without storing values. It may be valid but looks unlikely... > m = mean(A,axis=1) > plot([0, -coeff[0,0]*2]+m[0], [0, -coeff[0,1]*2]+m[1],'--k') > plot([0, coeff[1,0]*2]+m[0], [0, coeff[1,1]*2]+m[1],'--k') > plot(A[0,:],A[1,:],'ob') # the data > axis('equal') > subplot(122) > plot(score[0,:],score[1,:],'*g') > axis('equal') > plt.show() Here you use plt but plt is not defined anywhere in your program. I think you need to go back to Python basics and learn how to write basic code before trying to use the more exotic modules. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From s.charonis at gmail.com Mon Feb 4 12:12:22 2013 From: s.charonis at gmail.com (Spyros Charonis) Date: Mon, 4 Feb 2013 11:12:22 +0000 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: Message-ID: Thank you Alan, Steven, I don't care about the characters from the pickle operation per se, I just want the list to be stored in its native format. What I am trying to do is basically the Unix shell equivalent of: "Unix command" > newfile.txt I am trying to store the list that I get from my code in a separate file, in human-readable format. On Mon, Feb 4, 2013 at 1:03 AM, Alan Gauld wrote: > On 03/02/13 19:26, Spyros Charonis wrote: > >> I am experiencing a strange result with the pickle module when using it >> to write certain results to a separate file. >> > > The only strangec results using pickle would be if the uinpickle failed to > bring back that which was pickled. > Pickle is a storage format not a display format. > > > In short, I have a program that reads a file, finds lines which satisfy >> some criteria, and extracts those lines, storing them in a list. >> > > Extracting them with pickle I hope? That's the only thing that should be > used to unpickle a pickled file. > > > The list of extracted lines looks like this: >> >> ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 >> N >> >> The output stored from the call to the pickle.dump method, however, >> looks like this: >> >> (lp0 >> S'ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40 >> N \r\n' >> > > Yep, I'm sure pickle can make sense of it. > > > Does anyone know why the strings lp0, S', aS' are showing up? >> > > Because that's what pickle puts in there to help it unpickle it later. > > Why do you care? You shouldn't be looking at it (unless you want to > understand how pickle works). > > pickle, as the name suggests, is intended for storing python objects > for later use. This is often called object persistence in programming > parlance. It is not designed for anything else. > > If you want cleanly formatted data in a file that you can read in a text > editor or similar you need to do the formatting yourself or use another > recognised format such as CSV or configparser (aka ini file). > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 4 13:50:41 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Feb 2013 12:50:41 +0000 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: Message-ID: On 04/02/13 11:12, Spyros Charonis wrote: > What I am trying to do is basically the Unix shell equivalent of: "Unix > command" > newfile.txt That works just fine with Python too. Just print to stdout in whatever format you want and redirect the output to a file \$ python myscript.py > myfile.txt That will work from a command line in Windows, Linux and MacOS... > I am trying to store the list that I get from my code in a separate > file, in human-readable format. Then print it in the format you want using string formatting to control spacing, justification etc. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Feb 4 15:21:29 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 05 Feb 2013 01:21:29 +1100 Subject: [Tutor] pickle.dump yielding awkward output In-Reply-To: References: Message-ID: <510FC3E9.1000209@pearwood.info> On 04/02/13 22:12, Spyros Charonis wrote: > Thank you Alan, Steven, > > I don't care about the characters from the pickle operation per se, I just > want the list to be stored in its native format. That's an in-memory binary format. There is no way to get access to that from pure Python code. You may be able to do it using the ctypes module, which is an interface to the underlying C implementation. But keep in mind that this is only in the CPython implementation, and will not work in IronPython, PyPy or Jython. > What I am trying to do is basically the Unix shell equivalent of: "Unix > command"> newfile.txt In Unix commands, virtually everything is text. Python is not like that -- everything is a binary object. But you can get a text representation of Python objects, e.g. a list, with: print repr(mylist) -- Steven From steve at pearwood.info Mon Feb 4 15:33:09 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 05 Feb 2013 01:33:09 +1100 Subject: [Tutor] Help- Regarding python In-Reply-To: References: Message-ID: <510FC6A5.8090407@pearwood.info> On 04/02/13 17:24, Gayathri S wrote: > Hi All....! > If i have data set like this means... > > 3626,5000,2918,5000,2353,2334,2642,[...],496. No need to dump your entire data set on us. Just a few representative values will do. > How to do PCA on this data? if it is in array how to do that? and also how > to use princomp() in PCA? What's PCA? What's princomp? > Shall i use the following code for doing PCA on given input? could you tell > me? Have you tried it? What happens? This is a list for people learning Python the programming language. We are not experts on numpy, which is a specialist package for scientific use. We are not statisticians either. You can probably assume that most of us know what "standard deviation" is. Anything more complicated than that, you should ask on a specialist numpy mailing list. Good luck! -- Steven From david at graniteweb.com Mon Feb 4 15:58:26 2013 From: david at graniteweb.com (David Rock) Date: Mon, 4 Feb 2013 08:58:26 -0600 Subject: [Tutor] First Python Test In-Reply-To: <510E949E.7010506@kcl.ac.uk> References: <20130202093118.GB6079@kontrol.kode5.net> <87ehgz82hg.fsf@pbot.home> <510D0D1E.9010903@kcl.ac.uk> <510E561B.6070003@kcl.ac.uk> <7583509039403960590@unknownmsgid> <510E949E.7010506@kcl.ac.uk> Message-ID: <20130204145826.GB2129@wdfs.bad> * Shall, Sydney [2013-02-03 16:47]: > > On 03/02/2013 13:13, Jonat?n Guadamuz wrote: > > El 03/02/2013, a las 06:53 a.m., "Shall, Sydney" > > escribi?: > > > >> Dear Alan, > >> I installed Cocoa emacs successfully. > >> But it does not run on OS X 10.6.8. > >> The notes with it say that it was built for 10.4. > >> Where may I look for an update, please? > >> With many thanks for your help. > >> Sydney > > Maybe you can look here > > > > aquamacs.org The first hit I get googling for "cocoa emacs" returns: http://emacsformacosx.com/ Perhaps that will work for you. I've tested that it works on my system, at least ("works" = it ran). -- David Rock david at graniteweb.com From fomcl at yahoo.com Mon Feb 4 16:32:57 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 4 Feb 2013 07:32:57 -0800 (PST) Subject: [Tutor] nose, git, post-commit hook Message-ID: <1359991977.53244.YahooMailNeo@web163806.mail.gq1.yahoo.com> Hi, I am using git VCS and I read about the possibility to use post-commit hooks for nose tests. That sounds pretty cool, but does this also have disadvantages? It would be very annoying if I couldn't check in code, safely tucked away on some server, that is not yet working. Is there also a way to by-pass the 'mandatory' tests? ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From sydney.shall at kcl.ac.uk Mon Feb 4 18:08:43 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Mon, 4 Feb 2013 17:08:43 +0000 Subject: [Tutor] First Python Test In-Reply-To: <20130204145826.GB2129@wdfs.bad> References: <20130202093118.GB6079@kontrol.kode5 Message-ID: <510FEB1B.2070302@kcl.ac.uk> Dear David, Many thanks for this information. It was exactly what I needed. It anyone wants Emacs editor for MAC OS X 10.6, this is the place to find it. I would also like to say that I am deeply impressed with the knowledge and generosity of the people on this list. Thanks. Sydney On 04/02/2013 14:58, David Rock wrote: > * Shall, Sydney [2013-02-03 16:47]: >> On 03/02/2013 13:13, Jonat?n Guadamuz wrote: >>> El 03/02/2013, a las 06:53 a.m., "Shall, Sydney" >>> escribi?: >>> >>>> Dear Alan, >>>> I installed Cocoa emacs successfully. >>>> But it does not run on OS X 10.6.8. >>>> The notes with it say that it was built for 10.4. >>>> Where may I look for an update, please? >>>> With many thanks for your help. >>>> Sydney >>> Maybe you can look here >>> >>> aquamacs.org > The first hit I get googling for "cocoa emacs" returns: > http://emacsformacosx.com/ > > Perhaps that will work for you. I've tested that it works on my system, > at least ("works" = it ran). > -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From modulok at gmail.com Mon Feb 4 18:13:33 2013 From: modulok at gmail.com (Modulok) Date: Mon, 4 Feb 2013 10:13:33 -0700 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? Message-ID: List, Simple question: Is there a common pattern for iterating a dict, but also providing access to an iteration counter? Here's what I usually do (below). I'm just wondering if there are other, more clever ways:: data = {'a': "apple", 'b': "banana", 'c': "cherry"} i = 0 for k,v in data.items(): print("i: %s, k: %s, v: %s" % (i,k,v)) i += 1 Another variant, same idea:: data = {'a': "apple", 'b': "banana", 'c': "cherry"} for i,k,v in zip(range(len(data)), data.keys(), data.values()): print("i: %s, k: %s, v: %s" % (i,k,v)) How would you do it? -Modulok- From davea at davea.name Mon Feb 4 18:28:38 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Feb 2013 12:28:38 -0500 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: References: Message-ID: <510FEFC6.8030000@davea.name> On 02/04/2013 12:13 PM, Modulok wrote: > List, > > Simple question: Is there a common pattern for iterating a dict, but also > providing access to an iteration counter? Here's what I usually do (below). I'm > just wondering if there are other, more clever ways:: > > data = {'a': "apple", 'b': "banana", 'c': "cherry"} > i = 0 > for k,v in data.items(): > print("i: %s, k: %s, v: %s" % (i,k,v)) > i += 1 > > Another variant, same idea:: > > data = {'a': "apple", 'b': "banana", 'c': "cherry"} > for i,k,v in zip(range(len(data)), data.keys(), data.values()): > print("i: %s, k: %s, v: %s" % (i,k,v)) > > > How would you do it? > -Modulok- enumerate() for i, (k, v) in enumerate(data.items()): -- DaveA From robert.day at merton.oxon.org Mon Feb 4 18:42:08 2013 From: robert.day at merton.oxon.org (Rob Day) Date: Mon, 4 Feb 2013 17:42:08 +0000 Subject: [Tutor] nose, git, post-commit hook In-Reply-To: <1359991977.53244.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1359991977.53244.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 4 February 2013 15:32, Albert-Jan Roskam wrote: > I am using git VCS and I read about the possibility to use post-commit hooks for nose tests. That sounds pretty cool, but does this also have disadvantages? > It would be very annoying if I couldn't check in code, safely tucked away on some server, that is not yet working. Is there also a way to by-pass the 'mandatory' tests? This isn't really a Python question, but if you use pre-commit hooks, you can bypass them with the "--no-verify" option to "git commit". See http://git-scm.com/book/en/Customizing-Git-Git-Hooks. -- Robert K. Day robert.day at merton.oxon.org From ghasemmg01 at leedslearning.net Mon Feb 4 18:52:18 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Mon, 4 Feb 2013 17:52:18 +0000 Subject: [Tutor] (no subject) Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D8379478C@LLN-SPP-ES-04.user01.lln.local> hi guys, this is the first bit of my program converting from binary to decimal without use of built in functions. binnum = input("Please enter a binary number: ") decnum = 0 rank = 1 for i in reversed(binnum): decnum += rank * int(i) rank *= 2 print(decnum). When I first tested the program, It printed the answer in a weird way. you can see the print screen of first tirst in the attachment. I wanted to know how I could adjust the program so that it only prints the real answer. e.g If user enters 11111111, then program should only print 255. thank you. -------------- next part -------------- A non-text attachment was scrubbed... Name: firstprogramttest.PNG Type: image/x-png Size: 18199 bytes Desc: firstprogramttest.PNG URL: From modulok at gmail.com Mon Feb 4 18:58:10 2013 From: modulok at gmail.com (Modulok) Date: Mon, 4 Feb 2013 10:58:10 -0700 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: <510FEFC6.8030000@davea.name> References: <510FEFC6.8030000@davea.name> Message-ID: Hmm.. no kidding. Well, at least I knew I was over-complicating it. Cheers! -Modulok- On 2/4/13, Dave Angel wrote: > On 02/04/2013 12:13 PM, Modulok wrote: >> List, >> >> Simple question: Is there a common pattern for iterating a dict, but also >> providing access to an iteration counter? Here's what I usually do >> (below). I'm >> just wondering if there are other, more clever ways:: >> >> data = {'a': "apple", 'b': "banana", 'c': "cherry"} >> i = 0 >> for k,v in data.items(): >> print("i: %s, k: %s, v: %s" % (i,k,v)) >> i += 1 >> >> Another variant, same idea:: >> >> data = {'a': "apple", 'b': "banana", 'c': "cherry"} >> for i,k,v in zip(range(len(data)), data.keys(), data.values()): >> print("i: %s, k: %s, v: %s" % (i,k,v)) >> >> >> How would you do it? >> -Modulok- > > enumerate() > > > for i, (k, v) in enumerate(data.items()): > > -- > DaveA > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From kwpolska at gmail.com Mon Feb 4 19:06:49 2013 From: kwpolska at gmail.com (Kwpolska) Date: Mon, 4 Feb 2013 19:06:49 +0100 Subject: [Tutor] (no subject) In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478C@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478C@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Mon, Feb 4, 2013 at 6:52 PM, Ghadir Ghasemi wrote: > hi guys, this is the first bit of my program converting from binary to decimal without use of built in functions. > > binnum = input("Please enter a binary number: ") > decnum = 0 > rank = 1 > > for i in reversed(binnum): > decnum += rank * int(i) > rank *= 2 > print(decnum). > > When I first tested the program, It printed the answer in a weird way. you can see the print screen of first tirst in the attachment. I wanted to know how I could adjust the program so that > it only prints the real answer. e.g If user enters 11111111, then program should only print 255. > thank you. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Move the print out of the loop. Also, do not post screenshots, use copy-paste. So, this becomes: binnum = input("Please enter a binary number: ") decnum = 0 rank = 1 for i in reversed(binnum): decnum += rank * int(i) rank *= 2 print(decnum) -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From dyoo at hashcollision.org Mon Feb 4 19:49:41 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 4 Feb 2013 11:49:41 -0700 Subject: [Tutor] Help- Regarding python In-Reply-To: References: Message-ID: > How to do PCA on this data? if it is in array how to do that? and also how > to use princomp() in PCA? Principal component analysis, http://en.wikipedia.org/wiki/Principal_component_analysis may not be "built in". Do you know for sure that it is? According to this blog entry, you can do it in numpy by coding the algorithm: http://glowingpython.blogspot.com/2011/07/principal-component-analysis-with-numpy.html If you use Google and search for the term "Principal component analysis Python", you should see several implementations of modules that provide that algorithm. From davea at davea.name Mon Feb 4 23:26:31 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Feb 2013 17:26:31 -0500 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: References: <510FEFC6.8030000@davea.name> Message-ID: <51103597.20105@davea.name> On 02/04/2013 12:58 PM, Modulok wrote: > Hmm.. no kidding. Well, at least I knew I was over-complicating it. > > Cheers! > -Modulok- > > Please don't top-post. Another point. I don't currently have Python 3.x installed, but I seem to remember that in Python 3 you can use the dict itself as an iterator providing both key and value. If I'm right, then it could be simplified further to: for i, (k, v) in enumerate(data): A simple test will prove me right or wrong. -- DaveA From steve at pearwood.info Tue Feb 5 00:18:14 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 05 Feb 2013 10:18:14 +1100 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: <51103597.20105@davea.name> References: <510FEFC6.8030000@davea.name> <51103597.20105@davea.name> Message-ID: <511041B6.5010902@pearwood.info> On 05/02/13 09:26, Dave Angel wrote: > Another point. I don't currently have Python 3.x installed, but I seem to >remember that in Python 3 you can use the dict itself as an iterator >providing both key and value. If I'm right, then it could be simplified >further to: > > > for i, (k, v) in enumerate(data): Nope, in both Python 2 and 3 iterating over a dict directly just provides the key. That's also how "if key in dict" works. -- Steven From davea at davea.name Tue Feb 5 01:04:07 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Feb 2013 19:04:07 -0500 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: <511041B6.5010902@pearwood.info> References: <510FEFC6.8030000@davea.name> <51103597.20105@davea.name> <511041B6.5010902@pearwood.info> Message-ID: <51104C77.6050200@davea.name> On 02/04/2013 06:18 PM, Steven D'Aprano wrote: > On 05/02/13 09:26, Dave Angel wrote: > >> Another point. I don't currently have Python 3.x installed, but I seem to >> remember that in Python 3 you can use the dict itself as an iterator >> providing both key and value. If I'm right, then it could be simplified >> further to: >> >> >> for i, (k, v) in enumerate(data): > > Nope, in both Python 2 and 3 iterating over a dict directly just > provides the > key. That's also how "if key in dict" works. > Then I'm glad I was tentative about it. I do recall there was some difference. Was it just that items(), keys() and values() methods return a view (iterator) instead of a list, and the iter*() versions are gone? -- DaveA From oscar.j.benjamin at gmail.com Tue Feb 5 01:21:24 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 5 Feb 2013 00:21:24 +0000 Subject: [Tutor] Help- Regarding python In-Reply-To: References: Message-ID: On 4 February 2013 06:24, Gayathri S wrote: > Hi All....! > If i have data set like this means... > > 3626,5000,2918,5000,2353,2334,2642,1730,1687,1695,1717,1744,593,502,493,504,449,431,444,444,429,10 > 438,498,3626,3629,5000,2918,5000,2640,2334,2639,1696,1687,1695,1717,1744,592,502,493,504,449,431,444,441,429,10 > 439,498,3626,3629,5000,2918,5000,2633,2334,2645,1705,1686,1694,1719,1744,589,502,493,504,446,431,444,444,430,10 > 440,5000,3627,3628,5000,2919,3028,2346,2330,2638,1727,1684,1692,1714,1745,588,501,492,504,451,433,446,444,432,10 > 444,5021,3631,3634,5000,2919,5000,2626,2327,2638,1698,1680,1688,1709,1740,595,500,491,503,453,436,448,444,436,10 > 451,5025,3635,3639,5000,2920,3027,2620,2323,2632,1706,1673,1681,1703,753,595,499,491,502,457,440,453,454,442,20 > 458,5022,3640,3644,5000,2922,5000,2346,2321,2628,1688,1666,1674,1696,744,590,496. PCA only makes sense for multivariate data: your data should be a set of vectors *all of the same length*. I'll assume that you were just being lazy when you posted it and that you didn't bother to copy the first and last lines properly... [snip] > > Shall i use the following code for doing PCA on given input? could you tell > me? This code you posted is all screwed up. It will give you errors if you try to run it. Also I don't really know what you mean by "doing PCA". The code below transforms your data into PCA space and plots a 2D scatter plot using the first two principal components. #!/usr/bin/env python import numpy as np from matplotlib import pyplot as plt data = np.array([ [438,498,3626,3629,5000,2918,5000,2640,2334,2639,1696,1687,1695,1717,1744,592,502,493,504,449,431,444,441,429,10], [439,498,3626,3629,5000,2918,5000,2633,2334,2645,1705,1686,1694,1719,1744,589,502,493,504,446,431,444,444,430,10], [440,5000,3627,3628,5000,2919,3028,2346,2330,2638,1727,1684,1692,1714,1745,588,501,492,504,451,433,446,444,432,10], [444,5021,3631,3634,5000,2919,5000,2626,2327,2638,1698,1680,1688,1709,1740,595,500,491,503,453,436,448,444,436,10], [451,5025,3635,3639,5000,2920,3027,2620,2323,2632,1706,1673,1681,1703,753,595,499,491,502,457,440,453,454,442,20], ]) # Compute the eigenvalues and vectors of the covariance matrix C = np.cov(data.T) eigenvalues, eigenvectors = np.linalg.eig(C) # 2D PCA - get the two eigenvectors with the largest eigenvalues v1, v2 = eigenvectors[:,:2].T # Project the data onto the two principal components data_pc1 = [np.dot(v1, d) for d in data] data_pc2 = [np.dot(v2, d) for d in data] # Scatter plot in PCA space fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(data_pc1, data_pc2, 'x') ax.set_xlabel(r'\$PC_1\$') ax.set_ylabel(r'\$PC_2\$') ax.legend(['data']) plt.show() Oscar From eryksun at gmail.com Tue Feb 5 04:56:50 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 4 Feb 2013 22:56:50 -0500 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: <51104C77.6050200@davea.name> References: <510FEFC6.8030000@davea.name> <51103597.20105@davea.name> <511041B6.5010902@pearwood.info> <51104C77.6050200@davea.name> Message-ID: On Mon, Feb 4, 2013 at 7:04 PM, Dave Angel wrote: >> Nope, in both Python 2 and 3 iterating over a dict directly just >> provides the key. That's also how "if key in dict" works. A dict implements __contains__ for an efficient "in" test. In general, the interpreter falls back to using iteration if a type lacks __contains__. In 2.x iter(some_dict) returns a dictionary-keyiterator (weird hyphen). In 3.x it's a dict_keyiterator (normal underscore). > Was it just that items(), keys() and values() methods return a view > (iterator) instead of a list, and the iter*() versions are gone? In 3.x, keys() and items() return views that are iterable (__iter__) and that implement the sequence methods __len__ and __contains__ as well as a few set operations that return a set: intersection (&), union (|), difference (-), and symmetric difference (^). Using the set methods for items() requires the values to also be hashable. The view returned by values() doesn't bother implementing __contains__ and the set operations, but it does have __iter__ and __len__. 2.7 provides these views via viewkeys(), viewitems(), and viewvalues(). The corresponding iterators returned by iter() in 3.x are dict_keyiterator, dict_itemiterator, and dict_valueiterator. From godsofliberty at lavabit.com Tue Feb 5 05:39:31 2013 From: godsofliberty at lavabit.com (heathen) Date: Mon, 04 Feb 2013 23:39:31 -0500 Subject: [Tutor] (no subject) In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478C@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478C@LLN-SPP-ES-04.user01.lln.local> Message-ID: <51108D03.8070709@lavabit.com> On 02/04/2013 12:52 PM, Ghadir Ghasemi wrote: > hi guys, this is the first bit of my program converting from binary to decimal without use of built in functions. > > binnum = input("Please enter a binary number: ") > decnum = 0 > rank = 1 > > for i in reversed(binnum): > decnum += rank * int(i) > rank *= 2 > print(decnum). > > When I first tested the program, It printed the answer in a weird way. you can see the print screen of first tirst in the attachment. I wanted to know how I could adjust the program so that > it only prints the real answer. e.g If user enters 11111111, then program should only print 255. > thank you. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Move your print statement out of the for loop. for i in reversed(binnum): decnum += rank * int(i) rank *= 2 print(decnum) From eryksun at gmail.com Tue Feb 5 06:08:26 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Feb 2013 00:08:26 -0500 Subject: [Tutor] Help- Regarding python In-Reply-To: References: Message-ID: On Mon, Feb 4, 2013 at 7:21 PM, Oscar Benjamin wrote: > eigenvalues, eigenvectors = np.linalg.eig(C) First sort by eigenvalue magnitude: >>> idx = np.argsort(eigenvalues)[::-1] >>> print idx [ 0 1 2 3 8 10 11 12 14 22 20 21 18 19 23 24 17 16 15 13 9 7 5 6 4] >>> eigenvalues = eigenvalues[idx] >>> eigenvectors = eigenvectors[:, idx] > # 2D PCA - get the two eigenvectors with the largest eigenvalues > v1, v2 = eigenvectors[:,:2].T From aaronmisquith at gmail.com Tue Feb 5 10:38:56 2013 From: aaronmisquith at gmail.com (Aaron Misquith) Date: Tue, 5 Feb 2013 15:08:56 +0530 Subject: [Tutor] How to create a GUI for python using tkinter Message-ID: I have attached a python program with this mail which peforms following operations: 1.Logs in to facebook. 2.Asks the user for access tokens. 3.Gets the friend list of the user. 4.outputs the friend list as pdf. My Problems regarding the above program are: 1.I want to display the names of my friends(in output) one in each line in the intermediate .doc file that i have created. example output: {'data': [{'name': 'Roy Fernandes'}, {'name': 'Aniruddh Beigh'}, I want it to be displayed as : Roy Fernandes Aniruddh Beigh 2.Is there a way to automate getting access tokens for the user that is logging in? If not how to get access tokens for each user while logging in? 3.How to dislpay text with clickable links. Eg: Something thing like alert box, wherein if you click the link you go to the page. 4. Finally my lecturer has asked me to create a gui for the facebook login program using tkinter library module. I don't know how to create one (the lecturer has not thought this topic in class so i'm just clueless here). So if someone can do it and explain me the steps it will be very helpfull. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: newfb.py Type: application/octet-stream Size: 2049 bytes Desc: not available URL: From oscar.j.benjamin at gmail.com Tue Feb 5 12:27:22 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 5 Feb 2013 11:27:22 +0000 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: References: <510FEFC6.8030000@davea.name> <51103597.20105@davea.name> <511041B6.5010902@pearwood.info> <51104C77.6050200@davea.name> Message-ID: On 5 February 2013 03:56, eryksun wrote: > On Mon, Feb 4, 2013 at 7:04 PM, Dave Angel wrote: >>> Nope, in both Python 2 and 3 iterating over a dict directly just >>> provides the key. That's also how "if key in dict" works. > > A dict implements __contains__ for an efficient "in" test. In general, > the interpreter falls back to using iteration if a type lacks > __contains__. I almost wrote this response but then I realised that Dave probably meant that "obj in dict" returns True if the dict has a key equal to obj rather than if the dict has a (key, value) pair equal to obj. Oscar From eryksun at gmail.com Tue Feb 5 12:36:39 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Feb 2013 06:36:39 -0500 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: References: <510FEFC6.8030000@davea.name> <51103597.20105@davea.name> <511041B6.5010902@pearwood.info> <51104C77.6050200@davea.name> Message-ID: On Tue, Feb 5, 2013 at 6:27 AM, Oscar Benjamin wrote: > > I almost wrote this response but then I realised that Dave probably > meant that "obj in dict" returns True if the dict has a key equal to > obj rather than if the dict has a (key, value) pair equal to obj. Thanks, that's probably what Steven meant. It's keeping "item in a_dict" consistent with "item in list(a_dict)". From fomcl at yahoo.com Tue Feb 5 13:01:02 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 5 Feb 2013 04:01:02 -0800 (PST) Subject: [Tutor] nose, git, post-commit hook In-Reply-To: References: <1359991977.53244.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <1360065662.673.YahooMailNeo@web163801.mail.gq1.yahoo.com> > On 4 February 2013 15:32, Albert-Jan Roskam wrote: >> I am using git VCS and I read about the possibility to use post-commit > hooks for nose tests. That sounds pretty cool, but does this also have > disadvantages? >> It would be very annoying if I couldn't check in code, safely tucked > away on some server, that is not yet working. Is there also a way to by-pass the > 'mandatory' tests? > > This isn't really a Python question, but if you use pre-commit hooks, > you can bypass them with the "--no-verify" option to "git > commit". See > http://git-scm.com/book/en/Customizing-Git-Git-Hooks. Hi Rob, Thanks for this useful link. I'll see what's most practical for me. As usual, the number of options of git is bedazzlingly large. I dared to ask this question on the Python list because I am planning to use this in conjunction with the nose package. I figured that this package (or something of python) *may* have some other functionality that ensures that tests are automatically run on a regular basis. It would be ideal if it could be combined with other tasks (I have pylint or pep8 in mind). Commit hooks appear to be a good method. Regards, Albert-Jan From wprins at gmail.com Tue Feb 5 14:40:12 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 5 Feb 2013 13:40:12 +0000 Subject: [Tutor] Fwd: How to create a GUI for python using tkinter In-Reply-To: References: Message-ID: Forwarding (presumed accidental) personal reply back to list. ---------- Forwarded message ---------- From: Aaron Misquith Date: 5 February 2013 13:01 Subject: Re: [Tutor] How to create a GUI for python using tkinter To: Walter Prins On Tue, Feb 5, 2013 at 5:40 PM, Walter Prins wrote: > On 5 February 2013 09:38, Aaron Misquith wrote: > >> I have attached a python program with this mail which peforms following >> operations: >> 1.Logs in to facebook. >> 2.Asks the user for access tokens. >> 3.Gets the friend list of the user. >> 4.outputs the friend list as pdf. >> >> My Problems regarding the above program are: >> 1.I want to display the names of my friends(in output) one in each line >> in the intermediate .doc file that i have created. >> example output: {'data': [{'name': 'Roy Fernandes'}, >> {'name': 'Aniruddh Beigh'}, >> I want it to be displayed as : Roy >> Fernandes >> >> Aniruddh Beigh >> >> 2.Is there a way to automate getting access tokens for the user that is >> logging in? If not how to get access tokens for each user while logging in? >> >> 3.How to dislpay text with clickable links. >> Eg: Something thing like alert box, wherein if you click the link you >> go to the page. >> >> 4. Finally my lecturer has asked me to create a gui for the facebook >> login program using tkinter library module. I don't know how to create one >> (the lecturer has not thought this topic in class so i'm just clueless >> here). So if someone can do it and explain me the steps it will be very >> helpfull. > > > The way this tutoring mailing list (and in general, any programming > mailing list or support forum) works is that you do the legwork first, then > come with the actual problems you're having. You don't just ask for people > to write your solutions for you. > > Also, your questions together with a partial solution by (apparently) > someone else makes me wonder whether this is homework. Can you please > clarify? Obviously, apart from the above comment on this not being a > solution service, we cannot provide direct solutions to homework > assignments. > > All that said, to address your questions somewhat: > 1.) The program is directly printing the returned Python dict object (e.g. > nik) which is why you're getting the curly-braced representation of it. To > print/output it differently, take some more control over the printing > process. E.g. print the attributes of the nik object manually and use > newline characters (\n) where required. If you don't understand this > answer then you're lacking some basic Python skills/understanding and I'd > recommend learning some basic Python first, perhaps by working through Alan > Gauld's tutorial: http://www.alan-g.me.uk/tutor/index.htm > Then try your hand at this problem again yourself, and *then* post back > with specific problems you're having. > > 2.) Probably, but I don't offhand know how. This is not really a Python > tutoring question and may be a question for appropriate for a Facebook API > programming forum. > > 3.) There's lots of TkInter materials on the web that will get you > started. Here's a decent tutorial: > http://www.tkdocs.com/tutorial/index.html > First of all i would like to confirm that this was my assignment and i have completed it and shown to my lecturer. I'll also confirm that the class facebook was available in stackoverflow( Not completely, I had to make some changes to suit my requirements).But the rest is all mine especially exporting the output as pdf. None of the forums were helpful regarding this. Everywhere people have mentioned about pypdf and reportlab toolkit , but none of them worked for me (i have also posted the solution on stackoverflow yesterday). After showing the output my lecturer informed me if i could Display better using tkinter GUI. Since it wasn't thought in class I have no idea regarding this. The problem that i encounter in creating GUI is I already have a class *facebook*; How am i supposed to integrate it to class "*Application*"(required to create GUI with tkinter) which i have to integrate it with (the small bookish knowledge i possess in the topic). I don't expect direct solutions but if you do give them i want possible * explanations* on it so i can understand how it was done. And since this is a tutor i want someone who knows the answers to teach me; since you cant study everything in class. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Feb 5 15:43:15 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 5 Feb 2013 14:43:15 +0000 Subject: [Tutor] How to create a GUI for python using tkinter In-Reply-To: References: Message-ID: Hi On 5 February 2013 09:38, Aaron Misquith wrote: >> >>> I have attached a python program with this mail which peforms following >>> operations: >>> 1.Logs in to facebook. >>> 2.Asks the user for access tokens. >>> 3.Gets the friend list of the user. >>> 4.outputs the friend list as pdf. >>> >>> My Problems regarding the above program are: >>> 1.I want to display the names of my friends(in output) one in each line >>> in the intermediate .doc file that i have created. >>> example output: {'data': [{'name': 'Roy Fernandes'}, >>> {'name': 'Aniruddh Beigh'}, >>> I want it to be displayed as : >>> Roy Fernandes >>> >>> Aniruddh Beigh >>> >>> 2.Is there a way to automate getting access tokens for the user that is >>> logging in? If not how to get access tokens for each user while logging in? >>> >>> 3.How to dislpay text with clickable links. >>> Eg: Something thing like alert box, wherein if you click the link you >>> go to the page. >>> >>> 4. Finally my lecturer has asked me to create a gui for the facebook >>> login program using tkinter library module. I don't know how to create one >>> (the lecturer has not thought this topic in class so i'm just clueless >>> here). So if someone can do it and explain me the steps it will be very >>> helpfull. >> >> >> The way this tutoring mailing list (and in general, any programming >> mailing list or support forum) works is that you do the legwork first, then >> come with the actual problems you're having. You don't just ask for people >> to write your solutions for you. >> >> Also, your questions together with a partial solution by (apparently) >> someone else makes me wonder whether this is homework. Can you please >> clarify? Obviously, apart from the above comment on this not being a >> solution service, we cannot provide direct solutions to homework >> assignments. >> >> All that said, to address your questions somewhat: >> 1.) The program is directly printing the returned Python dict object >> (e.g. nik) which is why you're getting the curly-braced representation of >> it. To print/output it differently, take some more control over the >> printing process. E.g. print the attributes of the nik object manually and >> use newline characters (\n) where required. If you don't understand this >> answer then you're lacking some basic Python skills/understanding and I'd >> recommend learning some basic Python first, perhaps by working through Alan >> Gauld's tutorial: http://www.alan-g.me.uk/tutor/index.htm >> Then try your hand at this problem again yourself, and *then* post back >> with specific problems you're having. >> >> 2.) Probably, but I don't offhand know how. This is not really a Python >> tutoring question and may be a question for appropriate for a Facebook API >> programming forum. >> >> 3.) There's lots of TkInter materials on the web that will get you >> started. Here's a decent tutorial: >> http://www.tkdocs.com/tutorial/index.html >> > > First of all i would like to confirm that this was my assignment and i > have completed it and shown to my lecturer. I'll also confirm that the > class facebook was available in stackoverflow( Not completely, I had to > make some changes to suit my requirements).But the rest is all mine > especially exporting the output as pdf. None of the forums were helpful > regarding this. > Making simple PDF's is almost trivial with Python. The following example is from http://is.gd/ol6bhn (a ReportLab tutorial that was turned up with the google search "python reportlab example"): from reportlab.pdfgen import canvas c = canvas.Canvas("hello.pdf") c.drawString(100,750,"Welcome to Reportlab!") c.save() > Everywhere people have mentioned about pypdf and reportlab toolkit , but > none of them worked for me (i have also posted the solution on > stackoverflow yesterday). > What did you try and what problems or errors did you run into? What did you want to happen instead? The problem that i encounter in creating GUI is I already have a class * > facebook*; How am i supposed to integrate it to class "*Application*"(required > to create GUI with tkinter) which i have to integrate it with (the small > bookish knowledge i possess in the topic). > Put your Facebook class in it's own module. Then import that module from your GUI application module (or from whatever module needs to use it) and create an instance of the Facebook class where you need it. Seriously, work through a Python programming tutorial, and then a TkInter one. You wouldn't be asking these questions if you had a proper grounding in programming concepts in general and Python. However it's not feasible to address that piecemeal style via a mailing list exchange here. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Tue Feb 5 16:27:24 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 5 Feb 2013 15:27:24 +0000 Subject: [Tutor] Help- Regarding python In-Reply-To: References: Message-ID: On 5 February 2013 05:08, eryksun wrote: > On Mon, Feb 4, 2013 at 7:21 PM, Oscar Benjamin > wrote: >> eigenvalues, eigenvectors = np.linalg.eig(C) > > First sort by eigenvalue magnitude: > > >>> idx = np.argsort(eigenvalues)[::-1] > >>> print idx > [ 0 1 2 3 8 10 11 12 14 22 20 21 18 19 23 24 17 16 15 13 9 7 5 6 4] > > >>> eigenvalues = eigenvalues[idx] > >>> eigenvectors = eigenvectors[:, idx] > >> # 2D PCA - get the two eigenvectors with the largest eigenvalues >> v1, v2 = eigenvectors[:,:2].T Thanks. I thought that eig already sorted them. The doc claims says that the values are "not necessarily ordered" but when I run it they are in descending order of absolute value. Also I should have used eigh since the covariance matrix is Hermitian (eigh seems to give the eigenvalues in ascending order). Oscar From alan.gauld at btinternet.com Tue Feb 5 19:38:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 05 Feb 2013 18:38:52 +0000 Subject: [Tutor] How to create a GUI for python using tkinter In-Reply-To: References: Message-ID: On 05/02/13 09:38, Aaron Misquith wrote: > 2.Is there a way to automate getting access tokens for the user that is > logging in? If not how to get access tokens for each user while logging in? No idea, you'll need to ask on a Facebook programming list. This one only deals with Python programming issues. > 3.How to dislpay text with clickable links. > Eg: Something thing like alert box, wherein if you click the link > you go to the page. Presumably you need to construct a URL. I'm not sure where you want these links but if its in the PDF you'll need to find out how PDFs do URLs... Find one and open it, or look at Reportlab again. > 4. Finally my lecturer has asked me to create a gui for the facebook > login program using tkinter library module. I don't know how to create > one Then read the tutorials online. You can start with the GUI topic in my tutoroial, then go to the TKinter section of the Python web site. There are at least 2 other excellent tkinter reference sites and the Tcl/Tk pages have a lot of good detail too. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ilhs_hs at yahoo.com Tue Feb 5 22:08:08 2013 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 5 Feb 2013 13:08:08 -0800 (PST) Subject: [Tutor] Getting range of a list Message-ID: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> Dear List members: I always have problem in getting ranges: Following is my representation of part of my file. >X1 A G C G >X2 A G >X3 A G >X4 H T I want to print the above contents in the following way: X1 \t A X1 \t G X1 \t C X1 \t G X2 \t A X2 \t G X3 \t A X3 \t G X4 \t H X4 \t H Here is what I do : >>> f1 = open('test','r') >>> da = f1.read().split('\n') >>> dat = da[:-1] >>> dat >>> mpos = [] >>> for i in range(len(dat)): if dat[i].startswith('>'): mpos.append(i) >>> mpos [0, 3, 6, 9] >>> for item in range(len(mpos)): start = mpos[item] enda = item+1 end ?= mpos[enda]-1 head = dat[start] block ?= dat[start+1:end] for i in block: print head+'\t'+i >X1A >X2A >X3A Traceback (most recent call last): ? File "", line 4, in ? ? end ?= mpos[enda]-1 IndexError: list index out of range >>>? By the time I am looping through last item, I do not have anything to take 1 from and thus end up with that indexerror.? Could anyone please help me how to get a good habit of making this work. ?This is a very wrong and bad habit.? thank you for your help in advance.? Hs. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 5 22:28:47 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 06 Feb 2013 08:28:47 +1100 Subject: [Tutor] Getting range of a list In-Reply-To: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> References: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> Message-ID: <5111798F.4040100@pearwood.info> On 06/02/13 08:08, Hs Hs wrote: > Here is what I do : >>>> f1 = open('test','r') >>>> da = f1.read().split('\n') >>>> dat = da[:-1] >>>> dat >>>> mpos = [] > >>>> for i in range(len(dat)): > if dat[i].startswith('>'): > mpos.append(i) > >>>> mpos > [0, 3, 6, 9] > >>>> for item in range(len(mpos)): > start = mpos[item] > enda = item+1 > end = mpos[enda]-1 > head = dat[start] > block = dat[start+1:end] > for i in block: > print head+'\t'+i You are thinking like a C programmer, not a Python programmer. You should almost never need to iterate over a range of numbers like this. Instead, try something like this: f = open('test') head = '----' for line in f: if line.startswith('>'): head = line[1:].rstrip() # remove trailing newline else: print head + '\t' + line f.close() In general, you should iterate over collections of data directly. For example: # WRONG for i in range(len(data)): x = data[i] print x # RIGHT for x in data: print x # WRONG for i in range(len(data)): x = data[i] if x == 'spam': data[i] = 'ham' # RIGHT for i, x in enumerate(data): if x == 'spam': data[i] = 'ham' Hope this helps. -- Steven From steve at pearwood.info Tue Feb 5 22:35:51 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 06 Feb 2013 08:35:51 +1100 Subject: [Tutor] Iterating a dict with an iteration counter? How would *you* do it? In-Reply-To: References: <510FEFC6.8030000@davea.name> <51103597.20105@davea.name> <511041B6.5010902@pearwood.info> <51104C77.6050200@davea.name> Message-ID: <51117B37.2090908@pearwood.info> On 05/02/13 22:27, Oscar Benjamin wrote: > On 5 February 2013 03:56, eryksun wrote: >> On Mon, Feb 4, 2013 at 7:04 PM, Dave Angel wrote: >>>> Nope, in both Python 2 and 3 iterating over a dict directly just >>>> provides the key. That's also how "if key in dict" works. >> >> A dict implements __contains__ for an efficient "in" test. In general, >> the interpreter falls back to using iteration if a type lacks >> __contains__. > > I almost wrote this response but then I realised that Dave probably > meant that "obj in dict" returns True if the dict has a key equal to > obj rather than if the dict has a (key, value) pair equal to obj. It was actually me, not Dave, and yes, that's what I meant. I didn't mean that dict containment tests were literally implemented by iterating over the keys checking each one in turn, since that would be horribly inefficient for something so critical as a dict. Although I can see why eryksun may have thought so, sorry for any confusion caused by my poor wording. Although note that Python does fallback on iteration for containment if you don't define a __contains__ method: py> class Test(object): ... def __getitem__(self, n): ... if n >= 5: raise IndexError ... return n + 100 ... py> t = Test() py> 3 in t False py> 103 in t True -- Steven From davea at davea.name Tue Feb 5 22:39:54 2013 From: davea at davea.name (Dave Angel) Date: Tue, 05 Feb 2013 16:39:54 -0500 Subject: [Tutor] Getting range of a list In-Reply-To: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> References: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> Message-ID: <51117C2A.403@davea.name> On 02/05/2013 04:08 PM, Hs Hs wrote: > > First comment: do NOT post in html, as it frequently messes up indenting. Send your email in text mode, as this is a text mailing list. Compounding that, you apparently are running inside some shell program (pyshell ?) which is doing a further mess. But even if you were running under the real interpreter, once you've got doubly nested loops, it gets really hard to read. > Dear List members: > > I always have problem in getting ranges: > > Following is my representation of part of my file. > >> X1 > A > G > C > G >> X2 > A > G >> X3 > A > G >> X4 > H > T > > > I want to print the above contents in the following way: > > X1 \t A > X1 \t G > X1 \t C > X1 \t G > X2 \t A > X2 \t G > X3 \t A > X3 \t G > X4 \t H > X4 \t H > > > Here is what I do >>>> f1 = open('test','r') >>>> da = f1.read().split('\n') Why not just use readlines() ? That's what it's for. >>>> dat = da[:-1] >>>> dat Your shell forgot to display dat here. >>>> mpos = [] > >>>> for i in range(len(dat)): > if dat[i].startswith('>'): > mpos.append(i) > >>>> mpos > [0, 3, 6, 9] > >>>> for item in range(len(mpos)): > start = mpos[item] > enda = item+1 > end = mpos[enda]-1 What is this line intended to do? enda is too big, so why are you surprised it will throw an exception last time through? > head = dat[start] > block = dat[start+1:end] > for i in block: > print head+'\t'+i > >> X1A >> X2A >> X3A > > Traceback (most recent call last): > File "", line 4, in > end = mpos[enda]-1 > IndexError: list index out of range >>>> > > > By the time I am looping through last item, I do not have anything to take 1 from and thus end up with that indexerror. > > Could anyone please help me how to get a good habit of making this work. This is a very wrong and bad habit. > > thank you for your help in advance. > > Hs. > > Your mpos list is an index of starting points for records in the dat array. But you're using it also as ending points, and you're missing the last one. The usual way to fix this is to append one more entry to mpos, that points just beyond the end of the list dat mpos.append(len(dat)) Once you do that,you'll have to change your next for-loop, so it uses the original length, perhaps like: for item in range(len(mpos))-1: That should get you closer to working. However, this whole program feels like it was transliterated from BASIC or maybe C. Any time you have to range(len(... as the list for a for loop, something's probably wrong. The entire program could be done much more elegantly. And now I can see Steven has posted such an improvement. -- DaveA From ilhs_hs at yahoo.com Tue Feb 5 22:48:10 2013 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 5 Feb 2013 13:48:10 -0800 (PST) Subject: [Tutor] Getting range of a list In-Reply-To: <5111798F.4040100@pearwood.info> References: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> <5111798F.4040100@pearwood.info> Message-ID: <1360100890.8386.YahooMailNeo@web163502.mail.gq1.yahoo.com> Thanks Steve.? But one question, when I print, I get extra empty lines. How to get rid of them! ?Thanks again. >>> f = open('test') >>> head = '---' >>> for line in f: if line.startswith('>'): head = line[1:].strip() else: print head+'\t'+line X1A ? ? ? ? ? ? ? ? ? ? ? ? <------ X1G ? ? ? ? ? ? ? ? ? ? ? ?<----- X2A X2G X3A X3G X4A X4A Thanks Hs. ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Tuesday, February 5, 2013 4:28 PM Subject: Re: [Tutor] Getting range of a list On 06/02/13 08:08, Hs Hs wrote: > Here is what I do : >>>> f1 = open('test','r') >>>> da = f1.read().split('\n') >>>> dat = da[:-1] >>>> dat >>>> mpos = [] > >>>> for i in range(len(dat)): > if dat[i].startswith('>'): > mpos.append(i) > >>>> mpos > [0, 3, 6, 9] > >>>> for item in range(len(mpos)): > start = mpos[item] > enda = item+1 > end? = mpos[enda]-1 > head = dat[start] > block? = dat[start+1:end] > for i in block: > print head+'\t'+i You are thinking like a C programmer, not a Python programmer. You should almost never need to iterate over a range of numbers like this. Instead, try something like this: f = open('test') head = '----' for line in f: ? ? if line.startswith('>'): ? ? ? ? head = line[1:].rstrip()? # remove trailing newline ? ? else: ? ? ? ? print head + '\t' + line f.close() In general, you should iterate over collections of data directly. For example: # WRONG for i in range(len(data)): ? ? x = data[i] ? ? print x # RIGHT for x in data: ? ? print x # WRONG for i in range(len(data)): ? ? x = data[i] ? ? if x == 'spam': ? ? ? ? data[i] = 'ham' # RIGHT for i, x in enumerate(data): ? ? if x == 'spam': ? ? ? ? data[i] = 'ham' Hope this helps. -- Steven _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Feb 5 23:20:39 2013 From: davea at davea.name (Dave Angel) Date: Tue, 05 Feb 2013 17:20:39 -0500 Subject: [Tutor] Getting range of a list In-Reply-To: <1360100890.8386.YahooMailNeo@web163502.mail.gq1.yahoo.com> References: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> <5111798F.4040100@pearwood.info> <1360100890.8386.YahooMailNeo@web163502.mail.gq1.yahoo.com> Message-ID: <511185B7.2070202@davea.name> On 02/05/2013 04:48 PM, Hs Hs wrote: > Thanks Steve. > > But one question, when I print, I get extra empty lines. How to get rid of them! Thanks again. >>>> f = open('test') >>>> head = '---' >>>> for line in f: line = line.rstrip() #get rid of the trailing newline (and any other whitespace there) > if line.startswith('>'): > head = line[1:].strip() > else: > print head+'\t'+line The print generates a newline by default. So you either have to do the strip() I suggested above, or use a trailing comma on the print. I recommend the former. > > X1A > <------ > X1G > <----- > X2A > > X2G > > X3A > > X3G > > X4A > > X4A > > Thanks > Hs. > > > You're still posting using html mail. And your indentation is still getting messed up. Also, you top-posted. -- DaveA From 3n2solutions at gmail.com Wed Feb 6 00:44:35 2013 From: 3n2solutions at gmail.com (3n2 Solutions) Date: Tue, 5 Feb 2013 15:44:35 -0800 Subject: [Tutor] help with running perl script that writes to a text file Message-ID: Hello, I want to automate the following manual process from DOS promp: c:/scripts/perl>perl fix.pl base.gtx >base.txt Here is my python script: path="c:/scripts/perl/" subprocess.call(['perl','fix.pl','base.gtx >base.txt',path]) I also tried this alternative: subprocess.Popen(['perl','fix.pl','base.gtx >base.txt',path]) #same result from this method. The above script generates the base.txt file but has no content in it. any ideas as to why the resulting text file is empty? Am I using the correct python commands to run the above manual process? I'm using python 2.7 on windows 7 Thanks, Tim From ilhs_hs at yahoo.com Wed Feb 6 00:59:39 2013 From: ilhs_hs at yahoo.com (Hs Hs) Date: Tue, 5 Feb 2013 15:59:39 -0800 (PST) Subject: [Tutor] Getting range of a list In-Reply-To: <511185B7.2070202@davea.name> References: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> <5111798F.4040100@pearwood.info> <1360100890.8386.YahooMailNeo@web163502.mail.gq1.yahoo.com> <511185B7.2070202@davea.name> Message-ID: <1360108779.79426.YahooMailNeo@web163503.mail.gq1.yahoo.com> Thanks Dave.? Sorry for html formatting. Honestly I don't know how to shut html formatting off in Yahoo. I don't have options for send in ('Tools|Options|''send''missing'). Will investigate.? thanks Hs ________________________________ From: Dave Angel To: tutor at python.org Sent: Tuesday, February 5, 2013 5:20 PM Subject: Re: [Tutor] Getting range of a list On 02/05/2013 04:48 PM, Hs Hs wrote: > Thanks Steve. > > But one question, when I print, I get extra empty lines. How to get rid of them!? Thanks again. >>>> f = open('test') >>>> head = '---' >>>> for line in f: line = line.rstrip()? ? #get rid of the trailing newline (and any other whitespace there) > if line.startswith('>'): > head = line[1:].strip() > else: > print head+'\t'+line The print generates a newline by default.? So you either have to do the strip() I suggested above, or use a trailing comma on the print.? I recommend the former. > > X1A >? ? ? ? ? ? ? ? ? ? ? ? ? <------ > X1G >? ? ? ? ? ? ? ? ? ? ? ? <----- > X2A > > X2G > > X3A > > X3G > > X4A > > X4A > > Thanks > Hs. > > > You're still posting using html mail.? And your indentation is still getting messed up.? Also, you top-posted. -- DaveA _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 6 01:47:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Feb 2013 00:47:52 +0000 Subject: [Tutor] Getting range of a list In-Reply-To: <1360108779.79426.YahooMailNeo@web163503.mail.gq1.yahoo.com> References: <1360098488.70316.YahooMailNeo@web163505.mail.gq1.yahoo.com> <5111798F.4040100@pearwood.info> <1360100890.8386.YahooMailNeo@web163502.mail.gq1.yahoo.com> <511185B7.2070202@davea.name> <1360108779.79426.YahooMailNeo@web163503.mail.gq1.yahoo.com> Message-ID: On 05/02/13 23:59, Hs Hs wrote: > Thanks Dave. > > Sorry for html formatting. Honestly I don't know how to shut html > formatting off in Yahoo. Create a new message. Look at the bar just below the subject box, it has some tabs in it. At the extreme right end there is a button marked Switch to Plain Text... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 6 01:52:46 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Feb 2013 00:52:46 +0000 Subject: [Tutor] help with running perl script that writes to a text file In-Reply-To: References: Message-ID: On 05/02/13 23:44, 3n2 Solutions wrote: > I want to automate the following manual process from DOS promp: > > c:/scripts/perl>perl fix.pl base.gtx >base.txt Use a DOS batch file, that's what they are there for. If you are not doing any other processing Python is inefficient and overkill for this task. Unless you just want to learn how to use Popen I suppose... > path="c:/scripts/perl/" > subprocess.call(['perl','fix.pl','base.gtx >base.txt',path]) Do you get any error messages on the console? How are you running the python script? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kangyangjae at gmail.com Wed Feb 6 10:48:10 2013 From: kangyangjae at gmail.com (Kang, Yang Jae) Date: Wed, 6 Feb 2013 18:48:10 +0900 Subject: [Tutor] regarding the list problem Message-ID: <15ba01ce044f\$1551e860\$3ff5b920\$@gmail.com> Hello I'm a beginner to python. I ran following code and expected [[1, 0], [0, 0], [0, 0]] However unexpected result came up. Anybody who can teach me why and how to solve? Python 3.2.3 (default, May 19 2012, 23:34:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [1] *3 [1, 1, 1] >>> [[0,0]]*3 [[0, 0], [0, 0], [0, 0]] >>> a = [[0,0]]*3 >>> a [[0, 0], [0, 0], [0, 0]] >>> a[0][0] += 1 >>> a [[1, 0], [1, 0], [1, 0]] Kang, Yang Jae Ph.D. Cropgenomics Lab. College of Agriculture and Life Science Seoul National University Korea -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Feb 6 11:12:54 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 06 Feb 2013 11:12:54 +0100 Subject: [Tutor] help with running perl script that writes to a text file References: Message-ID: 3n2 Solutions wrote: > Hello, > > I want to automate the following manual process from DOS promp: > > c:/scripts/perl>perl fix.pl base.gtx >base.txt > > Here is my python script: > > path="c:/scripts/perl/" > subprocess.call(['perl','fix.pl','base.gtx >base.txt',path]) > > I also tried this alternative: > > subprocess.Popen(['perl','fix.pl','base.gtx >base.txt',path]) #same > result from this method. > > The above script generates the base.txt file but has no content in it. > > any ideas as to why the resulting text file is empty? Am I using the > correct python commands to run the above manual process? I'm surprised that base.txt is generated at all, I'd expect fix.pl to look for a file named "base.gtx >base.txt" and complain when it doesn't find that. I think the following should work: with open("c:/scripts/perl/base.txt", "w") as f: subprocess.check_call( ["perl", "c:/scripts/perl/fix.pl", "c:/scripts/perl/base.gtx"], stdout=f) From eryksun at gmail.com Wed Feb 6 11:58:54 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 6 Feb 2013 05:58:54 -0500 Subject: [Tutor] help with running perl script that writes to a text file In-Reply-To: References: Message-ID: On Tue, Feb 5, 2013 at 6:44 PM, 3n2 Solutions <3n2solutions at gmail.com> wrote: > > I want to automate the following manual process from DOS promp: I agree with Peter's answer. I'd just like to add a generally useless and pedantic comment about the habit of saying "DOS prompt". The cmd shell is a Win32 console application, unlike DOS command.com. On 64-bit Windows there isn't even a virtual DOS machine (NTVDM) to run command.com. There, I feel better now. :) From hugo.yoshi at gmail.com Wed Feb 6 12:07:14 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 6 Feb 2013 11:07:14 +0000 Subject: [Tutor] regarding the list problem In-Reply-To: <15ba01ce044f\$1551e860\$3ff5b920\$@gmail.com> References: <15ba01ce044f\$1551e860\$3ff5b920\$@gmail.com> Message-ID: On Wed, Feb 6, 2013 at 9:48 AM, Kang, Yang Jae wrote: This line: > >>> a = [[0,0]]*3 > creates a list, a, which contains the list object [0, 0] three times. What's crucial to note is that it contains *the same object* three times, not three different objects with the same value. You can verify this yourself, with the id() function: >>> a = [[0,0]] * 3 >>> a [[0, 0], [0, 0], [0, 0]] >>> id(a[0]), id(a[1]), id(a[2]) (41087144, 41087144, 41087144) >>> All three have the same id, therefore all three point to one and the same object. > >>> a**** > > [[0, 0], [0, 0], [0, 0]]**** > > >>> a[0][0] += 1**** > > >>> a**** > > [[1, 0], [1, 0], [1, 0]] > It should not be so strange, now, that if you modify a[0], this modification will be reflected in a[1] and a[2] as well, since those are all the same object. Now, this can happen with lists, because they are mutable. If we do the same with integers: >>> a = [1] * 3 >>> a [1, 1, 1] >>> id(a[0]), id(a[1]), id(a[2]) (3779904, 3779904, 3779904) >>> a[0] += 1 >>> a [2, 1, 1] >>> You get the expected behaviour now, even though the list again contained the same object three times. This is because integers are *immutable*, meaning you cannot change them. So this line: >>> a[0] += 1 did not modify the object, but created another integer object, with value 2, and assigned that to a[0]. The conclusion is that you should always be mindful of whether your objects are mutable or not, and you should understand what actually happens when you multiply a list by a constant, to avoid these kinds of problems. In this case, what you wanted to do was create three list objects with value [0, 0], not just the one. You may either generate them with a loop or list comprehension, or simply write the list out in its entirety: >>> a = [[0,0] for i in range(3)] >>> id(a[0]), id(a[1]), id(a[2]) (4070896, 41087984, 41061792) >>> a = [[0, 0], [0, 0], [0, 0]] >>> id(a[0]), id(a[1]), id(a[2]) (41087944, 41087824, 41069624) >>> This way, the lists are actually three different lists and not just the same object three times (as you can see, they have different id's) HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From schooluse1992 at yahoo.com Wed Feb 6 14:44:33 2013 From: schooluse1992 at yahoo.com (Mara Kelly) Date: Wed, 6 Feb 2013 13:44:33 +0000 (GMT) Subject: [Tutor] recursive function password check Message-ID: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> Hi everyone, trying to write a program that has the user enter a password, checks if it contains any vowels, and if it does prints ' It is false that password(whatever the user enters) has no vowels,' and if it has no vowels prints it is True that password has no vowels... Here is what I have so far...def password(y):? ? vowels=["a","e","i","o"]? ? if y[0] in vowels:? ? ? ? return False? ? if len(y) ==0:? ? ? ? return True? ? elif(y[len(y)-1] != vowels):? ? ? ? return False? ? else:? ? ? ? return password(y[1:len(y)-1])x=input("Enter a password:")print("It is", password(x),"that",x,"has no vowles") As of now it just asks for the password, and then prints 'It is False that password(whatever was entered) has no vowles' for any word I enter. I think maybe some of my if statement conditions may be being returned to the function, but then not printing the appropriate one? Can anyone help? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Wed Feb 6 15:05:58 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 6 Feb 2013 14:05:58 +0000 Subject: [Tutor] recursive function password check In-Reply-To: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> References: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> Message-ID: On Wed, Feb 6, 2013 at 1:44 PM, Mara Kelly wrote: > Hi everyone, trying to write a program that has the user enter a password, > checks if it contains any vowels, and if it does prints ' It is false that > password(whatever the user enters) has no vowels,' and if it has no vowels > prints it is True that password has no vowels... > > Here is what I have so far... > def password(y): > vowels=["a","e","i","o"] > if y[0] in vowels: > return False > if len(y) ==0: > return True > elif(y[len(y)-1] != vowels): > return False > else: > return password(y[1:len(y)-1]) > x=input("Enter a password:") > print("It is", password(x),"that",x,"has no vowles") > > Okay, it looks to me like you are inspecting the first and last characters in the string, returning False if some condition is met for each, and otherwise you chop them off and call recursively on the resulting string. So here's a question for you: For the first character, you check if y[0] in vowels. But for the last character, you check if y[len(y) - 1] != vowels. Why did you use "in" for the first test, and "!=" for the second? By the way, here's a related tip: in Python, negative indexes will work from the back of the sequence. So y[-1] is the last element, y[-2] the second to last, et cetera. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From simonyan at fedoraproject.org Wed Feb 6 15:10:40 2013 From: simonyan at fedoraproject.org (Simon Yan) Date: Wed, 6 Feb 2013 22:10:40 +0800 Subject: [Tutor] recursive function password check In-Reply-To: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> References: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> Message-ID: On Wed, Feb 6, 2013 at 9:44 PM, Mara Kelly wrote: > Hi everyone, trying to write a program that has the user enter a password, > checks if it contains any vowels, and if it does prints ' It is false that > password(whatever the user enters) has no vowels,' and if it has no vowels > prints it is True that password has no vowels... > > Here is what I have so far... > def password(y): > vowels=["a","e","i","o"] > if y[0] in vowels: > return False > if len(y) ==0: > return True > elif(y[len(y)-1] != vowels): > return False > else: > return password(y[1:len(y)-1]) > x=input("Enter a password:") > print("It is", password(x),"that",x,"has no vowles") > > As of now it just asks for the password, and then prints 'It is False that > password(whatever was entered) has no vowles' for any word I enter. I think > maybe some of my if statement conditions may be being returned to the > function, but then not printing the appropriate one? Can anyone help? > Thanks! > It appears that the issue is from this: elif(y[len(y)-1] != vowels): This condition will be true because you are comparing a string with a list. Thus causing passwrod() returning False. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From Noriko.Tani at tomtom.com Wed Feb 6 15:26:04 2013 From: Noriko.Tani at tomtom.com (Noriko Tani) Date: Wed, 6 Feb 2013 14:26:04 +0000 Subject: [Tutor] recursive function password check In-Reply-To: References: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> Message-ID: <212470589DA172418D299284EFF478AB409ECADE@BESRVWP-EXM02.ttg.global> Hi Mara, Several suggestions: Put the password in a list, then loop each letter to check if it is a vowel like this password=[] vowels=['a','e','i','o','u'] #in your message, u is missing, BTW password=input("Enter a password:") for p in password: if p in vowels: return True #I would use print("the message that you want to display") though. else: return False And how about error handling? You put if len(y) ==0: return True #I would use print("woops! You did not enter anything.") and add break Does this password case sensitive? If so, add AEIOU in vowels list. Good luck! Noriko ________________________________ From: Tutor [mailto:tutor-bounces+noriko.tani=tomtom.com at python.org] On Behalf Of Simon Yan Sent: Wednesday, February 06, 2013 9:11 AM To: Mara Kelly Cc: tutor at python.org Subject: Re: [Tutor] recursive function password check On Wed, Feb 6, 2013 at 9:44 PM, Mara Kelly > wrote: Hi everyone, trying to write a program that has the user enter a password, checks if it contains any vowels, and if it does prints ' It is false that password(whatever the user enters) has no vowels,' and if it has no vowels prints it is True that password has no vowels... Here is what I have so far... def password(y): vowels=["a","e","i","o"] if y[0] in vowels: return False if len(y) ==0: return True elif(y[len(y)-1] != vowels): return False else: return password(y[1:len(y)-1]) x=input("Enter a password:") print("It is", password(x),"that",x,"has no vowles") As of now it just asks for the password, and then prints 'It is False that password(whatever was entered) has no vowles' for any word I enter. I think maybe some of my if statement conditions may be being returned to the function, but then not printing the appropriate one? Can anyone help? Thanks! It appears that the issue is from this: elif(y[len(y)-1] != vowels): This condition will be true because you are comparing a string with a list. Thus causing passwrod() returning False. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Regards, YeeYaa (Simon Yan) http://simonyan.fedorapeople.org/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Feb 6 15:46:39 2013 From: davea at davea.name (Dave Angel) Date: Wed, 06 Feb 2013 09:46:39 -0500 Subject: [Tutor] recursive function password check In-Reply-To: <212470589DA172418D299284EFF478AB409ECADE@BESRVWP-EXM02.ttg.global> References: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> <212470589DA172418D299284EFF478AB409ECADE@BESRVWP-EXM02.ttg.global> Message-ID: <51126CCF.8010105@davea.name> On 02/06/2013 09:26 AM, Noriko Tani wrote: > Hi Mara, > > Several suggestions: > > Put the password in a list, then loop each letter to check if it is a vowel like this No need to make it a list, strings are already iterable. And you don't make it a list in the code, just in the remark above. > > password=[] > vowels=['a','e','i','o','u'] #in your message, u is missing, BTW > password=input("Enter a password:") > > for p in password: This loop goes around exactly once, since you return no matter what. > if p in vowels: > return True #I would use print("the message that you want to display") though. Shouldn't mix "calculation" and "output" unless it's just for play. > else: > return False This return should be dedented to line up with the for statement, so it only executes if none of the earlier characters was a vowel. > > And how about error handling? You put > if len(y) ==0: > return True #I would use print("woops! You did not enter anything.") and add break But in the OP's code, this return is triggered on any string with no vowels. Note, the function is recursive, and this is the only final exit condition. > > Does this password case sensitive? If so, add AEIOU in vowels list. > > Good luck! > > Noriko > > ________________________________ > From: Tutor [mailto:tutor-bounces+noriko.tani=tomtom.com at python.org] On Behalf Of Simon Yan > Sent: Wednesday, February 06, 2013 9:11 AM > To: Mara Kelly > Cc: tutor at python.org > Subject: Re: [Tutor] recursive function password check > > > > On Wed, Feb 6, 2013 at 9:44 PM, Mara Kelly > wrote: > Hi everyone, trying to write a program that has the user enter a password, checks if it contains any vowels, and if it does prints ' It is false that password(whatever the user enters) has no vowels,' and if it has no vowels prints it is True that password has no vowels... > > Here is what I have so far... > def password(y): > vowels=["a","e","i","o"] > if y[0] in vowels: > return False > if len(y) ==0: > return True > elif(y[len(y)-1] != vowels): > return False > else: > return password(y[1:len(y)-1]) > x=input("Enter a password:") > print("It is", password(x),"that",x,"has no vowles") > > As of now it just asks for the password, and then prints 'It is False that password(whatever was entered) has no vowles' for any word I enter. I think maybe some of my if statement conditions may be being returned to the function, but then not printing the appropriate one? Can anyone help? Thanks! > > It appears that the issue is from this: > > elif(y[len(y)-1] != vowels): > > This condition will be true because you are comparing a string with a list. Thus causing passwrod() returning False. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Regards, > YeeYaa (Simon Yan) > > http://simonyan.fedorapeople.org/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- DaveA From davea at davea.name Wed Feb 6 15:53:52 2013 From: davea at davea.name (Dave Angel) Date: Wed, 06 Feb 2013 09:53:52 -0500 Subject: [Tutor] recursive function password check In-Reply-To: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> References: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> Message-ID: <51126E80.6090901@davea.name> On 02/06/2013 08:44 AM, Mara Kelly wrote: > Hi everyone, trying to write a program that has the user enter a password, checks if it contains any vowels, and if it does prints ' It is false that password(whatever the user enters) has no vowels,' and if it has no vowels prints it is True that password has no vowels... > Here is what I have so far...def password(y): vowels=["a","e","i","o"] if y[0] in vowels: return False if len(y) ==0: return True elif(y[len(y)-1] != vowels): return False else: return password(y[1:len(y)-1])x=input("Enter a password:")print("It is", password(x),"that",x,"has no vowles") > As of now it just asks for the password, and then prints 'It is False that password(whatever was entered) has no vowles' for any word I enter. I think maybe some of my if statement conditions may be being returned to the function, but then not printing the appropriate one? Can anyone help? Thanks! > > > Please don't post in html email. It can seriously mess up your columns. In your case, your email program didn't even try to provide a text version, so those of us who read text emails can't make much sense of it. Fortunately, I can decipher it by using someone else's reply. I quote that below: > def password(y): > vowels=["a","e","i","o"] You might want to include "u" in that list. And maybe the uppercase versions as well. > if y[0] in vowels: > return False > if len(y) ==0: > return True > elif(y[len(y)-1] != vowels): No, you want if y[-1] in vowels: instead. A string is never going to be equal to a list. > return False > else: > return password(y[1:len(y)-1]) > x=input("Enter a password:") > print("It is", password(x),"that",x,"has no vowles") I presume that making the function recursive was an explicit part of the assignment. -- DaveA From ramit.prasad at jpmorgan.com Wed Feb 6 17:31:12 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 6 Feb 2013 16:31:12 +0000 Subject: [Tutor] recursive function password check In-Reply-To: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> References: <1360158273.46601.YahooMailClassic@web171602.mail.ir2.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741815C8C8@SCACMX008.exchad.jpmchase.net> Mara Kelly wrote: > Hi everyone, trying to write a program that has the user enter a password, checks if it contains any vowels, and > if it does prints ' It is false that password(whatever the user enters) has no vowels,' and if it has no vowels > prints it is True that password has no vowels... > > Here is what I have so far... > def password(y): > ? ? vowels=["a","e","i","o"] > ? ? if y[0] in vowels: > ? ? ? ? return False > ? ? if len(y) ==0: > ? ? ? ? return True > ? ? elif(y[len(y)-1] != vowels): > ? ? ? ? return False > ? ? else: > ? ? ? ? return password(y[1:len(y)-1]) > x=input("Enter a password:") > print("It is", password(x),"that",x,"has no vowles") > > As of now it just asks for the password, and then prints 'It is False that password(whatever was entered) has no > vowles' for any word I enter. I think maybe some of my if statement conditions may be being returned to the > function, but then not printing the appropriate one? Can anyone help? Thanks! Why look at each character in the password? Unless you have a very short password it will be more inefficient than looking for the vowels. Also, if you lowercase the incoming password then you can avoid looking for uppercase vowels. Note: if you have to deal with international character sets (code pages) then you might not want to lower. If you did not understand the previous statement, then chances are it does not apply to you. :) I will leave the following code snippet with you to adapt into your program. y = y.lower() if vowel in y: return False This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From alan.gauld at btinternet.com Wed Feb 6 18:47:19 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Feb 2013 17:47:19 +0000 Subject: [Tutor] help with running perl script that writes to a text file In-Reply-To: References: Message-ID: On 06/02/13 10:58, eryksun wrote: > and pedantic comment about the habit of saying "DOS prompt". The cmd > shell is a Win32 console application, unlike DOS command.com. Yes, but the problem is that Windows now has so many command prompts (cscript, cmd, power shell etc) that "the Windows prompt" would be meaningless and "the cmd prompt" too awkward to say, so "the DOS prompt" is both traditional and sufficiently specific making it the most easily understandable of the likely terms. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Wed Feb 6 19:12:16 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 06 Feb 2013 13:12:16 -0500 Subject: [Tutor] regarding the list problem In-Reply-To: <15ba01ce044f\$1551e860\$3ff5b920\$@gmail.com> References: <15ba01ce044f\$1551e860\$3ff5b920\$@gmail.com> Message-ID: <51129D00.4020708@gmail.com> http://www.pythontutor.com/visualize.html is very helpful. Enter your code, click Visualize Execution, then click forward. -- Bob Gailer 919-636-4239 Chapel Hill NC From 3n2solutions at gmail.com Wed Feb 6 23:02:27 2013 From: 3n2solutions at gmail.com (3n2 Solutions) Date: Wed, 6 Feb 2013 14:02:27 -0800 Subject: [Tutor] Tutor Digest, Vol 108, Issue 22 In-Reply-To: References: Message-ID: On Wed, Feb 6, 2013 at 3:00 AM, 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: help with running perl script that writes to a text file > (Peter Otten) > 2. Re: help with running perl script that writes to a text file > (eryksun) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 06 Feb 2013 11:12:54 +0100 > From: Peter Otten <__peter__ at web.de> > To: tutor at python.org > Subject: Re: [Tutor] help with running perl script that writes to a > text file > Message-ID: > Content-Type: text/plain; charset="ISO-8859-1" > > 3n2 Solutions wrote: > >> Hello, >> >> I want to automate the following manual process from DOS promp: >> >> c:/scripts/perl>perl fix.pl base.gtx >base.txt >> >> Here is my python script: >> >> path="c:/scripts/perl/" >> subprocess.call(['perl','fix.pl','base.gtx >base.txt',path]) >> >> I also tried this alternative: >> >> subprocess.Popen(['perl','fix.pl','base.gtx >base.txt',path]) #same >> result from this method. >> >> The above script generates the base.txt file but has no content in it. >> >> any ideas as to why the resulting text file is empty? Am I using the >> correct python commands to run the above manual process? > > I'm surprised that base.txt is generated at all, I'd expect fix.pl to look > for a file named "base.gtx >base.txt" and complain when it doesn't find > that. > > I think the following should work: > > with open("c:/scripts/perl/base.txt", "w") as f: > subprocess.check_call( > ["perl", > "c:/scripts/perl/fix.pl", > "c:/scripts/perl/base.gtx"], > stdout=f) > > Peter, that did it! Thank you. From sunil.techspk at gmail.com Thu Feb 7 07:09:52 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Thu, 7 Feb 2013 11:39:52 +0530 Subject: [Tutor] If a method has no return type? Message-ID: If a method has no return type? what will it return? -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Feb 7 07:32:22 2013 From: wescpy at gmail.com (wesley chun) Date: Thu, 7 Feb 2013 00:32:22 -0600 Subject: [Tutor] If a method has no return type? In-Reply-To: References: Message-ID: On Thu, Feb 7, 2013 at 12:09 AM, Sunil Tech wrote: > If a method has no return type? > what will it return? > note the original question is partially invalid... Python functions and methods aren't typed. however, i imagine the OP really meant *return value* instead, so the answer is really the following: functions *and* methods with no explicit return *value* return None... this happens when you either have no return statement or just return by itself with no object given. one exception is __init__()... you're never supposed to return anything from it... ever. i can't think of any others... can you? best regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From swordangel at gmail.com Thu Feb 7 07:37:55 2013 From: swordangel at gmail.com (Kal Sze) Date: Thu, 7 Feb 2013 14:37:55 +0800 Subject: [Tutor] If a method has no return type? In-Reply-To: References: Message-ID: Dear Sunil, No method or function in Python has a *static* return type. That's because Python is by nature a dynamic language, with duck typing and dynamic dispatch. In fact, any method or function may well return any of a number of different types: def crazy_function(return_int) if return_int: return 1 else: return 'foo' It's probably bad design, but there is nothing in the Python grammar and semantics that stops you from doing that. So your question is better phrased as: if I don't explicitly return anything, what is returned? The answer to that would be: the None object Cheers, Kal On 7 February 2013 14:09, Sunil Tech wrote: > If a method has no return type? > what will it return? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From eryksun at gmail.com Thu Feb 7 07:48:56 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 7 Feb 2013 01:48:56 -0500 Subject: [Tutor] help with running perl script that writes to a text file In-Reply-To: References: Message-ID: On Wed, Feb 6, 2013 at 12:47 PM, Alan Gauld wrote: > so "the DOS prompt" is both traditional and sufficiently specific making it > the most easily understandable of the likely terms. "DOS prompt" is a common idiom, but it bears mentioning now and then that the OS is NT [1], not DOS. That's all; I know I'm being pedantic. Officially the Windows command-line shell is called the "command prompt". I call it the shell [2] or command line. Unless someone says PowerShell or 4NT, I assume it's cmd. [1] Windows 8 is NT 6.2.9200 [2] Not the GUI shell, Explorer, which is set here: HKLM\Software\Microsoft\Windows NT\CurrentVersion\WinLogon\Shell From sunil.techspk at gmail.com Thu Feb 7 10:09:07 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Thu, 7 Feb 2013 14:39:07 +0530 Subject: [Tutor] If a method has no return type? In-Reply-To: References: Message-ID: Thank you Wesley, Kal & tutor On Thu, Feb 7, 2013 at 12:07 PM, Kal Sze wrote: > Dear Sunil, > > No method or function in Python has a *static* return type. That's > because Python is by nature a dynamic language, with duck typing and > dynamic dispatch. In fact, any method or function may well return any > of a number of different types: > > def crazy_function(return_int) > if return_int: > return 1 > else: > return 'foo' > > It's probably bad design, but there is nothing in the Python grammar > and semantics that stops you from doing that. > > So your question is better phrased as: if I don't explicitly return > anything, what is returned? > > The answer to that would be: the None object > > Cheers, > Kal > > On 7 February 2013 14:09, Sunil Tech wrote: > > If a method has no return type? > > what will it return? > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Feb 7 10:58:34 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 07 Feb 2013 20:58:34 +1100 Subject: [Tutor] If a method has no return type? In-Reply-To: References: Message-ID: <51137ACA.3080509@pearwood.info> On 07/02/13 17:32, wesley chun wrote: > On Thu, Feb 7, 2013 at 12:09 AM, Sunil Tech wrote: > >> If a method has no return type? >> what will it return? >> > > note the original question is partially invalid... Python functions and > methods aren't typed. however, i imagine the OP really meant *return value* > instead, so the answer is really the following: > functions *and* methods with no explicit return *value* return None... this > happens when you either have no return statement or just return by itself > with no object given. > > one exception is __init__()... you're never supposed to return anything > from it... ever. i can't think of any others... can you? In-place modification methods typically return None. Functions and methods intended to operate as procedures, or via side-effect, also typically return None: list.sort list.reverse list.append list.extend dict.clear dict.update set.clear set.update __delitem__ __setitem__ _delattr__ __setattr__ random.shuffle file.close print # Python 3 only But as far as I know, __init__ is the only one which actually enforces the rule that it returns None, at least in Python 3.3. -- Steven From timomlists at gmail.com Thu Feb 7 11:25:13 2013 From: timomlists at gmail.com (Timo) Date: Thu, 07 Feb 2013 11:25:13 +0100 Subject: [Tutor] If a method has no return type? In-Reply-To: References: Message-ID: <51138109.60006@gmail.com> Op 07-02-13 10:09, Sunil Tech schreef: > Thank you Wesley, Kal & tutor In the future, the Python interpreter comes in handy for quick checks. >>> def spam(): ... pass ... >>> s = spam() >>> s, repr(s), type(s) (None, 'None', ) Timo > > > On Thu, Feb 7, 2013 at 12:07 PM, Kal Sze > wrote: > > Dear Sunil, > > No method or function in Python has a *static* return type. That's > because Python is by nature a dynamic language, with duck typing and > dynamic dispatch. In fact, any method or function may well return any > of a number of different types: > > def crazy_function(return_int) > if return_int: > return 1 > else: > return 'foo' > > It's probably bad design, but there is nothing in the Python grammar > and semantics that stops you from doing that. > > So your question is better phrased as: if I don't explicitly return > anything, what is returned? > > The answer to that would be: the None object > > Cheers, > Kal > > On 7 February 2013 14:09, Sunil Tech > wrote: > > If a method has no return type? > > what will it return? > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From Yogesh.M.Pai at tektronix.com Fri Feb 8 10:06:11 2013 From: Yogesh.M.Pai at tektronix.com (Pai, Yogesh M) Date: Fri, 8 Feb 2013 09:06:11 +0000 Subject: [Tutor] How to log process handles and GDI objects in python Message-ID: Hi, I would like to know how can I log system process handles and GDI objects for debugging memory leak issues in python. I would like to log these inside a loop (stress test) to check if my application leaks handles and plot them later for my usage. Can you suggest any built in libraries that can help in this task? Thanks, ypai -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 8 12:31:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 08 Feb 2013 11:31:59 +0000 Subject: [Tutor] How to log process handles and GDI objects in python In-Reply-To: References: Message-ID: On 08/02/13 09:06, Pai, Yogesh M wrote: > I would like to know how can I log system process handles and GDI > objects for debugging memory leak issues in python. This isn't really a question about learning Python so probably would be better on the main Python mailing list. However it will help if you specify things like the OS, the Python version. Also be clear about what exactly you mean by process handles and GDI objects. I'm guessing you are talking about Windows but I can't be sure. > I would like to log these inside a loop (stress test) to check if my > application leaks handles and plot them later for my usage. I imagine that means you are creating a test lop that creates and releases these handles? How do you get a handle? can you store it as a variable? can you print it? can you create a string and print that? Sorry I can't be of more help but that's a fairly open question about a very specific problem. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jf_byrnes at comcast.net Sat Feb 9 03:02:59 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 08 Feb 2013 20:02:59 -0600 Subject: [Tutor] Which pip for Ubuntu 12.04 Message-ID: How important is it to have the latest pip installed? Initially I want to use it to install the latest pymongo driver for mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. I see on http://www.pip-installer.org/en/latest/ the version is 1.2.1. It certainly would be easier to install from the repositories but will that version work to install the latest python packages? Thanks, Jim From neubyr at gmail.com Sat Feb 9 08:01:37 2013 From: neubyr at gmail.com (neubyr) Date: Sat, 9 Feb 2013 01:01:37 -0600 Subject: [Tutor] classes : post-declaration attributes Message-ID: I am learning Python 2.7 classes and objects. It seems like attributes (data attributes and methods) can be added to a class/object even after it's first declaration. For example, ``` class A(object): def __init__(self,arg): self.val1 = arg a = A(1) print a.val1 ``` Now another data attribute val2 can be added as: ``` a.val2 = 2 A.val2 = 22 ``` I understand that all attributes are stored in a dictionary, but I am not following when adding an attribute after initial declaration approach should be used. The official documentation also suggests that valid attributes are all the names present when the class object was created [1]. So does it mean post-declaration attributes are invalid? Why are they allowed to be created then (any special use cases/examples)? 1. http://docs.python.org/2/tutorial/classes.html -- thanks, N -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Sat Feb 9 08:22:33 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 09 Feb 2013 02:22:33 -0500 Subject: [Tutor] classes : post-declaration attributes In-Reply-To: References: Message-ID: <5115F939.2030008@lightbird.net> On 02/09/2013 02:01 AM, neubyr wrote: > > I am learning Python 2.7 classes and objects. It seems like attributes (data attributes and methods) can be added to a class/object even after it's first declaration. For example, > > ``` > class A(object): > def __init__(self,arg): > self.val1 = arg > > a = A(1) > print a.val1 > ``` > > Now another data attribute val2 can be added as: > ``` > a.val2 = 2 > A.val2 = 22 > ``` > > I understand that all attributes are stored in a dictionary, but I am not following when adding an attribute after initial declaration approach should be used. The official documentation also suggests that valid attributes are all the names present when the class object was created [1]. So does it mean post-declaration attributes are invalid? Why are they allowed to be created then (any special use cases/examples)? > > 1. http://docs.python.org/2/tutorial/classes.html > > -- > thanks, > N > What is meant there is that without any additional assignments, those attributes will be valid, I think. You can assign attributes at a later time if they don't exist at the time class is defined, or even if it's just more convenient for your needs. E.g. you can simply store some values in instance attributes at various points in your program. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Fanaticism consists of redoubling your effort when you have forgotten your aim. George Santayana From steve at pearwood.info Sat Feb 9 08:41:53 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 09 Feb 2013 18:41:53 +1100 Subject: [Tutor] classes : post-declaration attributes In-Reply-To: References: Message-ID: <5115FDC1.5090200@pearwood.info> On 09/02/13 18:01, neubyr wrote: > I understand that all attributes are stored in a dictionary, but I am not > following when adding an attribute after initial declaration approach > should be used. The official documentation also suggests that valid > attributes are all the names present when the class object was created [1]. > So does it mean post-declaration attributes are invalid? Why are they > allowed to be created then (any special use cases/examples)? > > 1. http://docs.python.org/2/tutorial/classes.html No, they are not invalid, merely unusual. Normally you will create all the instance attributes you expect when you initialise the instance: class MyClass: def __init__(self, spam, ham): self.spam = spam self.ham = ham That simply makes it easier to program the class -- you don't have to worry about coding for the case that instance.spam doesn't exist yet, because it will be set when the instance is created. But sometimes you might want to add an extra, optional, attribute to an instance after it is already initialised: instance.eggs = 12 or delete an attribute: del instance.ham # No ham for you! It's your class, you can do whatever you like to it, but it's your responsibility if you break it. However, note that built-in types like int, str, list etc. do *not* allow this dynamic adding and deleting of attributes. Most builtins don't have a __dict__, in order to be as small as possible. One of the exceptions are functions, and I sometimes add attributes to functions: def spam(n): return "spam"*n spam.surprise = 'NOBODY expects the Spanish Inquisition!' Obviously that's a toy example, but I have done it in real code a few times. -- Steven From alan.gauld at btinternet.com Sat Feb 9 10:24:47 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 09 Feb 2013 09:24:47 +0000 Subject: [Tutor] classes : post-declaration attributes In-Reply-To: References: Message-ID: On 09/02/13 07:01, neubyr wrote: > > I am learning Python 2.7 classes and objects. It seems like attributes > (data attributes and methods) can be added to a class/object even after > it's first declaration. For example, You can do that, but mostly you shouldn't. Usually when classes/objects are used like that its where the object is just being used as a data container rather than a true object (with behaviour and supporting data). Often a straight dictionary is a better option. Python allows us lots of freedom in how we use it with many unusual features. Not all of those things are advisable to use in day to day programming. But very occasionally you find a case where they help. In general, beginners should avoid them. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Sat Feb 9 12:46:14 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 9 Feb 2013 03:46:14 -0800 (PST) Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: References: Message-ID: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> ----- Original Message ----- > From: Jim Byrnes > To: tutor at python.org > Cc: > Sent: Saturday, February 9, 2013 3:02 AM > Subject: [Tutor] Which pip for Ubuntu 12.04 > > How important is it to have the latest pip installed? > > Initially I want to use it to install the latest pymongo driver for mongoDB.? > The pip version in the Ubuntu 12.04 repositories is 1.0.1. I see on > http://www.pip-installer.org/en/latest/ the version is 1.2.1. > > It certainly would be easier to install from the repositories but will that > version work to install the latest python packages? > > Thanks,? Jim You could just try it? And downloading it and then doing sudo tar -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is it? But you're right, I also nnoticed that the Canonical repositories are a little outdated sometimes. Would be nice if it's possible to add pypi.org, so updating would be easier. Albert-Jan From fomcl at yahoo.com Sat Feb 9 12:47:00 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 9 Feb 2013 03:47:00 -0800 (PST) Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: References: Message-ID: <1360410420.21795.YahooMailNeo@web163805.mail.gq1.yahoo.com> > How important is it to have the latest pip installed? > > Initially I want to use it to install the latest pymongo driver for mongoDB.? > The pip version in the Ubuntu 12.04 repositories is 1.0.1. I see on > http://www.pip-installer.org/en/latest/ the version is 1.2.1. > > It certainly would be easier to install from the repositories but will that > version work to install the latest python packages? > > Thanks,? Jim (sorry, tar -xvf .... me and my big fingers ;-)) From ghasemmg01 at leedslearning.net Sat Feb 9 20:04:58 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Sat, 9 Feb 2013 19:04:58 +0000 Subject: [Tutor] python help! Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D8379478E@LLN-SPP-ES-04.user01.lln.local> Hi guys can you tell me what is wrong with the second part of this code(elif choice == '2'). When I type something other than 0-255, it correctly asks again for an input but when I enter a number from 0-255 it does nothing : def show_menu(): print("=======================") print("1-binary to denary") print("2-denary to binary") print("3-exit") print("=======================") while True: show_menu() choice = input("please enter an option: ") if choice == '1': binary = input("Please enter a binary number: ") denary = 0 place_value = 1 for i in binary [::-1]: denary += place_value * int(i) place_value *= 2 print("The result is",denary) elif choice == '2': denary2 = int(input("Please enter a denary number: ")) remainder = '' while denary2 not in range(0,256): denary2 = int(input("Please enter a denary number: ")) continue while denary2 in range(0,256): remainder = str(denary2 % 2) + remainder denary2 >>= 1 print("The result is",remainder) elif choice == '3': break elif choice not in '1' or '2' or '3': print("Invalid input-try again!") From __peter__ at web.de Sat Feb 9 20:20:31 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 09 Feb 2013 20:20:31 +0100 Subject: [Tutor] python help! References: <010FB2F3C55002408EE1404538D1B6AE030D8379478E@LLN-SPP-ES-04.user01.lln.local> Message-ID: Ghadir Ghasemi wrote: > Hi guys can you tell me what is wrong with the second part of this > code(elif choice == '2'). When I type something other than 0-255, it > correctly asks again for an input but when I enter a number from 0-255 it > does nothing : It doesn't do nothing, it keeps running the while loop. Add a print() call > elif choice == '2': > denary2 = int(input("Please enter a denary number: ")) > remainder = '' > while denary2 not in range(0,256): > denary2 = int(input("Please enter a denary number: ")) > continue > while denary2 in range(0,256): print("XXX denary2 =", denary2) > remainder = str(denary2 % 2) + remainder > denary2 >>= 1 > print("The result is",remainder) to see what's happening. From neubyr at gmail.com Sat Feb 9 21:04:25 2013 From: neubyr at gmail.com (neubyr) Date: Sat, 9 Feb 2013 14:04:25 -0600 Subject: [Tutor] classes : post-declaration attributes In-Reply-To: References: Message-ID: On Sat, Feb 9, 2013 at 3:24 AM, Alan Gauld wrote: > On 09/02/13 07:01, neubyr wrote: > >> >> I am learning Python 2.7 classes and objects. It seems like attributes >> (data attributes and methods) can be added to a class/object even after >> it's first declaration. For example, >> > > You can do that, but mostly you shouldn't. > > Usually when classes/objects are used like that its where the object is > just being used as a data container rather than a true object (with > behaviour and supporting data). Often a straight dictionary is a better > option. > > Python allows us lots of freedom in how we use it with many unusual > features. Not all of those things are advisable to use in day to day > programming. But very occasionally you find a case where they help. > In general, beginners should avoid them. > > > Thanks for the reply Alan, Steven and Mitya. That's helpful. -- N -------------- next part -------------- An HTML attachment was scrubbed... URL: From mannkann5 at gmail.com Sun Feb 10 02:00:32 2013 From: mannkann5 at gmail.com (mann kann) Date: Sat, 9 Feb 2013 20:00:32 -0500 Subject: [Tutor] Code to open a website Message-ID: Dear Jedi, I wrote my first program but it doesn't open a website as I intended it to. Please correct my mistake. Sincerely, Mann def a(): import urllib.request url = "http://www.google.com" response = urllib.request.urlopen(url) g = input("Please enter y or n to go to youtube : ") if g == "y": print("Opening the website") a() else: print("kein website") exit() -------------- next part -------------- An HTML attachment was scrubbed... URL: From wayne at waynewerner.com Sun Feb 10 02:17:23 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Sat, 9 Feb 2013 19:17:23 -0600 (CST) Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: On Sat, 9 Feb 2013, mann kann wrote: > Dear Jedi,? > I wrote my first program but it doesn't open a website as I intended it to. > Please correct my mistake.? > > Sincerely,? > Mann You'll actually want the webbrowser module, which will open the links in your web browser - at least if you want to load sites like YouTube. HTH, Wayne From mannkann5 at gmail.com Sun Feb 10 02:25:35 2013 From: mannkann5 at gmail.com (mann kann) Date: Sat, 9 Feb 2013 20:25:35 -0500 Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: I used webbrowser and it worked via terminal, but the same code returns AttrituteError: 'module' object has no attribute 'open' in komodo edit. suggestions? here's the code: import webbrowser webbrowser.open("http://youtube.com") On Sat, Feb 9, 2013 at 8:17 PM, Wayne Werner wrote: > On Sat, 9 Feb 2013, mann kann wrote: > > Dear Jedi, >> I wrote my first program but it doesn't open a website as I intended it >> to. >> Please correct my mistake. >> >> Sincerely, >> Mann >> > > You'll actually want the webbrowser module, which will open the links in > your web browser - at least if you want to load sites like YouTube. > > HTH, > Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 10 02:33:35 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Feb 2013 01:33:35 +0000 Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: On 10/02/13 01:00, mann kann wrote: > Dear Jedi, > > I wrote my first program but it doesn't open a website as I intended it > to. Please correct my mistake. Well, how did you intend it to? It looks like it probably does open the web site, but it will be hard to tell since you do nothing with the result. > def a(): Please use meaningful names. openURL() or similar would be a useful choice here. > import urllib.request > url = "http://www.google.com" > response = urllib.request.urlopen(url) Here you open the url and store the response. But then the function ends and it gets thrown away and the site is closed again. > g = input("Please enter y or n to go to youtube : ") You aren't going to YouTube yet, only Google but I assume YouTube is the intended eventual target? Again g is not a very meaningful name. 'choice' or similar would be more helpful. > if g == "y": > print("Opening the website") > a() Here you call you function but again all the action inside is just lost. > else: > print("kein website") > exit() Where does exit() come from? Usually its from sys but you don't import from sys anywhere... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dvnsarma at gmail.com Sun Feb 10 02:36:14 2013 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Sun, 10 Feb 2013 07:06:14 +0530 Subject: [Tutor] python help! In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE030D8379478E@LLN-SPP-ES-04.user01.lln.local> Message-ID: I have altered the program to run on Python 2.7.3 Perhaps it will run on Python 3 with small/or no alterations. def show_menu(): print("=======================") print("1-binary to denary") print("2-denary to binary") print("3-exit") print("=======================") while True: show_menu() choice = raw_input("please enter an option: ") if choice == '1': binary = raw_input("Please enter a binary number: ") denary = 0 place_value = 1 for i in binary [::-1]: denary += place_value * int(i) place_value *= 2 print("The result is",denary) elif choice == '2': denary2 = int(raw_input("Please enter a denary number: ")) remainder = '' if denary2 not in range(0,256): denary2 = int(input("Please enter a denary number: ")) continue while denary2 > 0: remainder = str(denary2 % 2) + remainder denary2 /= 2 print("The result is",remainder) elif choice == '3': break elif choice == '1' or choice == '2' or choice == '3': print("Invalid input-try again!") On Sun, Feb 10, 2013 at 12:50 AM, Peter Otten <__peter__ at web.de> wrote: > Ghadir Ghasemi wrote: > > > Hi guys can you tell me what is wrong with the second part of this > > code(elif choice == '2'). When I type something other than 0-255, it > > correctly asks again for an input but when I enter a number from 0-255 it > > does nothing : > > It doesn't do nothing, it keeps running the while loop. Add a print() call > > > elif choice == '2': > > denary2 = int(input("Please enter a denary number: ")) > > remainder = '' > > while denary2 not in range(0,256): > > denary2 = int(input("Please enter a denary number: ")) > > continue > > while denary2 in range(0,256): > > print("XXX denary2 =", denary2) > > > remainder = str(denary2 % 2) + remainder > > denary2 >>= 1 > > print("The result is",remainder) > > to see what's happening. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- regards, Sarma. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dvnsarma at gmail.com Sun Feb 10 02:47:24 2013 From: dvnsarma at gmail.com (=?UTF-8?B?RC5WLk4uU2FybWEg4LCh4LC/LuCwteCwvy7gsI7gsKjgsY0u4LC24LCw4LGN4LCu?=) Date: Sun, 10 Feb 2013 07:17:24 +0530 Subject: [Tutor] python help! In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE030D8379478E@LLN-SPP-ES-04.user01.lln.local> Message-ID: Remove also 'continue' statement under the 'if denary2 not in range(0,256)' clause. On Sun, Feb 10, 2013 at 7:06 AM, D.V.N.Sarma ??.??.???.???? < dvnsarma at gmail.com> wrote: > I have altered the program to run on Python 2.7.3 > Perhaps it will run on Python 3 with small/or no alterations. > > def show_menu(): > print("=======================") > print("1-binary to denary") > print("2-denary to binary") > print("3-exit") > print("=======================") > > > while True: > show_menu() > > choice = raw_input("please enter an option: ") > > if choice == '1': > binary = raw_input("Please enter a binary number: ") > denary = 0 > place_value = 1 > > for i in binary [::-1]: > denary += place_value * int(i) > place_value *= 2 > > print("The result is",denary) > > > elif choice == '2': > denary2 = int(raw_input("Please enter a denary number: ")) > remainder = '' > if denary2 not in range(0,256): > denary2 = int(input("Please enter a denary number: ")) > continue > while denary2 > 0: > remainder = str(denary2 % 2) + remainder > denary2 /= 2 > print("The result is",remainder) > > > > > elif choice == '3': break > > > elif choice == '1' or choice == '2' or choice == '3': > print("Invalid input-try again!") > > > > On Sun, Feb 10, 2013 at 12:50 AM, Peter Otten <__peter__ at web.de> wrote: > >> Ghadir Ghasemi wrote: >> >> > Hi guys can you tell me what is wrong with the second part of this >> > code(elif choice == '2'). When I type something other than 0-255, it >> > correctly asks again for an input but when I enter a number from 0-255 >> it >> > does nothing : >> >> It doesn't do nothing, it keeps running the while loop. Add a print() call >> >> > elif choice == '2': >> > denary2 = int(input("Please enter a denary number: ")) >> > remainder = '' >> > while denary2 not in range(0,256): >> > denary2 = int(input("Please enter a denary number: ")) >> > continue >> > while denary2 in range(0,256): >> >> print("XXX denary2 =", denary2) >> >> > remainder = str(denary2 % 2) + remainder >> > denary2 >>= 1 >> > print("The result is",remainder) >> >> to see what's happening. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > regards, > Sarma. > -- regards, Sarma. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sun Feb 10 04:40:06 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 9 Feb 2013 22:40:06 -0500 Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: On Sat, Feb 9, 2013 at 8:33 PM, Alan Gauld wrote: > > Where does exit() come from? Usually its from sys but you > don't import from sys anywhere... site.py adds the exit/quit Quitter instances to builtins (2.x __builtin__). When called they raise SystemExit, like sys.exit does. Since you can bypass importing site.py with the -S flag, it's better to use sys.exit. From dyoo at hashcollision.org Sun Feb 10 05:55:41 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 9 Feb 2013 21:55:41 -0700 Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: On Sat, Feb 9, 2013 at 6:25 PM, mann kann wrote: > I used webbrowser and it worked via terminal, but the same code returns > AttrituteError: 'module' object has no attribute 'open' in komodo edit. > suggestions? here's the code: > > import webbrowser > webbrowser.open("http://youtube.com") What's the file name of your program, just out of curiosity? From mannkann5 at gmail.com Sun Feb 10 06:32:35 2013 From: mannkann5 at gmail.com (mann kann) Date: Sun, 10 Feb 2013 00:32:35 -0500 Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: oh wow, I foolishly named it webbrowser.py earlier. Thanks for the witty hint, Danny :) On Sat, Feb 9, 2013 at 11:55 PM, Danny Yoo wrote: > On Sat, Feb 9, 2013 at 6:25 PM, mann kann wrote: > > I used webbrowser and it worked via terminal, but the same code returns > > AttrituteError: 'module' object has no attribute 'open' in komodo edit. > > suggestions? here's the code: > > > > import webbrowser > > webbrowser.open("http://youtube.com") > > > What's the file name of your program, just out of curiosity? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 10 09:39:25 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 10 Feb 2013 08:39:25 +0000 (GMT) Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: <1360485565.67804.YahooMailNeo@web186006.mail.ir2.yahoo.com> >site.py adds the exit/quit Quitter instances to builtins (2.x >__builtin__). When called they raise SystemExit, like sys.exit does. So it does. You learn something new every day... When did that first happen? It was one of my biggest frustrations? with Python when I first started learning, that you couldn't call exit without first importing sys (v1.3). But I never noticed that changing? till now. Alan G From fomcl at yahoo.com Sun Feb 10 10:17:10 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 10 Feb 2013 01:17:10 -0800 (PST) Subject: [Tutor] Code to open a website In-Reply-To: References: Message-ID: <1360487830.28294.YahooMailNeo@web163803.mail.gq1.yahoo.com> > On Sat, Feb 9, 2013 at 8:33 PM, Alan Gauld > wrote: >> >> Where does exit() come from? Usually its from sys but you >> don't import from sys anywhere... > > site.py adds the exit/quit Quitter instances to builtins (2.x > __builtin__). When called they raise SystemExit, like sys.exit does. > Since you can bypass importing site.py with the -S flag, it's better > to use sys.exit. Maybe the OP meant to say 'quit()' ? That does not require an import. From alan.gauld at btinternet.com Sun Feb 10 10:25:35 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 10 Feb 2013 09:25:35 +0000 (GMT) Subject: [Tutor] Code to open a website In-Reply-To: <1360487830.28294.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1360487830.28294.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <1360488335.4141.YahooMailNeo@web186005.mail.ir2.yahoo.com> > Maybe the OP meant to say 'quit()' ? That does not require an import. Ooh! another option I didn't know about! So many ways to get rid of Python and here's me been importing sys? or raising SystemExit all these years... :-) Alan G. From __peter__ at web.de Sun Feb 10 10:35:01 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Feb 2013 10:35:01 +0100 Subject: [Tutor] Code to open a website References: <1360487830.28294.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1360488335.4141.YahooMailNeo@web186005.mail.ir2.yahoo.com> Message-ID: ALAN GAULD wrote: >> Maybe the OP meant to say 'quit()' ? That does not require an import. > > > Ooh! another option I didn't know about! > So many ways to get rid of Python and here's me been importing sys > or raising SystemExit all these years... :-) I tend to use none of these and my scripts still terminate ;) From eryksun at gmail.com Sun Feb 10 10:30:30 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 10 Feb 2013 04:30:30 -0500 Subject: [Tutor] Code to open a website In-Reply-To: <1360485565.67804.YahooMailNeo@web186006.mail.ir2.yahoo.com> References: <1360485565.67804.YahooMailNeo@web186006.mail.ir2.yahoo.com> Message-ID: On Sun, Feb 10, 2013 at 3:39 AM, ALAN GAULD wrote: > So it does. You learn something new every day... > When did that first happen? It was one of my biggest frustrations > with Python when I first started learning, that you couldn't call exit > without first importing sys (v1.3). But I never noticed that changing > till now. Quitter was added to site.py in 2.5: http://hg.python.org/cpython/file/c10a71cf16e4/Lib/site.py#l227 In 2.4, exit/quit were simply strings: http://hg.python.org/cpython/file/f3f1f1462c82/Lib/site.py#l224 From wprins at gmail.com Sun Feb 10 15:32:28 2013 From: wprins at gmail.com (Walter Prins) Date: Sun, 10 Feb 2013 14:32:28 +0000 Subject: [Tutor] How to override getting items from a list for iteration Message-ID: Hello, I have a program where I'm overriding the retrieval of items from a list. As background: The data held by the lists are calculated but then read potentially many times thereafter, so in order to prevent needless re-calculating the same value over and over, and to remove checking/caching code from the calculation logic code, I therefore created a subclass of list that will automatically calculate the value in a given slot automatically if not yet calculated. (So differently put, I'm implemented a kind of list specific caching/memoization with the intent that it should be transparent to the client code.) The way I've implemented this so far was to simply override list.__getitem__(self, key) to check if the value needs to be calculated or not and call a calculation method if required, after which the value is returned as normal. On subsequent calls __getitem__ then directly returns the value without calculating it again. This worked mostly fine, however yesterday I ran into a slightly unexpected problem when I found that when the list contents is iterated over and values retrieved that way rather than via [], then __getitem__ is in fact *not* called on the list to read the item values from the list, and consequently I get back the "not yet calculated" entries in the list, without the calculation routine being automatically called as is intended. Here's a test application that demonstrates the issue: class NotYetCalculated: pass class CalcList(list): def __init__(self, calcitem): super(CalcList, self).__init__() self.calcitem = calcitem def __getitem__(self, key): """Override __getitem__ to call self.calcitem() if needed""" print "CalcList.__getitem__(): Enter" value = super(CalcList, self).__getitem__(key) if value is NotYetCalculated: print "CalcList.__getitem__(): calculating" value = self.calcitem(key) self[key] = value print "CalcList.__getitem__(): return" return value def calcitem(key): # Demo: return square of index return key*key def main(): # Create a list that calculates its contents via a given # method/fn onece only l = CalcList(calcitem) # Extend with few entries to demonstrate issue: l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated, NotYetCalculated]) print "1) Directly getting values from list works as expected: __getitem__ is called:" print "Retrieving value [2]:\n", l[2] print print "Retrieving value [3]:\n", l[3] print print "Retrieving value [2] again (no calculation this time):\n", l[2] print print "Retrieving values via an iterator doesn't work as expected:" print "(__getitem__ is not called and the code returns " print " NotYetCalcualted entries without calling __getitem__. How do I fix this?)" print "List contents:" for x in l: print x if __name__ == "__main__": main() To reiterate: What should happen: In test 2) above all entries should be automatically calculated and output should be numbers only. What actually happens: In test 2) above the first 2 list entries corresponding to list indexes 0 and 1 are output as "NotYetCalculated" and calcitem is not called when required. What's the best way to fix this problem? Do I need to maybe override another method, perhaps provide my own iterator implementation? For that matter, why doesn't iterating over the list contents fall back to calling __getitem__? Thanks in advance, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sun Feb 10 16:10:24 2013 From: davea at davea.name (Dave Angel) Date: Sun, 10 Feb 2013 10:10:24 -0500 Subject: [Tutor] How to override getting items from a list for iteration In-Reply-To: References: Message-ID: <5117B860.4090905@davea.name> On 02/10/2013 09:32 AM, Walter Prins wrote: > Hello, > > I have a program where I'm overriding the retrieval of items from a list. > As background: The data held by the lists are calculated but then read > potentially many times thereafter, so in order to prevent needless > re-calculating the same value over and over, and to remove checking/caching > code from the calculation logic code, I therefore created a subclass of > list that will automatically calculate the value in a given slot > automatically if not yet calculated. (So differently put, I'm implemented a > kind of list specific caching/memoization with the intent that it should be > transparent to the client code.) > > The way I've implemented this so far was to simply override > list.__getitem__(self, key) to check if the value needs to be calculated or > not and call a calculation method if required, after which the value is > returned as normal. On subsequent calls __getitem__ then directly returns > the value without calculating it again. > > This worked mostly fine, however yesterday I ran into a slightly unexpected > problem when I found that when the list contents is iterated over and > values retrieved that way rather than via [], then __getitem__ is in fact > *not* called on the list to read the item values from the list, and > consequently I get back the "not yet calculated" entries in the list, > without the calculation routine being automatically called as is intended. > > Here's a test application that demonstrates the issue: > > class NotYetCalculated: > pass > > class CalcList(list): > def __init__(self, calcitem): > super(CalcList, self).__init__() > self.calcitem = calcitem > > def __getitem__(self, key): > """Override __getitem__ to call self.calcitem() if needed""" > print "CalcList.__getitem__(): Enter" > value = super(CalcList, self).__getitem__(key) > if value is NotYetCalculated: > print "CalcList.__getitem__(): calculating" > value = self.calcitem(key) > self[key] = value > print "CalcList.__getitem__(): return" > return value > > def calcitem(key): > # Demo: return square of index > return key*key > > > def main(): > # Create a list that calculates its contents via a given > # method/fn onece only > l = CalcList(calcitem) > # Extend with few entries to demonstrate issue: > l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated, > NotYetCalculated]) > > print "1) Directly getting values from list works as expected: > __getitem__ is called:" > print "Retrieving value [2]:\n", l[2] > print > print "Retrieving value [3]:\n", l[3] > print > print "Retrieving value [2] again (no calculation this time):\n", l[2] > print > > print "Retrieving values via an iterator doesn't work as expected:" > print "(__getitem__ is not called and the code returns " > print " NotYetCalcualted entries without calling __getitem__. How do I > fix this?)" > print "List contents:" > for x in l: print x > > > if __name__ == "__main__": > main() > > To reiterate: > > What should happen: In test 2) above all entries should be automatically > calculated and output should be numbers only. > > What actually happens: In test 2) above the first 2 list entries > corresponding to list indexes 0 and 1 are output as "NotYetCalculated" and > calcitem is not called when required. > > What's the best way to fix this problem? Do I need to maybe override > another method, perhaps provide my own iterator implementation? For that > matter, why doesn't iterating over the list contents fall back to calling > __getitem__? > Implement your own __iter__() special method. And consider whether you might need __setitem__(), __len__(), __setslice__(), __getslice__() and others. Maybe you'd be better off not inheriting from list at all, and just having an attribute that's a list. It doesn't sound like you're defining a very big subset of list, and overriding the methods you *don't* want seems to be more work than just implementing the ones you do. A separate question: is this likely to be a sparse list? If it's very sparse, perhaps you'd consider using a dict, rather than a list attribute. -- DaveA From steve at pearwood.info Sun Feb 10 16:13:48 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Feb 2013 02:13:48 +1100 Subject: [Tutor] How to override getting items from a list for iteration In-Reply-To: References: Message-ID: <5117B92C.6010905@pearwood.info> On 11/02/13 01:32, Walter Prins wrote: > Hello, > > I have a program where I'm overriding the retrieval of items from a list. > As background: [...snip interesting but irrelevant background...] > Here's a test application that demonstrates the issue: [...snip overly complicated application...] Here is a much simpler demonstration: py> class MyList(list): ... def __getitem__(self, i): ... print "Checking item %d" % i ... return super(MyList, self).__getitem__(i) ... py> x = MyList([2, 4, 8, 16]) py> x[3] Checking item 3 16 py> for i in x: ... print "got %s" % i ... got 2 got 4 got 8 got 16 > What's the best way to fix this problem? Do I need to maybe override > another method, perhaps provide my own iterator implementation? Pretty much. For lists, the __iter__ method returns a listiterator object which efficiently iterates over the list items without calling __getitem__. Try overriding your class' __iter__ method: def __iter__(self): for i in range(len(self)): # use xrange in Python 2 yield self[i] (untested). > For that > matter, why doesn't iterating over the list contents fall back to calling > __getitem__? Probably as an optimization. -- Steven From __peter__ at web.de Sun Feb 10 16:15:57 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Feb 2013 16:15:57 +0100 Subject: [Tutor] How to override getting items from a list for iteration References: Message-ID: Walter Prins wrote: > Hello, > > I have a program where I'm overriding the retrieval of items from a list. > As background: The data held by the lists are calculated but then read > potentially many times thereafter, so in order to prevent needless > re-calculating the same value over and over, and to remove > checking/caching code from the calculation logic code, I therefore created > a subclass of list that will automatically calculate the value in a given > slot automatically if not yet calculated. (So differently put, I'm > implemented a kind of list specific caching/memoization with the intent > that it should be transparent to the client code.) > > The way I've implemented this so far was to simply override > list.__getitem__(self, key) to check if the value needs to be calculated > or not and call a calculation method if required, after which the value is > returned as normal. On subsequent calls __getitem__ then directly returns > the value without calculating it again. > > This worked mostly fine, however yesterday I ran into a slightly > unexpected problem when I found that when the list contents is iterated > over and values retrieved that way rather than via [], then __getitem__ is > in fact *not* called on the list to read the item values from the list, > and consequently I get back the "not yet calculated" entries in the list, > without the calculation routine being automatically called as is intended. > > Here's a test application that demonstrates the issue: > > class NotYetCalculated: > pass > > class CalcList(list): > def __init__(self, calcitem): > super(CalcList, self).__init__() > self.calcitem = calcitem > > def __getitem__(self, key): > """Override __getitem__ to call self.calcitem() if needed""" > print "CalcList.__getitem__(): Enter" > value = super(CalcList, self).__getitem__(key) > if value is NotYetCalculated: > print "CalcList.__getitem__(): calculating" > value = self.calcitem(key) > self[key] = value > print "CalcList.__getitem__(): return" > return value > > def calcitem(key): > # Demo: return square of index > return key*key > > > def main(): > # Create a list that calculates its contents via a given > # method/fn onece only > l = CalcList(calcitem) > # Extend with few entries to demonstrate issue: > l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated, > NotYetCalculated]) > > print "1) Directly getting values from list works as expected: > __getitem__ is called:" > print "Retrieving value [2]:\n", l[2] > print > print "Retrieving value [3]:\n", l[3] > print > print "Retrieving value [2] again (no calculation this time):\n", l[2] > print > > print "Retrieving values via an iterator doesn't work as expected:" > print "(__getitem__ is not called and the code returns " > print " NotYetCalcualted entries without calling __getitem__. How do I > fix this?)" > print "List contents:" > for x in l: print x > > > if __name__ == "__main__": > main() > > To reiterate: > > What should happen: In test 2) above all entries should be automatically > calculated and output should be numbers only. > > What actually happens: In test 2) above the first 2 list entries > corresponding to list indexes 0 and 1 are output as "NotYetCalculated" and > calcitem is not called when required. > > What's the best way to fix this problem? Do I need to maybe override > another method, perhaps provide my own iterator implementation? For that > matter, why doesn't iterating over the list contents fall back to calling > __getitem__? Probably an optimisation for the common case where retrieval of list items does not involve any calculation. You can override the __iter__() along the lines of def __iter__(self): for i in range(len(self)): return self[i] If the items are calculated from the index as in your example there's also the option to inherit from collections.Sequence instead of list: from collections import Sequence class List(Sequence): def __init__(self, getitem, size): self.getitem = getitem self._cache = [None] * size def __getitem__(self, index): assert not isinstance(index, (slice, tuple)) value = self._cache[index] if value is None: value = self._cache[index] = self.getitem(index) return value def __len__(self): return len(self._cache) if __name__ == "__main__": items = List(lambda x: x*x, 10) print("items[4] =", items[4]) print("items =", list(items)) But first and foremost I'd seriously reinvestigate your caching scheme. Does it really save enough time to make it worthwhile? From davea at davea.name Sun Feb 10 16:18:22 2013 From: davea at davea.name (Dave Angel) Date: Sun, 10 Feb 2013 10:18:22 -0500 Subject: [Tutor] How to override getting items from a list for iteration In-Reply-To: <5117B860.4090905@davea.name> References: <5117B860.4090905@davea.name> Message-ID: <5117BA3E.9020406@davea.name> On 02/10/2013 10:10 AM, Dave Angel wrote: > On 02/10/2013 09:32 AM, Walter Prins wrote: >> Hello, >> >> I have a program where I'm overriding the retrieval of items from a list. >> As background: The data held by the lists are calculated but then read >> potentially many times thereafter, so in order to prevent needless >> re-calculating the same value over and over, and to remove >> checking/caching >> code from the calculation logic code, I therefore created a subclass of >> list that will automatically calculate the value in a given slot >> automatically if not yet calculated. (So differently put, I'm >> implemented a >> kind of list specific caching/memoization with the intent that it >> should be >> transparent to the client code.) >> >> The way I've implemented this so far was to simply override >> list.__getitem__(self, key) to check if the value needs to be >> calculated or >> not and call a calculation method if required, after which the value is >> returned as normal. On subsequent calls __getitem__ then directly >> returns >> the value without calculating it again. >> >> This worked mostly fine, however yesterday I ran into a slightly >> unexpected >> problem when I found that when the list contents is iterated over and >> values retrieved that way rather than via [], then __getitem__ is in fact >> *not* called on the list to read the item values from the list, and >> consequently I get back the "not yet calculated" entries in the list, >> without the calculation routine being automatically called as is >> intended. >> >> Here's a test application that demonstrates the issue: >> >> class NotYetCalculated: >> pass >> >> class CalcList(list): >> def __init__(self, calcitem): >> super(CalcList, self).__init__() >> self.calcitem = calcitem >> >> def __getitem__(self, key): >> """Override __getitem__ to call self.calcitem() if needed""" >> print "CalcList.__getitem__(): Enter" >> value = super(CalcList, self).__getitem__(key) >> if value is NotYetCalculated: >> print "CalcList.__getitem__(): calculating" >> value = self.calcitem(key) >> self[key] = value >> print "CalcList.__getitem__(): return" >> return value >> >> def calcitem(key): >> # Demo: return square of index >> return key*key >> >> >> def main(): >> # Create a list that calculates its contents via a given >> # method/fn onece only >> l = CalcList(calcitem) >> # Extend with few entries to demonstrate issue: >> l.extend([NotYetCalculated, NotYetCalculated, NotYetCalculated, >> NotYetCalculated]) >> >> print "1) Directly getting values from list works as expected: >> __getitem__ is called:" >> print "Retrieving value [2]:\n", l[2] >> print >> print "Retrieving value [3]:\n", l[3] >> print >> print "Retrieving value [2] again (no calculation this time):\n", >> l[2] >> print >> >> print "Retrieving values via an iterator doesn't work as expected:" >> print "(__getitem__ is not called and the code returns " >> print " NotYetCalcualted entries without calling __getitem__. How >> do I >> fix this?)" >> print "List contents:" >> for x in l: print x >> >> >> if __name__ == "__main__": >> main() >> >> To reiterate: >> >> What should happen: In test 2) above all entries should be automatically >> calculated and output should be numbers only. >> >> What actually happens: In test 2) above the first 2 list entries >> corresponding to list indexes 0 and 1 are output as "NotYetCalculated" >> and >> calcitem is not called when required. >> >> What's the best way to fix this problem? Do I need to maybe override >> another method, perhaps provide my own iterator implementation? For that >> matter, why doesn't iterating over the list contents fall back to calling >> __getitem__? >> > > Implement your own __iter__() special method. > > And consider whether you might need __setitem__(), __len__(), > __setslice__(), __getslice__() and others. > > Maybe you'd be better off not inheriting from list at all, and just > having an attribute that's a list. It doesn't sound like you're > defining a very big subset of list, and overriding the methods you > *don't* want seems to be more work than just implementing the ones you do. > > A separate question: is this likely to be a sparse list? If it's very > sparse, perhaps you'd consider using a dict, rather than a list attribute. > > > BTW, the answer to why iterating over the list contents doesn't call __getitem__, the answer is because list does define __iter__, presumably to do it more efficiently. And there is your clue that perhaps you don't want to inherit from list. You don't want its more-efficient version, so all you have to do is not to implement an __iter__ and it should just work. -- DaveA From __peter__ at web.de Sun Feb 10 16:25:27 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 10 Feb 2013 16:25:27 +0100 Subject: [Tutor] How to override getting items from a list for iteration References: Message-ID: Peter Otten wrote: > def __iter__(self): > for i in range(len(self)): > return self[i] That should of course be 'yield', not 'return' From jf_byrnes at comcast.net Sun Feb 10 17:01:14 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 10 Feb 2013 10:01:14 -0600 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote: > ----- Original Message ----- > >> From: Jim Byrnes To: tutor at python.org Cc: >> Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip >> for Ubuntu 12.04 >> >> How important is it to have the latest pip installed? >> >> Initially I want to use it to install the latest pymongo driver for >> mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. >> I see on http://www.pip-installer.org/en/latest/ the version is >> 1.2.1. >> >> It certainly would be easier to install from the repositories but >> will that version work to install the latest python packages? >> >> Thanks, Jim > > You could just try it? And downloading it and then doing sudo tar > -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is > it? I usually install from the repositories or maybe a ppa so I don't believe I have ever done an install from a tar. If necessary I will familiarize myself with the command you gave (yes I saw your followup changing -xvr to -xvf) and install that way. However, I still wonder if using the outdated pip from the repository will allow me to install the latest python packages? Will trying to use an outdated pip cause me problems? > But you're right, I also nnoticed that the Canonical repositories are > a little outdated sometimes. Would be nice if it's possible to add > pypi.org, so updating would be easier. > > Albert-Jan Thanks, Jim From David_J_Pearson at uk.ibm.com Sun Feb 10 17:02:28 2013 From: David_J_Pearson at uk.ibm.com (David J Pearson) Date: Sun, 10 Feb 2013 16:02:28 +0000 Subject: [Tutor] AUTO: David J Pearson Is Attending An IBM Redbook residency (returning 19/02/2013) Message-ID: I am out of the office until 19/02/2013. I am attending an IBM Redbook residency in Raleigh, NC, USA ... and have limited access to my mail. My response to your email will be delayed during this time. Thanks David J Pearson MBCS CITP CEng MIET Technical Staff Member Solution Architect [Mobile, SmartCloud & OfficeProductivity] IBM Software Services for Collaboration CoE IBM Collaboration Software, IBM United Kingdom Ltd Mailto:David_J_Pearson at uk.ibm.com Twitter: @DJPearson1 Note: This is an automated response to your message "Tutor Digest, Vol 108, Issue 32" sent on 10/02/2013 11:00:02. This is the only notification you will receive while this person is away. From timomlists at gmail.com Sun Feb 10 19:53:18 2013 From: timomlists at gmail.com (Timo) Date: Sun, 10 Feb 2013 19:53:18 +0100 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <5117EC9E.8030207@gmail.com> Op 10-02-13 17:01, Jim Byrnes schreef: > On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote: >> ----- Original Message ----- >> >>> From: Jim Byrnes To: tutor at python.org Cc: >>> Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip >>> for Ubuntu 12.04 >>> >>> How important is it to have the latest pip installed? >>> >>> Initially I want to use it to install the latest pymongo driver for >>> mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. >>> I see on http://www.pip-installer.org/en/latest/ the version is >>> 1.2.1. >>> >>> It certainly would be easier to install from the repositories but >>> will that version work to install the latest python packages? >>> >>> Thanks, Jim >> >> You could just try it? And downloading it and then doing sudo tar >> -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is >> it? > > I usually install from the repositories or maybe a ppa so I don't > believe I have ever done an install from a tar. If necessary I will > familiarize myself with the command you gave (yes I saw your followup > changing -xvr to -xvf) and install that way. > > However, I still wonder if using the outdated pip from the repository > will allow me to install the latest python packages? Will trying to > use an outdated pip cause me problems? I doubt it will. Have a look at the pip changelog to see what has been changed. Timo > >> But you're right, I also nnoticed that the Canonical repositories are >> a little outdated sometimes. Would be nice if it's possible to add >> pypi.org, so updating would be easier. >> >> Albert-Jan > > > Thanks, Jim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From joel.goldstick at gmail.com Sun Feb 10 20:10:02 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 10 Feb 2013 14:10:02 -0500 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: <5117EC9E.8030207@gmail.com> References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> <5117EC9E.8030207@gmail.com> Message-ID: On Sun, Feb 10, 2013 at 1:53 PM, Timo wrote: > Op 10-02-13 17:01, Jim Byrnes schreef: > > On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote: >> >>> ----- Original Message ----- >>> >>> From: Jim Byrnes To: tutor at python.org Cc: >>>> Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip >>>> for Ubuntu 12.04 >>>> >>>> How important is it to have the latest pip installed? >>>> >>>> Initially I want to use it to install the latest pymongo driver for >>>> mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. >>>> I see on http://www.pip-installer.org/**en/latest/the version is >>>> 1.2.1. >>>> >>>> It certainly would be easier to install from the repositories but >>>> will that version work to install the latest python packages? >>>> >>>> Thanks, Jim >>>> >>> >>> You could just try it? And downloading it and then doing sudo tar >>> -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is >>> it? >>> >> >> I usually install from the repositories or maybe a ppa so I don't believe >> I have ever done an install from a tar. If necessary I will familiarize >> myself with the command you gave (yes I saw your followup changing -xvr to >> -xvf) and install that way. >> >> However, I still wonder if using the outdated pip from the repository >> will allow me to install the latest python packages? Will trying to use an >> outdated pip cause me problems? >> > I doubt it will. Have a look at the pip changelog to see what has been > changed. > > Timo > > > > >> But you're right, I also nnoticed that the Canonical repositories are >>> a little outdated sometimes. Would be nice if it's possible to add >>> pypi.org, so updating would be easier. >>> >>> Albert-Jan >>> >> >> >> Thanks, Jim >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > You can upgrade pip with pip i believe: jcg at jcg-desktop:~/code/python\$ pip install pip Requirement already satisfied (use --upgrade to upgrade): pip in /usr/lib/pymodules/python2.7 Cleaning up... jcg at jcg-desktop:~/code/python\$ jcg at jcg-desktop:~/code/python\$ pip install --upgrade pip Be sure to sudo before if you don't have permissions. -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ghasemmg01 at leedslearning.net Sun Feb 10 21:29:23 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Sun, 10 Feb 2013 20:29:23 +0000 Subject: [Tutor] Additional help Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> Hi guys, I wondered if you knew what I could add to this code so that when the user enters 1 from the menu and then doesn't enter a valid binary number the program should ask them over and over again until valid binary number is entered. here is the code: def show_menu(): print("=======================") print("1-binary to denary") print("2-denary to binary") print("3-exit") print("=======================") while True: show_menu() choice = input("please enter an option: ") if choice == '1': binary = input("Please enter a binary number: ") denary = 0 place_value = 1 for i in binary [::-1]: denary += place_value * int(i) place_value *= 2 print("The result is",denary) elif choice == '2': denary2 = int(input("Please enter a denary number: ")) remainder = '' while denary2 > 0: remainder = str(denary2 % 2) + remainder denary2 >>= 1 print("The result is",remainder) elif choice == '3': break elif choice not in '1' or '2' or '3': print("Invalid input-try again!") Thanks From brian.van.den.broek at gmail.com Sun Feb 10 22:15:04 2013 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sun, 10 Feb 2013 16:15:04 -0500 Subject: [Tutor] Additional help In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 10 February 2013 15:29, Ghadir Ghasemi wrote: > Hi guys, I wondered if you knew what I could add to this code so that when the user enters 1 from the menu and then doesn't enter a valid binary number the program should ask them over and over again until valid binary number is entered. > here is the code: > while True: > show_menu() > > choice = input("please enter an option: ") > > if choice == '1': > binary = input("Please enter a binary number: ") > denary = 0 > place_value = 1 > > for i in binary [::-1]: > denary += place_value * int(i) > place_value *= 2 > > print("The result is",denary) > elif choice == '3': > break Hi Ghadir, "over and over again until" suggests a while loop. So, you need something like the pseudo-code: while True: binary = input("Please enter a binary number: ") if isgood(binary): pass # do stuff then break else: pass #remind user of constraints before they are prompted again (This assumes you've an isgood function that will return a boolean as the user input is acceptable. That's not necessarily the best way, but it makes for easy pseduo-code and doesn't do the work for you ;-) Last, a better subject line is a good idea. Pretty much every post asking for help from someone who's posted before could have your subject line. Best, Brian vdB From oscar.j.benjamin at gmail.com Sun Feb 10 22:20:54 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 10 Feb 2013 21:20:54 +0000 Subject: [Tutor] How to override getting items from a list for iteration In-Reply-To: References: Message-ID: On 10 February 2013 14:32, Walter Prins wrote: [snip > > This worked mostly fine, however yesterday I ran into a slightly unexpected > problem when I found that when the list contents is iterated over and values > retrieved that way rather than via [], then __getitem__ is in fact *not* > called on the list to read the item values from the list, and consequently I > get back the "not yet calculated" entries in the list, without the > calculation routine being automatically called as is intended. > > Here's a test application that demonstrates the issue: > > class NotYetCalculated: > pass > > class CalcList(list): > def __init__(self, calcitem): > super(CalcList, self).__init__() > self.calcitem = calcitem > > def __getitem__(self, key): > """Override __getitem__ to call self.calcitem() if needed""" > print "CalcList.__getitem__(): Enter" > value = super(CalcList, self).__getitem__(key) > if value is NotYetCalculated: > print "CalcList.__getitem__(): calculating" > value = self.calcitem(key) > self[key] = value > print "CalcList.__getitem__(): return" > return value > > def calcitem(key): > # Demo: return square of index > return key*key > > What's the best way to fix this problem? Do I need to maybe override > another method, perhaps provide my own iterator implementation? For that > matter, why doesn't iterating over the list contents fall back to calling > __getitem__? It would use __getitem__ if __iter__ wasn't defined. e.g.: >>> class A(object): ... def __getitem__(self, index): ... if index > 4: ... raise IndexError ... return index ** 2 ... >>> a = A() >>> for x in a: ... print(x) ... 0 1 4 9 16 The problem is that by subclassing list you inherit its __iter__ method. A for loop begins by calling iter() on the iterable. The iter function is roughly like: def iterseq(seq): count = 0 while True: try: yield seq[count] except IndexError: return count += 1 def iter(iterable): if hasattr(iterable, '__iter__'): return iterable.__iter__() elif hasattr(iterable, '__getitem__'): return iterseq(iterable) else: raise TypeError Oscar From eire1130 at gmail.com Sun Feb 10 23:23:05 2013 From: eire1130 at gmail.com (James Reynolds) Date: Sun, 10 Feb 2013 17:23:05 -0500 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> <5117EC9E.8030207@gmail.com> Message-ID: The bigger issue with mongo is the apt versions are old. Be sure to follow the instructions on mongos site. If you pip install pymongo with a ubunuto or mint build your gtg -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Feb 11 00:14:44 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 10 Feb 2013 18:14:44 -0500 Subject: [Tutor] binary - denary converter (was Additional help) In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> Message-ID: <511829E4.3060604@gmail.com> I am changing the subject line to one that is more explicit. On 2/10/2013 3:29 PM, Ghadir Ghasemi wrote: > elif choice not in '1' or '2' or '3': > print("Invalid input-try again!") This works, but not for the reasons you had in mind. For experiment, try: >>> '1' or '2' or '3' '1' >>> '3' or'2' or '1' '3' >>> '1' not in '1' or '2' or '3' '2' It is easy to stare at this and say "huh"? or "that makes no sense". Instead read up on "in", "or" and "operator precedence" until you do understand it. From the Language Reference: 5:9 The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s 5:10 The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. 5:15 for operator precedence Also realize that all you need at the end is: else: print("Invalid input-try again!") For checking an item against several possibilities: elif choice not in ('1', '2', '3'): -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Mon Feb 11 02:14:42 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Feb 2013 12:14:42 +1100 Subject: [Tutor] Code to open a website In-Reply-To: <1360488335.4141.YahooMailNeo@web186005.mail.ir2.yahoo.com> References: <1360487830.28294.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1360488335.4141.YahooMailNeo@web186005.mail.ir2.yahoo.com> Message-ID: <51184602.7050302@pearwood.info> On 10/02/13 20:25, ALAN GAULD wrote: > > >> Maybe the OP meant to say 'quit()' ? That does not require an import. > > > Ooh! another option I didn't know about! > So many ways to get rid of Python and here's me been importing sys > or raising SystemExit all these years... :-) exit() and quit() (as added by the site.py module) are for interactive use. They're mostly there for the benefit of newbies. Experienced developers (at least in the Unix/Linux world) usually know to exit interactive terminal apps with Ctrl-D. I believe you use Ctrl-Z under Windows. For programmatic use in scripts, use sys.exit(), since the site module is not guaranteed to run. -- Steven From eryksun at gmail.com Mon Feb 11 02:31:34 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 10 Feb 2013 20:31:34 -0500 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: <5117EC9E.8030207@gmail.com> References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> <5117EC9E.8030207@gmail.com> Message-ID: On Sun, Feb 10, 2013 at 1:53 PM, Timo wrote: >> However, I still wonder if using the outdated pip from the repository will >> allow me to install the latest python packages? Will trying to use an >> outdated pip cause me problems? > > I doubt it will. Have a look at the pip changelog to see what has been > changed. Additionally, deb packages may have platform-specific patches. For example, here's the changelog and patches for python-pip: http://packages.debian.org/changelogs/pool/main/p/python-pip/current/changelog http://anonscm.debian.org/viewvc/python-modules/packages/python-pip/trunk/debian/patches From Yogesh.M.Pai at tektronix.com Mon Feb 11 05:25:02 2013 From: Yogesh.M.Pai at tektronix.com (Pai, Yogesh M) Date: Mon, 11 Feb 2013 04:25:02 +0000 Subject: [Tutor] How to log process handles and GDI objects in python In-Reply-To: References: Message-ID: Hi Alan, Here are the additional details: Python version: 2.7.3 OS version: Windows 7 -64 bit I have an application that has a automation layer built in python. During every subsequent runs, I want to log the process threads and GDI objects ( the one you see in the Windows task manager) in my python code- The idea is to use this data to generate a plot to check if the application leaks memory in a long run. Although I can use a third-party app to log this, is it possible to import certain library in python and log these windows attributes during the execution? Thanks, Yogesh -----Original Message----- From: Tutor [mailto:tutor-bounces+yogesh.m.pai=tektronix.com at python.org] On Behalf Of Alan Gauld Sent: Friday, February 08, 2013 5:02 PM To: tutor at python.org Subject: Re: [Tutor] How to log process handles and GDI objects in python On 08/02/13 09:06, Pai, Yogesh M wrote: > I would like to know how can I log system process handles and GDI > objects for debugging memory leak issues in python. This isn't really a question about learning Python so probably would be better on the main Python mailing list. However it will help if you specify things like the OS, the Python version. Also be clear about what exactly you mean by process handles and GDI objects. I'm guessing you are talking about Windows but I can't be sure. > I would like to log these inside a loop (stress test) to check if my > application leaks handles and plot them later for my usage. I imagine that means you are creating a test lop that creates and releases these handles? How do you get a handle? can you store it as a variable? can you print it? can you create a string and print that? Sorry I can't be of more help but that's a fairly open question about a very specific problem. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From neubyr at gmail.com Mon Feb 11 06:14:14 2013 From: neubyr at gmail.com (neubyr) Date: Sun, 10 Feb 2013 23:14:14 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file Message-ID: I have a text file with each line in following format: Book Name, Author Name, Genre, Publication Date I would like to perform following queries on this file: * Get all books written by an author * Remove all books of an author * Get information about a book (pretty print matching line!) * Get books of particular genre Also, I would like to add and delete entries in this file. I am not planning to use any database for this purpose and would like to get better grasp on file parsing and classes/OOP. I need some help in creating classes and following are my initial thoughts: # Create a class for Book object class Book: atributes: name, author_name, genre, publication-date # Create Author: attribute(s): name # Create class for reading and writing to the file class Booksfile: methods: ?? * How do I associate/relate Book and Author classes so that it will help me in getting information like 'get list of books written by an author'? Data attribute? * Should I create a new Booksfile object for reading, writing and deleting entries in the file OR add corresponding methods to the book object itself? I am not planning to use SQLite or any database and would like to use text file only. Appreciate any help on designing such application. thanks, N -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Mon Feb 11 06:28:40 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Mon, 11 Feb 2013 00:28:40 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: Message-ID: <51188188.2090002@lightbird.net> On 02/11/2013 12:14 AM, neubyr wrote: > > I have a text file with each line in following format: > > Book Name, Author Name, Genre, Publication Date > > I would like to perform following queries on this file: > * Get all books written by an author > * Remove all books of an author > * Get information about a book (pretty print matching line!) > * Get books of particular genre > > Also, I would like to add and delete entries in this file. I am not planning to use any database for this purpose and would like to get better grasp on file parsing and classes/OOP. I need some help in creating classes and following are my initial thoughts: > > # Create a class for Book object > class Book: > atributes: name, author_name, genre, publication-date > > # Create > Author: > attribute(s): name > > # Create class for reading and writing to the file > class Booksfile: > methods: ?? > > > * How do I associate/relate Book and Author classes so that it will help me in getting information like 'get list of books written by an author'? Data attribute? > * Should I create a new Booksfile object for reading, writing and deleting entries in the file OR add corresponding methods to the book object itself? > > I am not planning to use SQLite or any database and would like to use text file only. Appreciate any help on designing such application. > > Book.author should be author instance, Author def books(self): return [b for b in books if b.author==self] Get lists by genre etc in a similar way. To do file processing, look at the standard csv module: http://docs.python.org/2/library/csv.html -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ The doer alone learneth. Friedrich Nietzsche From davea at davea.name Mon Feb 11 06:56:55 2013 From: davea at davea.name (Dave Angel) Date: Mon, 11 Feb 2013 00:56:55 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: Message-ID: <51188827.8000301@davea.name> On 02/11/2013 12:14 AM, neubyr wrote: > I have a text file with each line in following format: > > Book Name, Author Name, Genre, Publication Date > > I would like to perform following queries on this file: > * Get all books written by an author > * Remove all books of an author > * Get information about a book (pretty print matching line!) > * Get books of particular genre > > Also, I would like to add and delete entries in this file. I am not > planning to use any database for this purpose and would like to get better > grasp on file parsing and classes/OOP. I take it from this that this is a class assignment, and that neither speed nor enormous data capacity nor concurrent operation is a requirement. But your professor may have other requirements that you haven't told us about. I need some help in creating classes > and following are my initial thoughts: > > # Create a class for Book object > class Book: > atributes: name, author_name, genre, publication-date > > # Create > Author: > attribute(s): name Is this in order to save space, since each Book instance can then have a reference to an Author object, rather than a reference to a string containing the Author's name. If you deem this class useful, then don't you also want one for Genre ? > > # Create class for reading and writing to the file > class Booksfile: > methods: ?? Why ? Are you transliterating this from Java ? > > > * How do I associate/relate Book and Author classes so that it will help me > in getting information like 'get list of books written by an author'? Data > attribute? If performance doesn't matter, then create one list of Book instances, and search it for whichever characteristics you like. > * Should I create a new Booksfile object for reading, writing and deleting > entries in the file OR add corresponding methods to the book object itself? Neither, a pair of regular functions will do fine. One that loads when you start the program, and another that saves the file when you exit. If you really expect to update the file incrementally, deleting entries in it, then think hard about your decision to roll your own database. A text file isn't random access. > > I am not planning to use SQLite or any database and would like to use text > file only. Appreciate any help on designing such application. > > The real question is where you might proceed after meeting these first requirements. For example, if you expect the list to grow to a few hundred million entries, then you'll need to be very careful about layout. And starting and exiting the program would be very slow, since you can do nothing till all the data has been loaded in and converted to objects. Or perhaps you'll want to have another file with additional author data, associated with the first by carefully spelling the author's name the same in all cases. In that case, having a separate Author class makes great sense. So if you expect to grow in that direction, then you should create the class now, even though it has only one attribute. -- DaveA From sulinet at postafiok.hu Mon Feb 11 11:58:48 2013 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Mon, 11 Feb 2013 11:58:48 +0100 Subject: [Tutor] Truncated urlopen Message-ID: Hi tutors, aboard again after a long time. http://..._export.php?mehet=1 is a link which exports me some data in CSV correctly when I click on it in my browser. (It contains personal data, that's why I dotted.) I want to process it directly from Python, excluding the browser phase. The following piece of code in Python 3.3 prints the first n-1 lines nicely, then the beginning of the last line truncated. I mean there are 12 fields in CSV and in the last line only 1.5 fields of them are displayed. I suspect some closing/caching error. In the first times it worked well but after a certain time it spoiled without PHP code being modified. I guess it may somehow be connected to quantity of lines. How could I read the last line? Thx, P?ter from urllib.request import urlopen x=urlopen('http://..._export.php?mehet=1') y=x.read().decode('windows-1250') print(y) Output looks like this: 159;Name of customer159;xxxx at gmail.com;phone;22;0;0;0;1;0;0;2013-02-09 20:20:26 160;Name of customer160;yyyy at gmail.com;phone;14;0;0;1;0;0;0;2013-02-09 20:38:16 161;Name of c -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Mon Feb 11 12:23:49 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 11 Feb 2013 06:23:49 -0500 Subject: [Tutor] How to log process handles and GDI objects in python In-Reply-To: References: Message-ID: On Sun, Feb 10, 2013 at 11:25 PM, Pai, Yogesh M wrote: > I want to log the process threads and GDI objects (the one you see in > the Windows task manager) in my python code- The idea is to use this > data to generate a plot to check if the application leaks memory in a > long run. Although I can use a third-party app to log this, is it > possible to import certain library in python and log these windows > attributes during the execution? psutil can query the number of handles and threads for a Windows process, but not GDI objects. http://code.google.com/p/psutil Getting the number of handles and gdi/user objects via the Win32 API isn't too hard. Required functions: ?OpenProcess http://msdn.microsoft.com/en-us/library/ms684320 CloseHandle http://msdn.microsoft.com/en-us/library/ms724211 GetProcessHandleCount http://msdn.microsoft.com/en-us/library/ms683214 GetGuiResources http://msdn.microsoft.com/en-us/library/ms683192 Here's a basic example with ctypes. In practice, set argtypes for each function call (a TypeError is better than a segfault) and error check the return value per the above docs. You can map the last error (i.e. GetLastError) to an exception using ctypes.WinError. (I haven't checked, but all of this is probably simple using pywin32. Just search around the net for examples.) >>> import os >>> from ctypes import * >>> from ctypes.wintypes import * >>> PQI = 0x400 # PROCESS_QUERY_INFORMATION >>> pid = os.getpid() >>> h = windll.kernel32.OpenProcess(PQI, 0, pid) >>> hndcnt = DWORD() >>> windll.kernel32.GetProcessHandleCount(h, byref(hndcnt)) 1 >>> hndcnt.value 72L >>> GR_GDIOBJECTS, GR_USEROBJECTS = 0, 1 >>> windll.user32.GetGuiResources(h, GR_GDIOBJECTS) 4 >>> windll.user32.GetGuiResources(h, GR_USEROBJECTS) 1 >>> windll.kernel32.CloseHandle(h) 1 The number of threads can be found by iterating over a system snapshot up to the desired PID. Here are the required functions and data struct: CreateToolhelp32Snapshot http://msdn.microsoft.com/en-us/library/ms682489 Process32First[W] http://msdn.microsoft.com/en-us/library/ms684834 Process32Next[W] http://msdn.microsoft.com/en-us/library/ms684836 PROCESSENTRTY32 http://msdn.microsoft.com/en-us/library/ms684839 class PROCESSENTRY32(Structure): _fields_ = [ ('dwSize', DWORD), ('cntUsage', DWORD), ('th32ProcessID', DWORD), ('th32DefaultHeapID', c_void_p), ('th32ModuleID', DWORD), ('cntThreads', DWORD), ('th32ParentProcessID', DWORD), ('pcPriClassBase', c_long), ('dwFlags', DWORD), ('szExeFile', WCHAR * MAX_PATH), ] def __init__(self, *args, **kwds): Structure.__init__(self, *args, **kwds) self.dwSize = sizeof(self) TH32CS_SNAPPROCESS = 2 th32cs = windll.kernel32.CreateToolhelp32Snapshot def get_num_threads(pid): num_threads = 0 hsnap = th32cs(TH32CS_SNAPPROCESS, 0) pe = PROCESSENTRY32() r = windll.kernel32.Process32FirstW(hsnap, byref(pe)) while r: if pe.th32ProcessID == pid: num_threads = int(pe.cntThreads) break r = windll.kernel32.Process32NextW(hsnap, byref(pe)) windll.kernel32.CloseHandle(hsnap) return num_threads Example: >>> from threading import Timer >>> pid = os.getpid() >>> get_num_threads(pid) 1 >>> for i in range(30): Timer(30, lambda: None).start() >>> get_num_threads(pid) 31 From davea at davea.name Mon Feb 11 14:36:16 2013 From: davea at davea.name (Dave Angel) Date: Mon, 11 Feb 2013 08:36:16 -0500 Subject: [Tutor] Truncated urlopen In-Reply-To: References: Message-ID: <5118F3D0.1070201@davea.name> On 02/11/2013 05:58 AM, V?las P?ter wrote: > Hi tutors, > > aboard again after a long time. Welcome back. > http://..._export.php?mehet=1 is a link which exports me some data in CSV > correctly when I click on it in my browser. (It contains personal data, > that's why I dotted.) I want to process it directly from Python, excluding > the browser phase. > > The following piece of code in Python 3.3 prints the first n-1 lines > nicely, then the beginning of the last line truncated. I mean there are 12 > fields in CSV and in the last line only 1.5 fields of them are displayed. I > suspect some closing/caching error. > In the first times it worked well but after a certain time it spoiled > without PHP code being modified. I guess it may somehow be connected to > quantity of lines. > How could I read the last line? > Thx, P?ter > > from urllib.request import urlopen > x=urlopen('http://..._export.php?mehet=1') > y=x.read().decode('windows-1250') I'd suggest splitting that expression into two separate statements, one that does the read, and the other that decodes. Then you can print the byte-string, and see if it also is truncated, or whether that happened during the decoding. (Though I can't imagine how decoding one of the windows-xxx character sets could fail to do the whole thing) Also, if you use print( repr(mystring) ) you might discover that there are funny escape sequence characters that are fooling your console. > print(y) > > Output looks like this: > 159;Name of customer159;xxxx at gmail.com;phone;22;0;0;0;1;0;0;2013-02-09 > 20:20:26 > 160;Name of customer160;yyyy at gmail.com;phone;14;0;0;1;0;0;0;2013-02-09 > 20:38:16 > 161;Name of c > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- DaveA From sulinet at postafiok.hu Mon Feb 11 16:00:18 2013 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Mon, 11 Feb 2013 16:00:18 +0100 Subject: [Tutor] Truncated urlopen In-Reply-To: <5118F3D0.1070201@davea.name> References: <5118F3D0.1070201@davea.name> Message-ID: 2013/2/11 Dave Angel > I'd suggest splitting that expression into two separate statements, one > that does the read, and the other that decodes. Then you can print the > byte-string, and see if it also is truncated, or whether that happened > during the decoding. > > Also, if you use print( repr(mystring) ) > you might discover that there are funny escape sequence characters that > are fooling your console. > Thanks, Dave, none of these helps. They are truncated as well. But I noticed a strange phenomenon. I am supposed to login to this page, but I can reach CVS data without login if I use the direct link to export. This may be a bug, but I like it. :-) Now, If I use the same link in browser, I get different results depending on I have logged in or not. (But in the first times of gathering data in this table, my Python script worked well!) So I should try to log in, but I have always difficulties with logging in from Python. I know http://docs.python.org/3/howto/urllib2.html#id6, but I couldn't use it in practice. Another way would be to log in in the browser correctly, then export CVS and process it with Python after saving, but I am too lazy to repeat this all the time. :-) -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Feb 11 16:12:12 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 11 Feb 2013 10:12:12 -0500 Subject: [Tutor] Truncated urlopen In-Reply-To: References: <5118F3D0.1070201@davea.name> Message-ID: On Mon, Feb 11, 2013 at 10:00 AM, V?las P?ter wrote: > 2013/2/11 Dave Angel > >> I'd suggest splitting that expression into two separate statements, one >> that does the read, and the other that decodes. Then you can print the >> byte-string, and see if it also is truncated, or whether that happened >> during the decoding. >> >> Also, if you use print( repr(mystring) ) >> you might discover that there are funny escape sequence characters that >> are fooling your console. >> > > Thanks, Dave, > none of these helps. They are truncated as well. > > But I noticed a strange phenomenon. I am supposed to login to this page, > but I can reach CVS data without login if I use the direct link to export. > This may be a bug, but I like it. :-) Now, If I use the same link in > browser, I get different results depending on I have logged in or not. (But > in the first times of gathering data in this table, my Python script worked > well!) > > So I should try to log in, but I have always difficulties with logging in > from Python. I know http://docs.python.org/3/howto/urllib2.html#id6, but > I couldn't use it in practice. > Another way would be to log in in the browser correctly, then export CVS > and process it with Python after saving, but I am too lazy to repeat this > all the time. :-) > > > There is a library called 'requests' http://docs.python-requests.org/en/latest/ that I have used to access websites. It seems much less confusing than urllib/urllib2 to me. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Mon Feb 11 16:31:20 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Mon, 11 Feb 2013 09:31:20 -0600 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> <5117EC9E.8030207@gmail.com> Message-ID: On 02/10/2013 01:10 PM, Joel Goldstick wrote: > On Sun, Feb 10, 2013 at 1:53 PM, Timo wrote: > >> Op 10-02-13 17:01, Jim Byrnes schreef: >> >> On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote: >>> >>>> ----- Original Message ----- >>>> >>>> From: Jim Byrnes To: tutor at python.org Cc: >>>>> Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip >>>>> for Ubuntu 12.04 >>>>> >>>>> How important is it to have the latest pip installed? >>>>> >>>>> Initially I want to use it to install the latest pymongo driver for >>>>> mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. >>>>> I see on http://www.pip-installer.org/**en/latest/the version is >>>>> 1.2.1. >>>>> >>>>> It certainly would be easier to install from the repositories but >>>>> will that version work to install the latest python packages? >>>>> >>>>> Thanks, Jim >>>>> >>>> >>>> You could just try it? And downloading it and then doing sudo tar >>>> -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is >>>> it? >>>> >>> >>> I usually install from the repositories or maybe a ppa so I don't believe >>> I have ever done an install from a tar. If necessary I will familiarize >>> myself with the command you gave (yes I saw your followup changing -xvr to >>> -xvf) and install that way. >>> >>> However, I still wonder if using the outdated pip from the repository >>> will allow me to install the latest python packages? Will trying to use an >>> outdated pip cause me problems? >>> >> I doubt it will. Have a look at the pip changelog to see what has been >> changed. >> >> Timo >> >> >> >> >>> But you're right, I also nnoticed that the Canonical repositories are >>>> a little outdated sometimes. Would be nice if it's possible to add >>>> pypi.org, so updating would be easier. >>>> >>>> Albert-Jan >>>> >>> >>> >>> Thanks, Jim >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> > > > > You can upgrade pip with pip i believe: > > jcg at jcg-desktop:~/code/python\$ pip install pip > Requirement already satisfied (use --upgrade to upgrade): pip in > /usr/lib/pymodules/python2.7 > Cleaning up... > jcg at jcg-desktop:~/code/python\$ > > > jcg at jcg-desktop:~/code/python\$ pip install --upgrade pip > > > Be sure to sudo before if you don't have permissions. > > I tried this on my laptop with the following results: jfb at jfb-tp:~\$ pip --version pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7) jfb at jfb-tp:~\$ pip install pip Requirement already satisfied (use --upgrade to upgrade): pip in /usr/lib/python2.7/dist-packages Cleaning up... jfb at jfb-tp:~\$ sudo pip install --upgrade pip [sudo] password for jfb: Downloading/unpacking pip Running setup.py egg_info for package pip warning: no files found matching '*.html' under directory 'docs' warning: no previously-included files matching '*.txt' found under directory 'docs/_build' no previously-included directories found matching 'docs/_build/_sources' Installing collected packages: pip Found existing installation: pip 1.0 Uninstalling pip: Successfully uninstalled pip Running setup.py install for pip warning: no files found matching '*.html' under directory 'docs' warning: no previously-included files matching '*.txt' found under directory 'docs/_build' no previously-included directories found matching 'docs/_build/_sources' Installing pip script to /usr/local/bin Installing pip-2.7 script to /usr/local/bin Successfully installed pip Cleaning up... jfb at jfb-tp:~\$ pip --version bash: /usr/bin/pip: No such file or directory jfb at jfb-tp:~\$ I not sure what the significance of the missing *.txt and *.html files is but it looks like I have a path problem. I would appreciate any pointers from anyone who has already solved this. Thanks, Jim From pravyareddy at gmail.com Mon Feb 11 16:56:36 2013 From: pravyareddy at gmail.com (Pravya Reddy) Date: Mon, 11 Feb 2013 07:56:36 -0800 Subject: [Tutor] (no subject) Message-ID: Can You Plaese help me with the code. #converts temperature to fahrenheit or celsius def print_options(): print ("Options:") print (" 'p' print options") print (" 'c' convert from celsius") print (" 'f' convert from fahrenheit") print (" 'q' quit the program") def celsius_to_fahrenheit(c_temp): return 9.0/5.0*c_temp+32 def fahrenheit_to_celsius(f_temp): return (f_temp - 32.0)*5.0/9.0 choice = "p" while choice != "q": if choice == "c": temp = input(input("Celsius temperature:")) print ("Fahrenheit:",celsius_to_fahrenheit(temp)) elif choice == "f": temp = input("Fahrenheit temperature:") print ("Celsius:",fahrenheit_to_celsius(temp)) elif choice != "q": print_options() choice = input(input("option:")) The Output i got is: Options: 'p' print options 'c' convert from celsius 'f' convert from fahrenheit 'q' quit the program option:c c Options: 'p' print options 'c' convert from celsius 'f' convert from fahrenheit 'q' quit the program option: -------------- next part -------------- An HTML attachment was scrubbed... URL: From pravyareddy at gmail.com Mon Feb 11 16:58:55 2013 From: pravyareddy at gmail.com (Pravya Reddy) Date: Mon, 11 Feb 2013 07:58:55 -0800 Subject: [Tutor] (no subject) Message-ID: Can you please help me with the code. #!/usr/bin/env python """ inchtocm.py """ def Inchtocm(inches): """Returns 2.54 * inches""" return (2.54 * float(inches_number1)) inches = None while True: try: inches_number1 = input(input("How many inches you want to convert: ")) inches = float(inches_number1) print ("You got", Inchtocm(inches), "cm.") print ("You converted", inches, "inches to cm.") break except ValueError: print ("This is not a number!") The code is incomplete and i am not getting a proper output: How many inches you want to convert: 455 455 This is not a number! How many inches you want to convert: -------------- next part -------------- An HTML attachment was scrubbed... URL: From pravyareddy at gmail.com Mon Feb 11 17:06:39 2013 From: pravyareddy at gmail.com (Pravya Reddy) Date: Mon, 11 Feb 2013 08:06:39 -0800 Subject: [Tutor] help with inch to cms conversion . Message-ID: Can you please help me with the code. #!/usr/bin/env python """ inchtocm.py """ def Inchtocm(inches): """Returns 2.54 * inches""" return (2.54 * float(inches_number1)) inches = None while True: try: inches_number1 = input(input("How many inches you want to convert: ")) inches = float(inches_number1) print ("You got", Inchtocm(inches), "cm.") print ("You converted", inches, "inches to cm.") break except ValueError: print ("This is not a number!") The code is incomplete and i am not getting a proper output: How many inches you want to convert: 455 455 This is not a number! How many inches you want to convert: _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Mon Feb 11 17:12:33 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 11 Feb 2013 11:12:33 -0500 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: First, pick a good subject header. By having caught excep ValueError in your mainline code you lose the opportunity to find out where it came from. If you comment it out you will see that the function inchtocm(inches) uses inches_number1 in its code. So you are ignoring the inches that you passed in. Is that what you want? On Mon, Feb 11, 2013 at 10:58 AM, Pravya Reddy wrote: > Can you please help me with the code. > > #!/usr/bin/env python > """ > inchtocm.py > > """ > > def Inchtocm(inches): > """Returns 2.54 * inches""" > return (2.54 * float(inches_number1)) > The line above here is suspect since you likely want to return 2.54 * inches > > inches = None > while True: > try: > inches_number1 = input(input("How many inches you want to convert: > ")) > inches = float(inches_number1) > print ("You got", Inchtocm(inches), "cm.") > print ("You converted", inches, "inches to cm.") > break > except ValueError: > print ("This is not a number!") > > The code is incomplete and i am not getting a proper output: > > How many inches you want to convert: 455 > 455 > This is not a number! > How many inches you want to convert: > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Mon Feb 11 17:17:18 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Mon, 11 Feb 2013 10:17:18 -0600 Subject: [Tutor] Which pip for Ubuntu 12.04 In-Reply-To: References: <1360410374.55825.YahooMailNeo@web163806.mail.gq1.yahoo.com> <5117EC9E.8030207@gmail.com> Message-ID: On 02/11/2013 09:31 AM, Jim Byrnes wrote: > On 02/10/2013 01:10 PM, Joel Goldstick wrote: >> On Sun, Feb 10, 2013 at 1:53 PM, Timo wrote: >> >>> Op 10-02-13 17:01, Jim Byrnes schreef: >>> >>> On 02/09/2013 05:46 AM, Albert-Jan Roskam wrote: >>>> >>>>> ----- Original Message ----- >>>>> >>>>> From: Jim Byrnes To: tutor at python.org Cc: >>>>>> Sent: Saturday, February 9, 2013 3:02 AM Subject: [Tutor] Which pip >>>>>> for Ubuntu 12.04 >>>>>> >>>>>> How important is it to have the latest pip installed? >>>>>> >>>>>> Initially I want to use it to install the latest pymongo driver for >>>>>> mongoDB. The pip version in the Ubuntu 12.04 repositories is 1.0.1. >>>>>> I see on >>>>>> http://www.pip-installer.org/**en/latest/the >>>>>> version is >>>>>> 1.2.1. >>>>>> >>>>>> It certainly would be easier to install from the repositories but >>>>>> will that version work to install the latest python packages? >>>>>> >>>>>> Thanks, Jim >>>>>> >>>>> >>>>> You could just try it? And downloading it and then doing sudo tar >>>>> -xvr pip.tar.gz, cd ..., sudo python setup.py isn't that hard, is >>>>> it? >>>>> >>>> >>>> I usually install from the repositories or maybe a ppa so I don't >>>> believe >>>> I have ever done an install from a tar. If necessary I will >>>> familiarize >>>> myself with the command you gave (yes I saw your followup changing >>>> -xvr to >>>> -xvf) and install that way. >>>> >>>> However, I still wonder if using the outdated pip from the repository >>>> will allow me to install the latest python packages? Will trying to >>>> use an >>>> outdated pip cause me problems? >>>> >>> I doubt it will. Have a look at the pip changelog to see what has been >>> changed. >>> >>> Timo >>> >>> >>> >>> >>>> But you're right, I also nnoticed that the Canonical repositories are >>>>> a little outdated sometimes. Would be nice if it's possible to add >>>>> pypi.org, so updating would be easier. >>>>> >>>>> Albert-Jan >>>>> >>>> >>>> >>>> Thanks, Jim >>>> >>>> ______________________________**_________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/**mailman/listinfo/tutor >>>> >>>> >>> >>> ______________________________**_________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/**mailman/listinfo/tutor >>> >>> >> >> >> >> You can upgrade pip with pip i believe: >> >> jcg at jcg-desktop:~/code/python\$ pip install pip >> Requirement already satisfied (use --upgrade to upgrade): pip in >> /usr/lib/pymodules/python2.7 >> Cleaning up... >> jcg at jcg-desktop:~/code/python\$ >> >> >> jcg at jcg-desktop:~/code/python\$ pip install --upgrade pip >> >> >> Be sure to sudo before if you don't have permissions. >> >> > > I tried this on my laptop with the following results: > > jfb at jfb-tp:~\$ pip --version > pip 1.0 from /usr/lib/python2.7/dist-packages (python 2.7) > jfb at jfb-tp:~\$ pip install pip > Requirement already satisfied (use --upgrade to upgrade): pip in > /usr/lib/python2.7/dist-packages > Cleaning up... > > jfb at jfb-tp:~\$ sudo pip install --upgrade pip > [sudo] password for jfb: > Downloading/unpacking pip > Running setup.py egg_info for package pip > > warning: no files found matching '*.html' under directory 'docs' > warning: no previously-included files matching '*.txt' found under > directory 'docs/_build' > no previously-included directories found matching > 'docs/_build/_sources' > Installing collected packages: pip > Found existing installation: pip 1.0 > Uninstalling pip: > Successfully uninstalled pip > Running setup.py install for pip > > warning: no files found matching '*.html' under directory 'docs' > warning: no previously-included files matching '*.txt' found under > directory 'docs/_build' > no previously-included directories found matching > 'docs/_build/_sources' > Installing pip script to /usr/local/bin > Installing pip-2.7 script to /usr/local/bin > Successfully installed pip > Cleaning up... > jfb at jfb-tp:~\$ pip --version > bash: /usr/bin/pip: No such file or directory > jfb at jfb-tp:~\$ > > I not sure what the significance of the missing *.txt and *.html files > is but it looks like I have a path problem. I would appreciate any > pointers from anyone who has already solved this. > > Thanks, Jim > Apparently I was wrong about the path problem. I closed the terminal I used for the update and opened another session and now I get: \$pip --version pip 1.2.1 from /usr/local/lib/python2.7/dist-packages (python 2.7) I guess the real test will come when I attempt to use it to install a package. Regards, Jim From davea at davea.name Mon Feb 11 17:25:01 2013 From: davea at davea.name (Dave Angel) Date: Mon, 11 Feb 2013 11:25:01 -0500 Subject: [Tutor] help with inch to cms conversion . In-Reply-To: References: Message-ID: <51191B5D.8010900@davea.name> On 02/11/2013 11:06 AM, Pravya Reddy wrote: > Can you please help me with the code. > > #!/usr/bin/env python > """ > inchtocm.py > > """ First, remove that try/except until the code is free of obvious bugs. It's masking where the error actually occurs. Alternatively, include a variable there, and print the stack trace yourself. > > def Inchtocm(inches): > """Returns 2.54 * inches""" > return (2.54 * float(inches_number1)) As Joel pointed out, you're using a global instead of the parameter that was passed. Call float() on inches, not on some non-local variable. > > inches = None > while True: > try: > inches_number1 = input(input("How many inches you want to convert: > ")) Calling input(input()) doesn't do any favors. It echoes the first response, and waits for another one. The user doesn't probably realize that he has to type the number 455 twice. > inches = float(inches_number1) Since you're presumably getting the exception on this line, you should print out the value you're trying to convert. You can remove the print after it works. > print ("You got", Inchtocm(inches), "cm.") > print ("You converted", inches, "inches to cm.") > break > except ValueError: > print ("This is not a number!") > > The code is incomplete and i am not getting a proper output: > > How many inches you want to convert: 455 > 455 > This is not a number! > How many inches you want to convert: > -- DaveA From dyoo at hashcollision.org Mon Feb 11 17:48:03 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 11 Feb 2013 09:48:03 -0700 Subject: [Tutor] help with inch to cms conversion . In-Reply-To: References: Message-ID: On Mon, Feb 11, 2013 at 9:06 AM, Pravya Reddy wrote: > Can you please help me with the code. > > #!/usr/bin/env python > """ > inchtocm.py > > """ > > def Inchtocm(inches): > """Returns 2.54 * inches""" > return (2.54 * float(inches_number1)) I don't know if your curriculum talks about writing test cases for functions. If your instructors do not mention it, ask them, because it's a crucial concept. And if they have no clue about it (which is unfortunately possible), you probably will need to stretch a little to learn about them yourself. Python's default testing framework, unittest, unfortunately requires knowledge on how to use "classes", which you haven't probably seen yet. And it's a bit heavyweight, to boot. In lieu of that, you can use something simpler: just run your Inchtocm() with a few sample inputs first, and "assert" that they have the right value, like this: def Inchtocm(inches): """Returns 2.54 * inches""" return (2.54 * float(inches_number1)) assert Inchtocm(0) == 0 Note that we don't just call Inchtocm(), but check to see that it has the right value. This is important: otherwise, you are not really "testing" the function, but just making it run. The code above just has one test: usually, you want to add a few more. And you want to write them _before_ you code up the function. From alan.gauld at btinternet.com Mon Feb 11 18:46:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2013 17:46:43 +0000 Subject: [Tutor] How to log process handles and GDI objects in python In-Reply-To: References: Message-ID: On 11/02/13 04:25, Pai, Yogesh M wrote: > Hi Alan, > > Here are the additional details: > Python version: 2.7.3 > OS version: Windows 7 -64 bit > > I have an application that has a automation layer built in python. > During every subsequent runs, I want to log the process threads and GDI objects > ( the one you see in the Windows task manager) in my python code You can definitely do it from Python using the Win32 API (which is in turn available in Python via ctypes or the pythonwin package). But its a bit beyond the scope of this list, I'd suggest you will get more results on the Win32 mailing list (also on Gmane)... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 11 18:50:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2013 17:50:15 +0000 Subject: [Tutor] Code to open a website In-Reply-To: <51184602.7050302@pearwood.info> References: <1360487830.28294.YahooMailNeo@web163803.mail.gq1.yahoo.com> <1360488335.4141.YahooMailNeo@web186005.mail.ir2.yahoo.com> <51184602.7050302@pearwood.info> Message-ID: On 11/02/13 01:14, Steven D'Aprano wrote: > exit() and quit() (as added by the site.py module) are for interactive use. aha! > They're mostly there for the benefit of newbies. Experienced developers (at > least in the Unix/Linux world) usually know to exit interactive terminal > apps with Ctrl-D. I believe you use Ctrl-Z under Windows. Indeed, and Ctrl-D is how I exit the prompt... > For programmatic use in scripts, use sys.exit(), since the site module is > not guaranteed to run. Thanks for that clarification. No need to change my coding habits after all then :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 11 19:04:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2013 18:04:45 +0000 Subject: [Tutor] temp conversion problem was: Re: (no subject) In-Reply-To: References: Message-ID: Please always provide a meaningful subject line, it helps us find related posts more easily in future and will stimulate more focused responses than a no subject message (which implies we are dealing with a newbie with no net experience and therefore requiring a lot of time/effort to help)... On 11/02/13 15:56, Pravya Reddy wrote: > Can You Plaese help me with the code. Try to give us a bit more clue about what you think is wrong. What did you expect? What did you get? Otherwise we have to cut n paste the code and run it and then guess what you think is the problem... The more work we have to do the less likely we will bother. > def print_options(): > print ("Options:") > print (" 'p' print options") > print (" 'c' convert from celsius") > print (" 'f' convert from fahrenheit") > print (" 'q' quit the program") You could have had this return the menu as a string instead of printing it. Or you could have got the user input inside the function and returned the choice directly. Either would be better than this. > def celsius_to_fahrenheit(c_temp): > return 9.0/5.0*c_temp+32 > > def fahrenheit_to_celsius(f_temp): > return (f_temp - 32.0)*5.0/9.0 > > choice = "p" You could have printed the menu and got the users real choice here rather than set a default that you never use... > while choice != "q": > if choice == "c": > temp = input(input("Celsius temperature:")) > print ("Fahrenheit:",celsius_to_fahrenheit(temp)) > elif choice == "f": > temp = input("Fahrenheit temperature:") > print ("Celsius:",fahrenheit_to_celsius(temp)) > elif choice != "q": > print_options() This prints the menu if the user did not choose f or q. But wouldn't you want the menu displayed every time round the loop? > choice = input(input("option:")) Why two inputs? This prints option and reads the input. It then prints the option and reads another input. > The Output i got is: > Options: > 'p' print options > 'c' convert from celsius > 'f' convert from fahrenheit > 'q' quit the program > option:c > c It prints the menu Then it prints options and reads the value Then it prints that value and reads another value which it sets choice to. If your print_menu() function returned the menu as a string (and was called get_menu) you could do choice = input(get_menu()) or if it got the choice in the menu function it would look like choice = get_menu_item() Which is a lot simpler to read. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 11 19:19:19 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2013 18:19:19 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: Message-ID: On 11/02/13 05:14, neubyr wrote: > > I have a text file with each line in following format: > > Book Name, Author Name, Genre, Publication Date > > I would like to perform following queries on this file: > * Get all books written by an author > * Remove all books of an author > * Get information about a book (pretty print matching line!) > * Get books of particular genre > > Also, I would like to add and delete entries in this file. I am not > planning to use any database for this purpose and would like to get > better grasp on file parsing and classes/OOP. I need some help in > creating classes and following are my initial thoughts: > > # Create a class for Book object > class Book: > atributes: name, author_name, genre, publication-date > Yep, that looks like all you need. > # Create > Author: > attribute(s): name No idea why you want this. A waste of space ... > # Create class for reading and writing to the file > class Booksfile: > methods: ?? You do not create classes for functions. The functions are part of the class. You can have a list of Books read from the file as an attribute of your Books class. Populate it at program startup and write the edited list back at termination. (Or any other time you make a change for improved robustness) > * How do I associate/relate Book and Author classes so that it will help > me in getting information like 'get list of books written by an author'? > Data attribute? I woudn't have a separate Author class but, if you must, something like: class Book: def __init__(self, theAuthor,theTitle): self.Author = theAuthor self.title = theTitle class Author: def __init__(self,aName): self.name = aName myBook = Book(Author('Jane Austin'), 'Pride & Prejudice') > * Should I create a new Booksfile object for reading, writing and > deleting entries in the file OR add corresponding methods to the book > object itself? Instance methods in the Book for reading/writing single lines Class methods in Book for reading/writing the entire file (or standalone functions could also be used) into a bookList class attribute. > I am not planning to use SQLite or any database and would like to use > text file only. Appreciate any help on designing such application. As a learning exercise that's fine, for any real world problem it would be foolish. This is what databases were built for... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Mon Feb 11 19:36:42 2013 From: davea at davea.name (Dave Angel) Date: Mon, 11 Feb 2013 13:36:42 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: Message-ID: <51193A3A.2080907@davea.name> On 02/11/2013 01:19 PM, Alan Gauld wrote: > On 11/02/13 05:14, neubyr wrote: >> >> >> > >> * How do I associate/relate Book and Author classes so that it will help >> me in getting information like 'get list of books written by an author'? >> Data attribute? > > I woudn't have a separate Author class but, if you must, something like: > > class Book: > def __init__(self, theAuthor,theTitle): > self.Author = theAuthor > self.title = theTitle > > class Author: > def __init__(self,aName): > self.name = aName > > myBook = Book(Author('Jane Austin'), 'Pride & Prejudice') Big problem with that; then there may be multiple instances of Author, representing the same Author. Instead, there needs to be a factory function which reuses the same Author objects if an additional book with the same author is encountered. Without such an approach, one might as well stick with strings, which is what we each recommended. -- DaveA From pravyareddy at gmail.com Mon Feb 11 21:07:16 2013 From: pravyareddy at gmail.com (Pravya Reddy) Date: Mon, 11 Feb 2013 12:07:16 -0800 Subject: [Tutor] calling and returning functions. Message-ID: Can you please complete the code. #!/usr/bin/env python """ One function receives a value in inches and returns the equivalent value in cms like cm = 2.54 * in.The other function receives a value in cms and returns the equivalent value in inches like in = cm / 2.54.""" def conversion(inch,cm): """returns the value in cm and in.""" return (2.54 * float(inches)) return (float(cm) / 2.54) def GetInt(prompt): """Returns a number, or None if user doesn't answer.""" while True: said = input(input(prompt)) if not said: return None try: number = int(said) except ValueError: print (said, "is not a number.") continue return number def Test(): first = GetInt('Please enter inches:') if first: second = GetInt('Please enter cms:') print(first, "*", 2.54, "=", "cms") print(second, "/", 2.54, "=", "in") Test() -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Feb 11 21:20:05 2013 From: davea at davea.name (Dave Angel) Date: Mon, 11 Feb 2013 15:20:05 -0500 Subject: [Tutor] calling and returning functions. In-Reply-To: References: Message-ID: <51195275.5020607@davea.name> On 02/11/2013 03:07 PM, Pravya Reddy wrote: > Can you please complete the code. > > #!/usr/bin/env python > """ One function receives a value in inches and returns the equivalent > value in > cms like cm = 2.54 * in.The other function receives a value in cms and > returns > the equivalent value in inches like in = cm / 2.54.""" > > def conversion(inch,cm): > """returns the value in cm and in.""" > return (2.54 * float(inches)) > return (float(cm) / 2.54) This second line does nothing, since the first line always returns. But it doesn't matter much, since you never call it. Don't you want two functions? > def GetInt(prompt): > """Returns a number, or None if user doesn't answer.""" > while True: > said = input(input(prompt)) This has been corrected several times, by various people. What do you think it does, and what do you wish it would do? Is there ever a reason to call input with the results of a call to input? > if not said: > return None > try: > number = int(said) > except ValueError: > print (said, "is not a number.") > continue > return number The return never gets executed, since it follows an unconditional continue statement. Do you perhaps want it dedented? > def Test(): > first = GetInt('Please enter inches:') > if first: > second = GetInt('Please enter cms:') Do you always want to do a pair of conversions? if not, why are you asking for both values before doing anything? > print(first, "*", 2.54, "=", "cms") This prints an equation without actually printing a result. > print(second, "/", 2.54, "=", "in") Ditto. > Test() > -- DaveA From ahmetcan196 at gmail.com Mon Feb 11 21:21:25 2013 From: ahmetcan196 at gmail.com (Ahmet Can KEPENEK) Date: Mon, 11 Feb 2013 22:21:25 +0200 Subject: [Tutor] Additional help In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> Message-ID: Hello, I used regular expression module of python. I checked binary and denary numbers. If input is invalid i ask again. I edited your code. Code is below follow as . import re def show_menu(): print("=======================") print("1-binary to denary") print("2-denary to binary") print("3-exit") print("=======================") while True: show_menu() choice = raw_input("please enter an option: ") if choice == '1': binary = raw_input("Please enter a binary number: ") if re.match("^[0-1]*\$", binary): denary = 0 place_value = 1 for i in binary [::-1]: denary += place_value * int(i) place_value *= 2 print("The result is",denary) else: print("Warning! Please enter a binary number") continue elif choice == '2': denary2 = raw_input("Please enter a denary number: ") if re.match("^[0-9]*\$", denary2): denary2 = int(denary2) remainder = '' while denary2 > 0: remainder = str(denary2 % 2) + remainder denary2 >>= 1 print("The result is",remainder) else: print("Warning! Please enter a denary number") continue elif choice == '3': break elif choice not in '1' or '2' or '3': print("Invalid input-try again!") Output is ---------- ======================= 1-binary to denary 2-denary to binary 3-exit ======================= please enter an option: 1 Please enter a binary number: 110 ('The result is', 6) ======================= 1-binary to denary 2-denary to binary 3-exit ======================= please enter an option: 1 Please enter a binary number: 12 Warning! Please enter a binary number ======================= 1-binary to denary 2-denary to binary 3-exit ======================= please enter an option: 3 -------------- next part -------------- An HTML attachment was scrubbed... URL: From neubyr at gmail.com Mon Feb 11 23:48:21 2013 From: neubyr at gmail.com (neubyr) Date: Mon, 11 Feb 2013 16:48:21 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <51188827.8000301@davea.name> References: <51188827.8000301@davea.name> Message-ID: Thank you for your inputs Dave. That's really helpful. Reply in-line below: On Sun, Feb 10, 2013 at 11:56 PM, Dave Angel wrote: > On 02/11/2013 12:14 AM, neubyr wrote: > >> I have a text file with each line in following format: >> >> Book Name, Author Name, Genre, Publication Date >> >> I would like to perform following queries on this file: >> * Get all books written by an author >> * Remove all books of an author >> * Get information about a book (pretty print matching line!) >> * Get books of particular genre >> >> Also, I would like to add and delete entries in this file. I am not >> planning to use any database for this purpose and would like to get better >> grasp on file parsing and classes/OOP. >> > > I take it from this that this is a class assignment, and that neither > speed nor enormous data capacity nor concurrent operation is a requirement. > But your professor may have other requirements that you haven't told us > about. Not a class assignment, just picked up this problem as a learning exercise. > > > I need some help in creating classes > >> and following are my initial thoughts: >> >> # Create a class for Book object >> class Book: >> atributes: name, author_name, genre, publication-date >> >> # Create >> Author: >> attribute(s): name >> > > Is this in order to save space, since each Book instance can then have a > reference to an Author object, rather than a reference to a string > containing the Author's name. > > If you deem this class useful, then don't you also want one for Genre ? Hmm.. I didn't think about saving space by reference an object. I created separate class thinking from database/ORM perspective. I am not planning to use it right now anyway, but if I was creating a non-trivial application with database models then I would have had Books tables, Authors tables etc.. I think I don't need it here though. > > > > >> # Create class for reading and writing to the file >> class Booksfile: >> methods: ?? >> > > Why ? Are you transliterating this from Java ? Scrapped that class - adding add/list/delete methods in Book class. Thanks for pointing it out. > > > >> >> * How do I associate/relate Book and Author classes so that it will help >> me >> in getting information like 'get list of books written by an author'? Data >> attribute? >> > > If performance doesn't matter, then create one list of Book instances, and > search it for whichever characteristics you like. > > > > * Should I create a new Booksfile object for reading, writing and deleting >> entries in the file OR add corresponding methods to the book object >> itself? >> > > Neither, a pair of regular functions will do fine. One that loads when > you start the program, and another that saves the file when you exit. If > you really expect to update the file incrementally, deleting entries in it, > then think hard about your decision to roll your own database. A text file > isn't random access. > > > >> I am not planning to use SQLite or any database and would like to use text >> file only. Appreciate any help on designing such application. >> >> >> > The real question is where you might proceed after meeting these first > requirements. For example, if you expect the list to grow to a few hundred > million entries, then you'll need to be very careful about layout. And > starting and exiting the program would be very slow, since you can do > nothing till all the data has been loaded in and converted to objects. > > Or perhaps you'll want to have another file with additional author data, > associated with the first by carefully spelling the author's name the same > in all cases. In that case, having a separate Author class makes great > sense. So if you expect to grow in that direction, then you should create > the class now, even though it has only one attribute. > > > -- > DaveA > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > - N -------------- next part -------------- An HTML attachment was scrubbed... URL: From neubyr at gmail.com Mon Feb 11 23:49:39 2013 From: neubyr at gmail.com (neubyr) Date: Mon, 11 Feb 2013 16:49:39 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <51193A3A.2080907@davea.name> References: <51193A3A.2080907@davea.name> Message-ID: On Mon, Feb 11, 2013 at 12:36 PM, Dave Angel wrote: > On 02/11/2013 01:19 PM, Alan Gauld wrote: > >> On 11/02/13 05:14, neubyr wrote: >> >>> >>> >>> >>> >> * How do I associate/relate Book and Author classes so that it will help >>> me in getting information like 'get list of books written by an author'? >>> Data attribute? >>> >> >> I woudn't have a separate Author class but, if you must, something like: >> >> class Book: >> def __init__(self, theAuthor,theTitle): >> self.Author = theAuthor >> self.title = theTitle >> >> class Author: >> def __init__(self,aName): >> self.name = aName >> >> myBook = Book(Author('Jane Austin'), 'Pride & Prejudice') >> > > Big problem with that; then there may be multiple instances of Author, > representing the same Author. Instead, there needs to be a factory > function which reuses the same Author objects if an additional book with > the same author is encountered. Without such an approach, one might as > well stick with strings, which is what we each recommended. > > > -- > DaveA > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > Thank you for suggestions - Mitya, Dave and Alan. I am doing it as a learning exercise and it's not a class assignment. I have little experience with Ruby and now trying to learn Python. It's not going to be any production application and I haven't thought about concurrency problems yet. Based on suggestions, following is a code snippet that I have right now. I agree that there isn't any need of separate Author object right now, so I may remove it as well. I have created a class method 'list_by_author' to return list of books. I am not sure if class method is right approach to implement 'list_by_author' function as a class method is typically used as an alternative constructor. Here I am returning list of objects and not just an object. Any suggestions for improving this code will be really useful. class Book(object): def __init__(self,name,author,genre,pubdate): self.name = name self.author = author self.genre = genre self.pubdate = pubdate # TODO: use csv module # write/add method def add(self,uname,kname): """ Write book info to a file """ pass @classmethod def list_by_author(self,author): """ Return list of books of an author """ bookfile = config.bookfile books = [] # empty list - used as list of Books # TODO: improve regex regex = re.compile(author) with open (bookfile,'r') as f: for line in f: if regex.findall(line): # error prone - if name contains comma l = line.split(',') # create book object and append it to a list book = self(*l) books.append(book) return books # return list of books class Author(object): def __init__(self,name): self.name = name def books(self): """ Get list of books """ books = Book.list_by_author(self.name) return books - N -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 12 00:16:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2013 23:16:40 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> Message-ID: On 11/02/13 22:49, neubyr wrote: > is right approach to implement 'list_by_author' function as a class > method is typically used as an alternative constructor. Not at all that is only one use case for class methods. A class method is *any* method that operates on the whole class of objects - i.e. all instances(potentially including those still to be created) Now I agree that in some lanmguages they tend to be limited to factory metjods(eg Objective C implicitly goes that way) but in others like Smalltalk search methods and persistence etc are often found as class methods. In Python, because of it's hybrid nature, these are often "demoted" to global scope functions. > Here I am > returning list of objects and not just an object. Which is to say a subset of the class Book. Therefore quite reasonably a class method. > @classmethod > def list_by_author(self,author): > """ Return list of books of an author """ > bookfile = config.bookfile > books = [] # empty list - used as list of Books > # TODO: improve regex > regex = re.compile(author) > with open (bookfile,'r') as f: > for line in f: > if regex.findall(line): > # error prone - if name contains comma > l = line.split(',') > # create book object and append it to a list > book = self(*l) > books.append(book) > return books # return list of books I'd probably, for a small dataset, load a list of books into the class at startup and save it at termination. Which makes the search code easier and potentially can be data driven so you pass the filter attribute as a parameter. You can then use getattr() to find the value: def findBooks(cls, param, value): return [book for book in books if getattr(book, param) == value] You could make it more flexible still by defining the filter as a function and passing a lambda: def findBooks(cls, filterExp): return [book for book in books if filterExp(book)] Usage example: DickensBooks = Book.findBook(lambda b: 'Dickens' in b.author) Of course if you have a huge dataset then that won't work - which brings us back to a database :-) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 12 00:21:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Feb 2013 23:21:53 +0000 Subject: [Tutor] calling and returning functions. In-Reply-To: References: Message-ID: On 11/02/13 20:07, Pravya Reddy wrote: > > def conversion(inch,cm): > """returns the value in cm and in.""" > return (2.54 * float(inches)) > return (float(cm) / 2.54) return exits the function so the second return statement never gets executed. > def GetInt(prompt): > """Returns a number, or None if user doesn't answer.""" > while True: > said = input(input(prompt)) You are still using double input. That is almost never the right thing to do. > if not said: > return None > try: > number = int(said) > except ValueError: > print (said, "is not a number.") > continue > return number The continue will jump right back to the loop start so the return will never be executed. The only way this function will ever exit is if the user hits Enter twice and then it will return None. You need to rethink the logic here. > def Test(): > first = GetInt('Please enter inches:') > if first: > second = GetInt('Please enter cms:') > print(first, "*", 2.54, "=", "cms") > print(second, "/", 2.54, "=", "in") Since GetInt() can only ever return None the if will always fail and nothing will ever be printed. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From neubyr at gmail.com Tue Feb 12 01:55:36 2013 From: neubyr at gmail.com (neubyr) Date: Mon, 11 Feb 2013 18:55:36 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> Message-ID: On Mon, Feb 11, 2013 at 5:16 PM, Alan Gauld wrote: > On 11/02/13 22:49, neubyr wrote: > > is right approach to implement 'list_by_author' function as a class >> method is typically used as an alternative constructor. >> > > Not at all that is only one use case for class methods. > A class method is *any* method that operates on the whole class of objects > - i.e. all instances(potentially including those still to be created) > > Now I agree that in some lanmguages they tend to be limited to factory > metjods(eg Objective C implicitly goes that way) but in others like > Smalltalk search methods and persistence etc are often found as class > methods. In Python, because of it's hybrid nature, these are often > "demoted" to global scope functions. > > > > Here I am >> returning list of objects and not just an object. >> > > Which is to say a subset of the class Book. > Therefore quite reasonably a class method. > > > @classmethod >> def list_by_author(self,author): >> """ Return list of books of an author """ >> bookfile = config.bookfile >> books = [] # empty list - used as list of Books >> # TODO: improve regex >> regex = re.compile(author) >> with open (bookfile,'r') as f: >> for line in f: >> if regex.findall(line): >> # error prone - if name contains comma >> l = line.split(',') >> # create book object and append it to a list >> book = self(*l) >> books.append(book) >> return books # return list of books >> > > I'd probably, for a small dataset, load a list of books into the class at > startup and save it at termination. Which makes the search code easier and > potentially can be data driven so you pass the filter attribute as a > parameter. You can then use getattr() to find the value: > > def findBooks(cls, param, value): > return [book for book in books if getattr(book, param) == value] > > You could make it more flexible still by defining the filter as a function > and passing a lambda: > > def findBooks(cls, filterExp): > return [book for book in books if filterExp(book)] > > > Usage example: > > DickensBooks = Book.findBook(lambda b: 'Dickens' in b.author) > > > Of course if you have a huge dataset then that won't work - which brings > us back to a database :-) > > > HTH > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > That's really helpful Alan. Thank you for your inputs on class methods and how can I modify my existing find/list method. I am not using any database/ORM as I am trying to learn basic search/filter operations on file and enumerator objects. Also, ORMs generally add magic methods based on associations (at least with Ruby ActiveRecord: e.g. has_many and belongs_to associations). I would like to do it 'manually' before using any other library. -- N -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 12 01:58:31 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 12 Feb 2013 11:58:31 +1100 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: Message-ID: <511993B7.8040703@pearwood.info> On 11/02/13 16:14, neubyr wrote: > I have a text file with each line in following format: > > Book Name, Author Name, Genre, Publication Date > > I would like to perform following queries on this file: > * Get all books written by an author > * Remove all books of an author > * Get information about a book (pretty print matching line!) > * Get books of particular genre > > Also, I would like to add and delete entries in this file. I am not > planning to use any database for this purpose and would like to get better > grasp on file parsing and classes/OOP. I need some help in creating classes > and following are my initial thoughts: > > # Create a class for Book object > class Book: > atributes: name, author_name, genre, publication-date You could use a class. But since Books don't have any behaviour, a simple struct or record would be better than a class: from collections import namedtuple Book = namedtuple("Book", "name author genre date") lotr = Book("The Hobbit", "J.R.R. Tolkien", "Fantasy", "1937") This has the advantage of simplicity. But if you need to add behaviour to the Book class, e.g. validation of the fields, you should be able to inherit from a named tuple. Untested: class Book(namedtuple("Book", "name author genre date")): @property def genre(self): return super(Book, self).genre @genre.setter(self, value): super(Book, self).genre = value.title() # 'fantasy' -> 'Fantasy' > # Create > Author: > attribute(s): name As Alan suggested, a waste of time. Since the Author has no behaviour and only a single field, why not just use a string? > # Create class for reading and writing to the file > class Booksfile: > methods: ?? Why should this be a class? This is not Java. http://steve-yegge.blogspot.com.au/2006/03/execution-in-kingdom-of-nouns.html Just write a function that reads a file and returns a list of Books. Or perhaps I should say: Programmer().getwriter().write(MakeCallable(FileReader).setmethod("read", return_type=list, return_item_values=Book) > * How do I associate/relate Book and Author classes so that it will help me > in getting information like 'get list of books written by an author'? Data > attribute? You want to map authors to books. Whenever you want a mapping, use a dict: data = { 'J.R.R. Tolkien': [Book("The Hobbit"), Book("The Lord of the Rings")], 'Tom Clancy': [Book("The Hunt for Red October")], 'Terry Pratchett': [Book('Small Gods'), Book('Night Watch'), Book('Nation')], 'Stephenie Meyer': [ Book('Something about abusive boyfriends but that's okay because they sparkle')], } > * Should I create a new Booksfile object for reading, writing and deleting > entries in the file OR add corresponding methods to the book object itself? Heavens no. Why should the book know about the library catalog it is listed in? Your book class should be responsible for the book, and nothing but the book. -- Steven From neubyr at gmail.com Tue Feb 12 02:33:04 2013 From: neubyr at gmail.com (neubyr) Date: Mon, 11 Feb 2013 19:33:04 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <511993B7.8040703@pearwood.info> References: <511993B7.8040703@pearwood.info> Message-ID: On Mon, Feb 11, 2013 at 6:58 PM, Steven D'Aprano wrote: > On 11/02/13 16:14, neubyr wrote: > >> I have a text file with each line in following format: >> >> Book Name, Author Name, Genre, Publication Date >> >> I would like to perform following queries on this file: >> * Get all books written by an author >> * Remove all books of an author >> * Get information about a book (pretty print matching line!) >> * Get books of particular genre >> >> Also, I would like to add and delete entries in this file. I am not >> planning to use any database for this purpose and would like to get better >> grasp on file parsing and classes/OOP. I need some help in creating >> classes >> and following are my initial thoughts: >> >> # Create a class for Book object >> class Book: >> atributes: name, author_name, genre, publication-date >> > > > You could use a class. But since Books don't have any behaviour, a simple > struct or record would be better than a class: > > > from collections import namedtuple > Book = namedtuple("Book", "name author genre date") > > lotr = Book("The Hobbit", "J.R.R. Tolkien", "Fantasy", "1937") > > > This has the advantage of simplicity. But if you need to add behaviour to > the > Book class, e.g. validation of the fields, you should be able to inherit > from > a named tuple. Untested: > > > class Book(namedtuple("Book", "name author genre date")): > @property > def genre(self): > return super(Book, self).genre > @genre.setter(self, value): > super(Book, self).genre = value.title() # 'fantasy' -> 'Fantasy' > > > > # Create >> Author: >> attribute(s): name >> > > > As Alan suggested, a waste of time. Since the Author has no behaviour and > only a single field, why not just use a string? > > > > > # Create class for reading and writing to the file >> class Booksfile: >> methods: ?? >> > > Why should this be a class? This is not Java. > > http://steve-yegge.blogspot.**com.au/2006/03/execution-in-** > kingdom-of-nouns.html > > > Just write a function that reads a file and returns a list of Books. > > Or perhaps I should say: > > > Programmer().getwriter().**write(MakeCallable(FileReader)** > .setmethod("read", > return_type=list, return_item_values=Book) > > > > > * How do I associate/relate Book and Author classes so that it will help >> me >> in getting information like 'get list of books written by an author'? Data >> attribute? >> > > You want to map authors to books. Whenever you want a mapping, use a dict: > > > data = { > 'J.R.R. Tolkien': [Book("The Hobbit"), Book("The Lord of the Rings")], > 'Tom Clancy': [Book("The Hunt for Red October")], > 'Terry Pratchett': [Book('Small Gods'), Book('Night Watch'), > Book('Nation')], > 'Stephenie Meyer': [ > Book('Something about abusive boyfriends but that's okay because > they sparkle')], > > } > > > > * Should I create a new Booksfile object for reading, writing and deleting >> entries in the file OR add corresponding methods to the book object >> itself? >> > > Heavens no. Why should the book know about the library catalog it is > listed in? > Your book class should be responsible for the book, and nothing but the > book. > > > > > -- > Steven > > Thanks Steven! I have used namedtuple like approach in few Ruby programs (not the same problem) using Structs, but it didn't strike me for this exercise [1]. I am going to try this approach soon. I haven't added any validation methods for fields yet, but I am planning to add them soon - e.g. validate alphabets or alphanumeric characters etc. It may bring up new questions from my side, but I am sure you all will be glad to help.. :) 1. http://www.ruby-doc.org/core-1.9.3/Struct.html -N -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Feb 12 02:34:28 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 12 Feb 2013 12:34:28 +1100 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> Message-ID: <51199C24.1060708@pearwood.info> On 12/02/13 10:16, Alan Gauld wrote: > On 11/02/13 22:49, neubyr wrote: > >> is right approach to implement 'list_by_author' function as a class >> method is typically used as an alternative constructor. > > Not at all that is only one use case for class methods. > A class method is *any* method that operates on the whole class of >objects - i.e. all instances(potentially including those still to be >created) Strictly speaking, a class method is just a method which takes as its first argument the class itself, not the instance. What it does with that is completely open. The usual thing is to use class methods for alternative constructors, e.g. Decimal.fromfloat. If the class keeps a list of all instances, then the class method could walk the list and operate on each instance in turn. (But why would you do that?) If the class method modifies the class itself, then it could indirectly have an effect on each instance. Although class methods could do anything, it is hard to think of actually useful things for them to do apart from being used as a constructor. [...] >> Here I am >> returning list of objects and not just an object. > > Which is to say a subset of the class Book. > Therefore quite reasonably a class method. Just a minute, I think that is completely wrong. A Book is not a set, so how can you have subset of it? What is a subset of "Pride and Prejudice"? Perhaps chapter 5. There are more problems with this idea that you query the Book to get a list of books by some author. Suppose you did this: prpr = Book("Pride and Prejudice", "Jane Austin") prpr.list_by_author() Now *each and every* book is responsible for tracking all the other books by the same author. This is a lousy design. Even worse: prpr.list_by_author("Jane Austin") since now books are responsible for tracking ALL books by ALL authors, since the caller could say: prpr.list_by_author("Leo Tolstoy") Of course, books should know their own author, not the authors of other books, but authors should know all their own books: author = prpr.author # --> Author("Jane Austin") author.get_books() # --> return a list of books by this author This is an argument for making Authors a class, with behaviour, rather than just a string. >> @classmethod >> def list_by_author(self,author): >> """ Return list of books of an author """ >> bookfile = config.bookfile >> books = [] # empty list - used as list of Books [snip] First off, by convention the first argument to a class method should be called "cls", not "self". Secondly, here you are relying on a mysterious global "config", which points to a bookfile. What does this have to do with a book? - Does a nail keep track of the packet it came from? - Why should a book keep track of the catalog it was listed in? This should be a top level function, not a Book method. The rest of the method's design is also poor. You have already read the file once, to get the initial set of books. So why read the file again, every time you want to get some piece of information. Big databases, capable of holding billions of pieces of data, have to use disk-based storage because you can't keep that much data in memory at once. For anything smaller, you should only read and write to disk for persistence, everything else should use in-memory data structures. In this case, that means a dict. >> return books # return list of books Really? Thank goodness for the comment, I wouldn't have understood that line of code otherwise! *wink* -- Steven From alan.gauld at btinternet.com Tue Feb 12 02:56:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Feb 2013 01:56:24 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <51199C24.1060708@pearwood.info> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> Message-ID: On 12/02/13 01:34, Steven D'Aprano wrote: > If the class keeps a list of all instances, then the class method > could walk the list and operate on each instance in turn. (But why > would you do that?) Because its how classes work in some languages (like smalltalk). The class object represents all instances of the class. > Although class methods could do anything, it is hard to think of > actually useful things for them to do apart from being used as a > constructor. Again its the norm in Smalltalk apps to implement electors(searches) and other class wide operations in the class methods. Most Smalltalk classes have at least 5 or 6 class methods. >> Which is to say a subset of the class Book. >> Therefore quite reasonably a class method. > > Just a minute, I think that is completely wrong. A Book is not a set, > so how can you have subset of it? A Book is an instance of the class Book. Book is a class of object encompassing all books. So returning a subset of all instances of the class is normal class method behaviour. > What is a subset of "Pride and Prejudice"? Perhaps chapter 5. That might be a chapter or two? But Pride and Prejudice is not the class Book, it's an instance of Book. > There are more problems with this idea that you query the Book to get > a list of books by some author. Suppose you did this: > > prpr = Book("Pride and Prejudice", "Jane Austin") > prpr.list_by_author() No, you don't query the instance, you should query the class. Book.list_by_author() # -> a dict of lists keyed by author name? (One of the unfortunate features of Python's implementation of class methods is that you can call them from an instance which doesn't really make sense! IMHO) > Now *each and every* book is responsible for tracking all the other > books by the same author. This is a lousy design. Even worse: > > prpr.list_by_author("Jane Austin") > > since now books are responsible for tracking ALL books by ALL authors, Which is why it should be a class method not an instance one. And in the real world we'd do that by building class methods querying a database. > Of course, books should know their own author, not the authors of other > books, but authors should know all their own books: instances should, I agree. The Book class should know about all books in the class. > First off, by convention the first argument to a class method should be > called "cls", not "self". Yes, my bad. Although it is of course only a Python convention. > Secondly, here you are relying on a mysterious global "config", which > points to a bookfile. What does this have to do with a book? The storage mechanism is an implementation detail. In Smalltalk its part of the infrastructure of the runtime. > - Does a nail keep track of the packet it came from? No, but the nail factory may keep track of the nails it produces, or at least the batches... > - Why should a book keep track of the catalog it was listed in? A book wouldn't. but the Book class might. > The rest of the method's design is also poor. You have already read > the file once, to get the initial set of books. So why read the file > again, every time you want to get some piece of information. This I agree with. It would be better to persist the data somewhere for a small dataset. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From richkappler at gmail.com Tue Feb 12 05:27:32 2013 From: richkappler at gmail.com (richard kappler) Date: Mon, 11 Feb 2013 23:27:32 -0500 Subject: [Tutor] sockets and networking Message-ID: I want to be able to communicate between a raspberry pi and a laptop running ubuntu, transferring text from the pi to the laptop. Specifically the Pi would be running poscketsphinx speech rec and would send the generated text through the crossover between the two ethernet ports to a python program on the laptop. Someone suggest using sockets, with which I am completely unfamiliar. I've read the socket docs and admit I find them quite confusing. Can someone point me to a/some good beginner tutorials on sockets/networking for me to look at? regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Feb 12 05:37:40 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 11 Feb 2013 23:37:40 -0500 Subject: [Tutor] sockets and networking In-Reply-To: References: Message-ID: On Mon, Feb 11, 2013 at 11:27 PM, richard kappler wrote: > I've read the socket docs and admit I find them quite confusing. Can someone > point me to a/some good beginner tutorials on sockets/networking for me to > look at? Try Doug Hellmann's Python Module of the Week: http://www.doughellmann.com/PyMOTW/socket From alan.gauld at btinternet.com Tue Feb 12 09:47:46 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Feb 2013 08:47:46 +0000 Subject: [Tutor] sockets and networking In-Reply-To: References: Message-ID: On 12/02/13 04:27, richard kappler wrote: > ports to a python program on the laptop. Someone suggest using sockets, > with which I am completely unfamiliar. I've read the socket docs and > admit I find them quite confusing. Can someone point me to a/some good > beginner tutorials on sockets/networking for me to look at? You can try the network programming topic in my tutor (v2 only) Its probably worth reading the Inter-process comms topic too since some of the concepts apply to sockets. After that the HowTo and other official docs should make sense. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Tue Feb 12 10:02:52 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 12 Feb 2013 04:02:52 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> Message-ID: On Mon, Feb 11, 2013 at 8:56 PM, Alan Gauld wrote: > (One of the unfortunate features of Python's implementation of > class methods is that you can call them from an instance which > doesn't really make sense! IMHO) Smalltalk derives a metaclass for the class methods, in parallel with the class. That's an option in Python, if you prefer it. It can hinder multiple inheritance, however. Using a classmethod object is more flexible. From neubyr at gmail.com Tue Feb 12 18:32:18 2013 From: neubyr at gmail.com (neubyr) Date: Tue, 12 Feb 2013 11:32:18 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <51199C24.1060708@pearwood.info> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> Message-ID: On Mon, Feb 11, 2013 at 7:34 PM, Steven D'Aprano wrote: > On 12/02/13 10:16, Alan Gauld wrote: > >> On 11/02/13 22:49, neubyr wrote: >> >> is right approach to implement 'list_by_author' function as a class >>> method is typically used as an alternative constructor. >>> >> >> Not at all that is only one use case for class methods. >> A class method is *any* method that operates on the whole class of >> objects - i.e. all instances(potentially including those still to be >> created) >> > > > Strictly speaking, a class method is just a method which takes as its > first argument the class itself, not the instance. What it does with > that is completely open. > > The usual thing is to use class methods for alternative constructors, > e.g. Decimal.fromfloat. > > If the class keeps a list of all instances, then the class method > could walk the list and operate on each instance in turn. (But why > would you do that?) > > If the class method modifies the class itself, then it could indirectly > have an effect on each instance. > > Although class methods could do anything, it is hard to think of > actually useful things for them to do apart from being used as a > constructor. > > [...] > > Here I am >>> returning list of objects and not just an object. >>> >> >> Which is to say a subset of the class Book. >> Therefore quite reasonably a class method. >> > > Just a minute, I think that is completely wrong. A Book is not a set, > so how can you have subset of it? > > What is a subset of "Pride and Prejudice"? Perhaps chapter 5. > > There are more problems with this idea that you query the Book to get > a list of books by some author. Suppose you did this: > > prpr = Book("Pride and Prejudice", "Jane Austin") > prpr.list_by_author() > > Now *each and every* book is responsible for tracking all the other > books by the same author. This is a lousy design. Even worse: > > prpr.list_by_author("Jane Austin") > > > since now books are responsible for tracking ALL books by ALL authors, > since the caller could say: > > prpr.list_by_author("Leo Tolstoy") > > > Of course, books should know their own author, not the authors of other > books, but authors should know all their own books: > > author = prpr.author # --> Author("Jane Austin") > > author.get_books() # --> return a list of books by this author > > > This is an argument for making Authors a class, with behaviour, rather > than just a string. > > > > @classmethod >>> def list_by_author(self,author): >>> """ Return list of books of an author """ >>> bookfile = config.bookfile >>> books = [] # empty list - used as list of Books >>> >> [snip] > > > First off, by convention the first argument to a class method should be > called "cls", not "self". > > Secondly, here you are relying on a mysterious global "config", which > points to a bookfile. What does this have to do with a book? > > - Does a nail keep track of the packet it came from? > > - Why should a book keep track of the catalog it was listed in? > > This should be a top level function, not a Book method. > > The rest of the method's design is also poor. You have already read > the file once, to get the initial set of books. So why read the file > again, every time you want to get some piece of information. > > Big databases, capable of holding billions of pieces of data, have > to use disk-based storage because you can't keep that much data in > memory at once. For anything smaller, you should only read and write > to disk for persistence, everything else should use in-memory data > structures. In this case, that means a dict. > > > > return books # return list of books >>> >> > Really? Thank goodness for the comment, I wouldn't have understood > that line of code otherwise! > > *wink* > > > :) Thank you for your inputs Steven. I will keep your suggestions in mind while refactoring this code. I am not following your comment on opening books file twice in list_by_author method. I have opened it only once and then reading each line while checking for a regex match. Am I missing something? - N -------------- next part -------------- An HTML attachment was scrubbed... URL: From Marcin.Mleczko at onet.eu Tue Feb 12 18:43:25 2013 From: Marcin.Mleczko at onet.eu (Marcin Mleczko) Date: Tue, 12 Feb 2013 18:43:25 +0100 Subject: [Tutor] Question on regular expressions In-Reply-To: References: Message-ID: <511A7F3D.8070209@onet.eu> Hello, given this kind of string: "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end" a search string like: r"start.*?end" would give me the entire string from the first "start" to "end" : "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end" but I am interested only in the second part between the 2nd "start" and the "end": "start AnotherArbitraryAmountOfText end" What would be best, most clever way to search for that? Or even more general: how do I exlude always the text between the last "start" and the "end" tag assuming the entire text contains several "start" tags spaced by an arbitrary amount of text befor the "end" tag? Any ideas? Thank you in advance. ;-) Marcin From alan.gauld at btinternet.com Tue Feb 12 19:40:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Feb 2013 18:40:06 +0000 Subject: [Tutor] Question on regular expressions In-Reply-To: <511A7F3D.8070209@onet.eu> References: <511A7F3D.8070209@onet.eu> Message-ID: On 12/02/13 17:43, Marcin Mleczko wrote: > but I am interested only in the second part between the 2nd "start" and > the "end": "start AnotherArbitraryAmountOfText end" > > What would be best, most clever way to search for that? best and clever are not always the same. The simplest way if its a fixed string is just use the string split() method... being more 'clever' you could use the re.split() method to handle non-constant strings. Being even more clever you can define regex of increasing complexity to match the Nth appearance of a pattern. These kinds of regex are very easy to get wrong so you have to be very clever to get them right. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Tue Feb 12 20:01:09 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Feb 2013 20:01:09 +0100 Subject: [Tutor] Question on regular expressions References: <511A7F3D.8070209@onet.eu> Message-ID: Marcin Mleczko wrote: > given this kind of string: > > "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end" > > a search string like: r"start.*?end" would give me the entire string > from the first "start" to "end" : "start SomeArbitraryAmountOfText start > AnotherArbitraryAmountOfText end" > > but I am interested only in the second part between the 2nd "start" and > the "end": "start AnotherArbitraryAmountOfText end" > > What would be best, most clever way to search for that? > > Or even more general: how do I exlude always the text between the last > "start" and the "end" tag assuming the entire text contains several > "start" tags spaced by an arbitrary amount of text befor the "end" tag? >>> s = "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end" >>> [t[::-1] for t in re.compile("dne(.*?)trats").findall(s[::-1])] [' AnotherArbitraryAmountOfText '] Ok, I'm not serious about this one -- but how about >>> parts = (t.partition("end") for t in s.split("start")) >>> [left for left, mid, right in parts if mid] [' AnotherArbitraryAmountOfText '] From richkappler at gmail.com Tue Feb 12 21:48:56 2013 From: richkappler at gmail.com (richard kappler) Date: Tue, 12 Feb 2013 15:48:56 -0500 Subject: [Tutor] sending a wav file to a website? Message-ID: Maybe way off scope here, I hope not. I just can't get the accuracy I need with pocketsphinx at the moment(though I continue to work on it). Google's webkit-speech actually works pretty durned well, here's an example: http://slides.html5rocks.com/#speech-input But that doesn't really solve any problems either. So the question is, how do I get a wav file to a website like the one listed above and retrieve the text result using python (or don't I)? I've looked at and played around with urllib, I get how it works, I'm pretty comfy with it, but it seems to be for sending text only? Or is it? I can use rec in the terminal (command line) to record speech into a wav file, I'm pretty sure I can figure out how to make it start and stop recording as desired, (yes, I've looked at pyaudio, my system crashed when I used it this morning, come to find out that may be a different problem so will look again), but sending the wav file to the url and retrieving the text for further processing has me a bit baffled. Any ideas? regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Feb 12 21:58:39 2013 From: davea at davea.name (Dave Angel) Date: Tue, 12 Feb 2013 15:58:39 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> Message-ID: <511AACFF.3080102@davea.name> On 02/12/2013 12:32 PM, neubyr wrote: > On Mon, Feb 11, 2013 at 7:34 PM, Steven D'Aprano wrote: > >> > > I am not following your comment on opening books file twice in > list_by_author method. I have opened it only once and then reading each > line while checking for a regex match. Am I missing something? > Not tiwce, 490 times. Each time you call that method, you're going to open and read the whole file? Why on earth would you do that, rather than just storing the Book instances in a list for later perusal? Read the file when starting, and save it when quitting. You did say you were going to be inserting and deleting books, right? You sure don't want to write that code to manage a text file. -- DaveA From breamoreboy at yahoo.co.uk Tue Feb 12 22:55:42 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 12 Feb 2013 21:55:42 +0000 Subject: [Tutor] Question on regular expressions In-Reply-To: <511A7F3D.8070209@onet.eu> References: <511A7F3D.8070209@onet.eu> Message-ID: On 12/02/2013 17:43, Marcin Mleczko wrote: > Hello, > > given this kind of string: > > "start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end" > > a search string like: r"start.*?end" would give me the entire string > from the first "start" to "end" : "start SomeArbitraryAmountOfText start > AnotherArbitraryAmountOfText end" > > but I am interested only in the second part between the 2nd "start" and > the "end": "start AnotherArbitraryAmountOfText end" > > What would be best, most clever way to search for that? > > Or even more general: how do I exlude always the text between the last > "start" and the "end" tag assuming the entire text contains several > "start" tags spaced by an arbitrary amount of text befor the "end" tag? > > Any ideas? > > Thank you in advance. ;-) > > Marcin > IMHO the best way is to use the rindex method to grab what you're after. I don't do clever, it makes code too difficult to maintain. So how about. >>> a="start SomeArbitraryAmountOfText start AnotherArbitraryAmountOfText end" >>> b="start " >>> x=a.rindex(b) >>> y=a.rindex(' end') >>> a[x+len(b):y] 'AnotherArbitraryAmountOfText' >>> c="garbage in, garbage out" >>> x=c.rindex(b) Traceback (most recent call last): File "", line 1, in ValueError: substring not found >>> -- Cheers. Mark Lawrence From steve at pearwood.info Tue Feb 12 23:56:56 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 13 Feb 2013 09:56:56 +1100 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> Message-ID: <511AC8B8.80207@pearwood.info> On 13/02/13 04:32, neubyr wrote: > I am not following your comment on opening books file twice in > list_by_author method. I have opened it only once and then reading each > line while checking for a regex match. Am I missing something? You open the catalog file once to read the books in the first place. Then when you want a list of books by author Fred, you open the catalog file, even though all the books are (somewhere) in memory. Then when you want a list of books by author Bob, you open the catalog file again. Then when you want a list of books by Sally, you open the catalog file yet again. And so on. -- Steven From alan.gauld at btinternet.com Wed Feb 13 02:10:38 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Feb 2013 01:10:38 +0000 Subject: [Tutor] sending a wav file to a website? In-Reply-To: References: Message-ID: On 12/02/13 20:48, richard kappler wrote: > So the question is, how do I get a wav file to a website like the one > listed above and retrieve the text result using python Can you be a bit more explicit? You can send the file to a url using http or ftp. That will create a copy of the file on the remote server but I get the feeling that's not what you mean? > I've looked at and played around with urllib, I get how it works, I'm > pretty comfy with it, but it seems to be for sending text only? It speaks http, and http is a text based protocol, like most internet protocols. But urllib is normally used for reading from a url not writing files to it. (Although it might support that too, but I've never used it for that...) > I can use rec in the terminal (command line) to record speech into > a wav file, I'm pretty sure I can figure out how to make it start and > stop recording as desired, ... Creating a wav file is completely different to sending it to a remote server. > ... but sending the wav file to the > url and retrieving the text for further processing has me a bit baffled. But this bit I don't understand? Do you mean sending the file itself? Or are you trying to play the recorded sound over the network to a url? If the latter how do you imagine the server will respond?What text do you expect back? I'm confused. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Wed Feb 13 08:33:01 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 13 Feb 2013 02:33:01 -0500 Subject: [Tutor] sending a wav file to a website? In-Reply-To: References: Message-ID: On Tue, Feb 12, 2013 at 3:48 PM, richard kappler wrote: > So the question is, how do I get a wav file to a website like the one listed > above and retrieve the text result using python (or don't I)? I've looked at > and played around with urllib, I get how it works, I'm pretty comfy with it, > but it seems to be for sending text only? Or is it? Are you looking to use Google's speech recognition service? It's meant for use with the Chrome browser. I suppose you can play around with it for non-commercial, personal use. Bear in mind Google can pull the plug on public access to the API at any time. Here's the unofficial spec: https://gist.github.com/1730160 And a rough draft: import urllib import urllib2 import json SPEECH_URL = 'https://www.google.com/speech-api/v1/recognize' CLIENT = 'chromium' USER_AGENT = ( 'Mozilla/5.0 (X11; Linux x86_64) ' 'AppleWebKit/537.4 (KHTML like Gecko) ' 'Chrome/22.0.1229.56 Safari/537.4') def gspeech(data, rate=16000, lang='en-US', maxresults=10): params = urllib.urlencode({ 'lang': lang, 'maxresults': maxresults, 'client': CLIENT}) url = '{0}?{1}'.format(SPEECH_URL, params) header = { 'Content-Type': 'audio/x-flac; rate={0}'.format(rate), 'User-Agent': USER_AGENT} request = urllib2.Request(url, data, header) data = urllib2.urlopen(request).read() return json.loads(data) Sample data: http://archive.org/details/MichaelGraySampleSamplewav >>> url = ('http://archive.org/download/' ... 'MichaelGraySampleSamplewav/Sample.flac') >>> data = urllib2.urlopen(url).read() >>> result = gspeech(data, 44100, 'en-UK') >>> result['hypotheses'][0]['utterance'] u"I'm speaking normally" >>> result['hypotheses'][0]['confidence'] 0.7365484 From Mahadea at LabCorp.com Wed Feb 13 14:45:09 2013 From: Mahadea at LabCorp.com (Mahadevan, Anand) Date: Wed, 13 Feb 2013 13:45:09 +0000 Subject: [Tutor] "Strange" behaviour of list comprehension Message-ID: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> I'm playing around with list comprehension and in IDLE typed this in. I actually wanted it to return all tuples satisfying the condition where z is the sum of x and y. I kind of got mixed up with the syntax, hence I put a comma in there instead of an "if". I'd like some assistance understanding what it's doing... Thanks! >>> somelist = [(x,y,z) for x in range(1,10) for y in range(x,10) for z in range(y,10), x+y==z] >>> somelist [(1, 1, [1, 2, 3, 4, 5, 6, 7, 8, 9]), (1, 1, False), (1, 2, [2, 3, 4, 5, 6, 7, 8, 9]), (1, 2, False), (1, 3, [3, 4, 5, 6, 7, 8, 9]), (1, 3, False), (1, 4, [4, 5, 6, 7, 8, 9]), (1, 4, False), (1, 5, [5, 6, 7, 8, 9]), (1, 5, False), (1, 6, [6, 7, 8, 9]), (1, 6, False), (1, 7, [7, 8, 9]), (1, 7, False), (1, 8, [8, 9]), (1, 8, False), (1, 9, [9]), (1, 9, False), (2, 2, [2, 3, 4, 5, 6, 7, 8, 9]), (2, 2, False), (2, 3, [3, 4, 5, 6, 7, 8, 9]), (2, 3, False), (2, 4, [4, 5, 6, 7, 8, 9]), (2, 4, False), (2, 5, [5, 6, 7, 8, 9]), (2, 5, False), (2, 6, [6, 7, 8, 9]), (2, 6, False), (2, 7, [7, 8, 9]), (2, 7, False), (2, 8, [8, 9]), (2, 8, False), (2, 9, [9]), (2, 9, False), (3, 3, [3, 4, 5, 6, 7, 8, 9]), (3, 3, False), (3, 4, [4, 5, 6, 7, 8, 9]), (3, 4, False), (3, 5, [5, 6, 7, 8, 9]), (3, 5, False), (3, 6, [6, 7, 8, 9]), (3, 6, False), (3, 7, [7, 8, 9]), (3, 7, False), (3, 8, [8, 9]), (3, 8, False), (3, 9, [9]), (3, 9, False), (4, 4, [4, 5, 6, 7, 8, 9]), (4, 4, False), (4, 5, [5, 6, 7, 8, 9]), (4, 5, False), (4, 6, [6, 7, 8, 9]), (4, 6, False), (4, 7, [7, 8, 9]), (4, 7, False), (4, 8, [8, 9]), (4, 8, False), (4, 9, [9]), (4, 9, False), (5, 5, [5, 6, 7, 8, 9]), (5, 5, False), (5, 6, [6, 7, 8, 9]), (5, 6, False), (5, 7, [7, 8, 9]), (5, 7, False), (5, 8, [8, 9]), (5, 8, False), (5, 9, [9]), (5, 9, False), (6, 6, [6, 7, 8, 9]), (6, 6, False), (6, 7, [7, 8, 9]), (6, 7, False), (6, 8, [8, 9]), (6, 8, False), (6, 9, [9]), (6, 9, False), (7, 7, [7, 8, 9]), (7, 7, False), (7, 8, [8, 9]), (7, 8, False), (7, 9, [9]), (7, 9, False), (8, 8, [8, 9]), (8, 8, False), (8, 9, [9]), (8, 9, False), (9, 9, [9]), (9, 9, False)] -This e-mail and any attachments may contain CONFIDENTIAL information, including PROTECTED HEALTH INFORMATION. If you are not the intended recipient, any use or disclosure of this information is STRICTLY PROHIBITED; you are requested to delete this e-mail and any attachments, notify the sender immediately, and notify the LabCorp Privacy Officer at privacyofficer at labcorp.com or call (877) 23-HIPAA / (877) 234-4722. From oscar.j.benjamin at gmail.com Wed Feb 13 15:13:50 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 13 Feb 2013 14:13:50 +0000 Subject: [Tutor] "Strange" behaviour of list comprehension In-Reply-To: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> References: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> Message-ID: On 13 February 2013 13:45, Mahadevan, Anand wrote: > I'm playing around with list comprehension and in IDLE typed this in. I actually wanted it to return all tuples satisfying the condition where z is the sum of x and y. I kind of got mixed up with the syntax, hence I put a comma in there instead of an "if". I'd like some assistance understanding what it's doing... > Thanks! > >>>> somelist = [(x,y,z) for x in range(1,10) for y in range(x,10) for z in range(y,10), x+y==z] This line doesn't actually work if you paste it into a fresh interpreter: >>> somelist = [(x,y,z) for x in range(1,10) for y in range(x,10) for z in range(y,10), x+y==z] Traceback (most recent call last): File "", line 1, in NameError: name 'z' is not defined The clause at the end x+y==z should be preceded by 'if' rather than a comma. Commas separate function arguments and elements of collections in displays. Expressions separated by commas without brackets are interpreted as tuples: >>> a = 1, 0 >>> a (1, 0) So your outermost loop is over a tuple (range(y, 10), x+y==z): >>> [x for x in 1, 2] [1, 2] >>> [x for x in 'a', 'w', 'b'] ['a', 'w', 'b'] >>> [x for x in range(3), False] [[0, 1, 2], False] Which explains the output you get: >>>> somelist > [(1, 1, [1, 2, 3, 4, 5, 6, 7, 8, 9]), (1, 1, False), (1, 2, [2, 3, 4, 5, 6, 7, 8, 9]), (1, 2, False), (1, 3, [3, 4, 5, 6, 7, 8, 9]), (1, 3, False), (1, 4, [4, 5, 6, 7, 8, 9]), (1, 4, False), (1, 5, [5, 6, 7, 8, 9]), (1, 5, False), (1, 6, [6, 7, 8, 9]), (1, 6, False), (1, 7, [7, 8, 9]), (1, 7, False), (1, 8, [8, 9]), (1, 8, False), (1, 9, [9]), (1, 9, False), (2, 2, [2, 3, 4, 5, 6, 7, 8, 9]), (2, 2, False), (2, 3, [3, 4, 5, 6, 7, 8, 9]), (2, 3, False), (2, 4, [4, 5, 6, 7, 8, 9]), (2, 4, False), (2, 5, [5, 6, 7, 8, 9]), (2, 5, False), (2, 6, [6, 7, 8, 9]), (2, 6, False), (2, 7, [7, 8, 9]), (2, 7, False), (2, 8, [8, 9]), (2, 8, False), (2, 9, [9]), (2, 9, False), (3, 3, [3, 4, 5, 6, 7, 8, 9]), (3, 3, False), (3, 4, [4, 5, 6, 7, 8, 9]), (3, 4, False), (3, 5, [5, 6, 7, 8, 9]), (3, 5, False), (3, 6, [6, 7, 8, 9]), (3, 6, False), (3, 7, [7, 8, 9]), (3, 7, False), (3, 8, [8, 9]), (3, 8, False), (3, 9, [9]), (3, 9, False), (4, 4, [4, 5, 6, 7, 8, 9]), (4, 4, False), (4, 5, [5, 6, 7, 8, 9]), (4 > , 5, False), (4, 6, [6, 7, 8, 9]), (4, 6, False), (4, 7, [7, 8, 9]), (4, 7, False), (4, 8, [8, 9]), (4, 8, False), (4, 9, [9]), (4, 9, False), (5, 5, [5, 6, 7, 8, 9]), (5, 5, False), (5, 6, [6, 7, 8, 9]), (5, 6, False), (5, 7, [7, 8, 9]), (5, 7, False), (5, 8, [8, 9]), (5, 8, False), (5, 9, [9]), (5, 9, False), (6, 6, [6, 7, 8, 9]), (6, 6, False), (6, 7, [7, 8, 9]), (6, 7, False), (6, 8, [8, 9]), (6, 8, False), (6, 9, [9]), (6, 9, False), (7, 7, [7, 8, 9]), (7, 7, False), (7, 8, [8, 9]), (7, 8, False), (7, 9, [9]), (7, 9, False), (8, 8, [8, 9]), (8, 8, False), (8, 9, [9]), (8, 9, False), (9, 9, [9]), (9, 9, False)] If you put the 'if' keyword in place of the comma it should work: >>> [x for x in 'a', 'w', 'b' if x != 'b'] ['a', 'w'] Oscar From __peter__ at web.de Wed Feb 13 15:16:58 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Feb 2013 15:16:58 +0100 Subject: [Tutor] "Strange" behaviour of list comprehension References: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> Message-ID: Mahadevan, Anand wrote: > I'm playing around with list comprehension and in IDLE typed this in. I > actually wanted it to return all tuples satisfying the condition where z > is the sum of x and y. I kind of got mixed up with the syntax, hence I put > a comma in there instead of an "if". I'd like some assistance > understanding what it's doing... Thanks! > >>>> somelist = [(x,y,z) for x in range(1,10) for y in range(x,10) for z in >>>> range(y,10), x+y==z] somelist If you're puzzled about a list comprehension, try translating it into for loops: somelist = [] for x in range(1, 10): for y in range(x, 10): for z in range(y, 10), x+y==z: somelist.append((x, y, z)) In the first iteration you get x=1, y=1, so let's see what the inner loop gives: >>> x = y = 1 >>> for z in range(y, 10), x+y==z: ... print z ... Traceback (most recent call last): File "", line 1, in NameError: name 'z' is not defined So if you don't get a NameError you have defined z before entering the inner "loop". Let's fix that: >>> z = 42 >>> for z in range(y, 10), x+y==z: ... print z ... [1, 2, 3, 4, 5, 6, 7, 8, 9] False It should be obvious now that Python interprets range(y, 10), x+y==z as a tuple and iterates over that. range(1, 10) is a list in Python 2, so you are getting that first, then follows a boolean expression x+y == z which gives either True or False. From hugo.yoshi at gmail.com Wed Feb 13 15:17:54 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 13 Feb 2013 15:17:54 +0100 Subject: [Tutor] "Strange" behaviour of list comprehension In-Reply-To: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> References: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> Message-ID: On Wed, Feb 13, 2013 at 2:45 PM, Mahadevan, Anand wrote: > I'm playing around with list comprehension and in IDLE typed this in. I > actually wanted it to return all tuples satisfying the condition where z is > the sum of x and y. I kind of got mixed up with the syntax, hence I put a > comma in there instead of an "if". I'd like some assistance understanding > what it's doing... > Thanks! > > >>> somelist = [(x,y,z) for x in range(1,10) for y in range(x,10) for z in > range(y,10), x+y==z] > >>> somelist > [(1, 1, [1, 2, 3, 4, 5, 6, 7, 8, 9]), (1, 1, False), (1, 2, [2, 3, 4, 5, > 6, 7, 8, 9]), (1, 2, False), (1, 3, [3, 4, 5, 6, 7, 8, 9]), (1, 3, False), > (1, 4, [4, 5, 6, 7, 8, 9]), (1, 4, False), (1, 5, [5, 6, 7, 8, 9]), (1, 5, > False), (1, 6, [6, 7, 8, 9]), (1, 6, False), (1, 7, [7, 8, 9]), (1, 7, > False), (1, 8, [8, 9]), (1, 8, False), (1, 9, [9]), (1, 9, False), (2, 2, > [2, 3, 4, 5, 6, 7, 8, 9]), (2, 2, False), (2, 3, [3, 4, 5, 6, 7, 8, 9]), > (2, 3, False), (2, 4, [4, 5, 6, 7, 8, 9]), (2, 4, False), (2, 5, [5, 6, 7, > 8, 9]), (2, 5, False), (2, 6, [6, 7, 8, 9]), (2, 6, False), (2, 7, [7, 8, > 9]), (2, 7, False), (2, 8, [8, 9]), (2, 8, False), (2, 9, [9]), (2, 9, > False), (3, 3, [3, 4, 5, 6, 7, 8, 9]), (3, 3, False), (3, 4, [4, 5, 6, 7, > 8, 9]), (3, 4, False), (3, 5, [5, 6, 7, 8, 9]), (3, 5, False), (3, 6, [6, > 7, 8, 9]), (3, 6, False), (3, 7, [7, 8, 9]), (3, 7, False), (3, 8, [8, 9]), > (3, 8, False), (3, 9, [9]), (3, 9, False), (4, 4, [4, 5, 6, 7, 8, 9]), (4, > 4, False), (4, 5, [5, 6, 7, 8, 9]), (4 > , 5, False), (4, 6, [6, 7, 8, 9]), (4, 6, False), (4, 7, [7, 8, 9]), (4, > 7, False), (4, 8, [8, 9]), (4, 8, False), (4, 9, [9]), (4, 9, False), (5, > 5, [5, 6, 7, 8, 9]), (5, 5, False), (5, 6, [6, 7, 8, 9]), (5, 6, False), > (5, 7, [7, 8, 9]), (5, 7, False), (5, 8, [8, 9]), (5, 8, False), (5, 9, > [9]), (5, 9, False), (6, 6, [6, 7, 8, 9]), (6, 6, False), (6, 7, [7, 8, > 9]), (6, 7, False), (6, 8, [8, 9]), (6, 8, False), (6, 9, [9]), (6, 9, > False), (7, 7, [7, 8, 9]), (7, 7, False), (7, 8, [8, 9]), (7, 8, False), > (7, 9, [9]), (7, 9, False), (8, 8, [8, 9]), (8, 8, False), (8, 9, [9]), (8, > 9, False), (9, 9, [9]), (9, 9, False)] > This list comprehension is basically interpreted like so: [(x,y,z) for x in range(1,10) for y in range(x,10) for z in (range(y,10), x+y==z)] To be more precise, the comma at the end is part of a tuple (you can omit parentheses of a tuple in many cases). This makes the final for loop iterate over the tuple (range(y, 10), x + y == z). You'll notice that this only works if the variable 'z' is already defined, since the tuple isn't constructed in the for loop. In other words, if we just run the code in a clean interpreter we'll get a NameError: Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> [(x,y,z) for x in range(1,10) for y in range(x,10) for z in range(y,10), x+y==z] Traceback (most recent call last): File "", line 1, in [(x,y,z) for x in range(1,10) for y in range(x,10) for z in range(y,10), x+y==z] NameError: name 'z' is not defined What happened in your case is probably you were running different variations of the list comprehension in the same interpreter session. Since the iterating variable in a for loop still exists after the for loop exits, we won't encounter this error if we run a slightly different list comprehension first: Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> [(x,y,z) for x in range(1,10) for y in range(x,10) for z in range(y,10) if x+y==z] [(1, 1, 2), (1, 2, 3), (1, 3, 4), (1, 4, 5), (1, 5, 6), (1, 6, 7), (1, 7, 8), (1, 8, 9), (2, 2, 4), (2, 3, 5), (2, 4, 6), (2, 5, 7), (2, 6, 8), (2, 7, 9), (3, 3, 6), (3, 4, 7), (3, 5, 8), (3, 6, 9), (4, 4, 8), (4, 5, 9)] >>> z 9 >>> As you can see, z exists after we run a for loop with z in it. Its value is still at the value it had during the last iteration. The same applies to x and y. Looking at your output, you had values of x, y and z in your interpreter session such that x + y == z evaluated to False. So the third value in your tuples is cycling between range(y, 10) and False. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Feb 13 16:18:12 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 13 Feb 2013 15:18:12 +0000 Subject: [Tutor] "Strange" behaviour of list comprehension In-Reply-To: References: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> Message-ID: On 13/02/2013 14:17, Hugo Arts wrote: > > To be more precise, the comma at the end is part of a tuple (you can > omit parentheses of a tuple in many cases). Parantheses are not part of a tuple except in special cases, see http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences -- Cheers. Mark Lawrence From brajesh_pant at hotmail.com Wed Feb 13 16:23:28 2013 From: brajesh_pant at hotmail.com (Brajesh) Date: Wed, 13 Feb 2013 20:53:28 +0530 Subject: [Tutor] Python Lover Message-ID: Hi , I have just subscribed mailing list to learn python. I am programming in java for nearly 8 months, I have developed a strong love towards python and want to learn and start making the best use of it. I want to know where to from as i know JAVA already so where to start from. Regards Brajesh From joel.goldstick at gmail.com Wed Feb 13 16:32:22 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 13 Feb 2013 10:32:22 -0500 Subject: [Tutor] Python Lover In-Reply-To: References: Message-ID: On Wed, Feb 13, 2013 at 10:23 AM, Brajesh wrote: > Hi , > > I have just subscribed mailing list to learn python. I am programming in > java for nearly 8 months, I have developed a strong love towards python and > want to learn and start making the best use of it. I want to know where to > from as i know JAVA already so where to start from. > You can start here: http://www.python.org/about/gettingstarted/ > > Regards > Brajesh > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From neubyr at gmail.com Wed Feb 13 20:14:17 2013 From: neubyr at gmail.com (neubyr) Date: Wed, 13 Feb 2013 13:14:17 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <511AC8B8.80207@pearwood.info> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> Message-ID: On Tue, Feb 12, 2013 at 4:56 PM, Steven D'Aprano wrote: > On 13/02/13 04:32, neubyr wrote: > > I am not following your comment on opening books file twice in >> list_by_author method. I have opened it only once and then reading each >> line while checking for a regex match. Am I missing something? >> > > > You open the catalog file once to read the books in the first place. > > Then when you want a list of books by author Fred, you open the catalog > file, even though all the books are (somewhere) in memory. > > Then when you want a list of books by author Bob, you open the catalog > file again. Then when you want a list of books by Sally, you open the > catalog file yet again. And so on. > > > > Thank you for your feedback Dave and Steven. I realize that I am opening the file for every add/delete call. I thought you were referring to duplicate file open call within the code snippet itself. I am not sure how to save an object in memory to a file before exiting the program. Any examples or related documentation links would be really helpful. I am guessing it would be using some kind of before teardown method, but not sure about it. Any help? thanks, N -------------- next part -------------- An HTML attachment was scrubbed... URL: From ghasemmg01 at leedslearning.net Wed Feb 13 20:13:05 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Wed, 13 Feb 2013 19:13:05 +0000 Subject: [Tutor] Binary Addition Message-ID: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> Hi guys can you tell me what is wrong with this code?. It says unexpected indent and the bottom of the code everytime I run it. Thank you on=True while on == True: def eight_digit_binary1(message): response1 = input(message) while len(response1) > 8: response1 = input(message) return (response1) try: binary1 = eight_digit_binary1('please enter the first 8 bit binary number: '); denary1 = 0 place_value1 = 1 for i in binary1 [::-1]: denary1 += place_value1 * int(i) place_value1 *= 2 def eight_digit_binary2(message): response2 = input(message) while len(response2) > 8: response2 = input(message) return (response2) try: binary2 = eight_digit_binary2('please enter the first 8 bit binary number: '); denary2 = 0 place_value2 = 1 for i in binary2 [::-1]: denary2 += place_value2 * int(i) place_value2 *= 2 def print_result(result): result = (place_value1 + place_value2) remainder = '' while result > 0: remainder = str(result % 2) + remainder result >>= 1 print("The result is",remainder) From breamoreboy at yahoo.co.uk Wed Feb 13 20:51:08 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 13 Feb 2013 19:51:08 +0000 Subject: [Tutor] Binary Addition In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 13/02/2013 19:13, Ghadir Ghasemi wrote: > Hi guys can you tell me what is wrong with this code?. It says unexpected indent and the bottom of the code everytime I run it. Thank you > > > on=True > while on == True: > def eight_digit_binary1(message): > response1 = input(message) > while len(response1) > 8: > response1 = input(message) > return (response1) > > > try: > > binary1 = eight_digit_binary1('please enter the first 8 bit binary number: '); > denary1 = 0 > place_value1 = 1 > > for i in binary1 [::-1]: > denary1 += place_value1 * int(i) > place_value1 *= 2 > > > def eight_digit_binary2(message): > response2 = input(message) > while len(response2) > 8: > response2 = input(message) > return (response2) > > > try: > > binary2 = eight_digit_binary2('please enter the first 8 bit binary number: '); > denary2 = 0 > place_value2 = 1 > > for i in binary2 [::-1]: > denary2 += place_value2 * int(i) > place_value2 *= 2 > > def print_result(result): > result = (place_value1 + place_value2) > remainder = '' > while result > 0: > remainder = str(result % 2) + remainder > result >>= 1 > print("The result is",remainder) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The while loops and return statements in the eight_digit_binary1/2 functions aren't correctly indented. Why put these functions within the outer while loop? The trys aren't matched up with anything, you need something else, usually one or more except clauses. -- Cheers. Mark Lawrence From alan.gauld at btinternet.com Wed Feb 13 20:50:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Feb 2013 19:50:48 +0000 Subject: [Tutor] Binary Addition In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 13/02/13 19:13, Ghadir Ghasemi wrote: > Hi guys can you tell me what is wrong with this code?. Quite a few things. Your try lines don't have matching excepts.... You have a function definitions in the middle that have indentation errors. eg. def eight_digit_binary1(message): response1 = input(message) while len(response1) > 8: response1 = input(message) return (response1) should be: def eight_digit_binary1(message): response1 = input(message) while len(response1) > 8: response1 = input(message) return (response1) Except that its buggy (what is returned if the user just hits Enter? Or types "fabulous"), but at least the indentation is right! Also, since you never seem to change 'on' anywhere you might as well use a while True loop.... It says unexpected indent and the bottom of the code everytime I run it. Thank you > > > on=True > while on == True: > def eight_digit_binary1(message): > response1 = input(message) > while len(response1) > 8: > response1 = input(message) > return (response1) > > > try: > > binary1 = eight_digit_binary1('please enter the first 8 bit binary number: '); > denary1 = 0 > place_value1 = 1 > > for i in binary1 [::-1]: > denary1 += place_value1 * int(i) > place_value1 *= 2 > > > def eight_digit_binary2(message): > response2 = input(message) > while len(response2) > 8: > response2 = input(message) > return (response2) > > > try: > > binary2 = eight_digit_binary2('please enter the first 8 bit binary number: '); > denary2 = 0 > place_value2 = 1 > > for i in binary2 [::-1]: > denary2 += place_value2 * int(i) > place_value2 *= 2 > > def print_result(result): > result = (place_value1 + place_value2) > remainder = '' > while result > 0: > remainder = str(result % 2) + remainder > result >>= 1 > print("The result is",remainder) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Wed Feb 13 20:50:09 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 13 Feb 2013 14:50:09 -0500 Subject: [Tutor] Binary Addition In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> Message-ID: <511BEE71.4060506@gmail.com> On 2/13/2013 2:13 PM, Ghadir Ghasemi wrote: > Hi guys can you tell me what is wrong with this code?. It says unexpected indent and the bottom of the code everytime I run it. Thank you Please post the entire traceback - there is valuable information there. Without that we have to go on a time consuming witch hunt. We are volunteers who love to help - with limits on our time and energy. Do you understand how Python uses indentation? The error you report says you have violated the indentation rules. > > > on=True > while on == True: > def eight_digit_binary1(message): > response1 = input(message) > while len(response1) > 8: > response1 = input(message) > return (response1) > > > try: > > binary1 = eight_digit_binary1('please enter the first 8 bit binary number: '); > denary1 = 0 > place_value1 = 1 > > for i in binary1 [::-1]: > denary1 += place_value1 * int(i) > place_value1 *= 2 > > > def eight_digit_binary2(message): > response2 = input(message) > while len(response2) > 8: > response2 = input(message) > return (response2) > > > try: > > binary2 = eight_digit_binary2('please enter the first 8 bit binary number: '); > denary2 = 0 > place_value2 = 1 > > for i in binary2 [::-1]: > denary2 += place_value2 * int(i) > place_value2 *= 2 > > def print_result(result): > result = (place_value1 + place_value2) > remainder = '' > while result > 0: > remainder = str(result % 2) + remainder > result >>= 1 > print("The result is",remainder) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Wed Feb 13 20:55:36 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Feb 2013 19:55:36 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> Message-ID: On 13/02/13 19:14, neubyr wrote: > I am not sure how to save an object in memory to a file > before exiting the program. Any examples or related documentation links > would be really helpful. I am guessing it would be using some kind of > before teardown method, but not sure about it. Any help? If using class methods or standalone functions just call them explicitly at the start and end of your program. If you want to be sure it gets called use a try/finally try: Book.loadBooks(filename) # load the data # do your program stuff finally: Book.saveBooks(filename) # save the data That ensures that even if there is an exception the data will always be saved. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Wed Feb 13 21:03:56 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 13 Feb 2013 15:03:56 -0500 Subject: [Tutor] Binary Addition In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE030D83794790@LLN-SPP-ES-04.user01.lln.local> Message-ID: <511BF1AC.7020507@gmail.com> On 2/13/2013 2:13 PM, Ghadir Ghasemi wrote: > Hi guys can you tell me what is wrong with this code?. It says unexpected indent and the bottom of the code everytime I run it. Thank you > > > on=True > while on == True: > def eight_digit_binary1(message): > response1 = input(message) > while len(response1) > 8: > response1 = input(message) > return (response1) > > > try: > > binary1 = eight_digit_binary1('please enter the first 8 bit binary number: '); > denary1 = 0 > place_value1 = 1 > > for i in binary1 [::-1]: > denary1 += place_value1 * int(i) > place_value1 *= 2 > > > def eight_digit_binary2(message): > response2 = input(message) > while len(response2) > 8: > response2 = input(message) > return (response2) > > > try: > > binary2 = eight_digit_binary2('please enter the first 8 bit binary number: '); > denary2 = 0 > place_value2 = 1 > > for i in binary2 [::-1]: > denary2 += place_value2 * int(i) > place_value2 *= 2 > > def print_result(result): > result = (place_value1 + place_value2) > remainder = '' > while result > 0: > remainder = str(result % 2) + remainder > result >>= 1 > print("The result is",remainder) You have some incomplete try: statements. try must be followed by except: and/or finally: You should limit the scope of try: to just the one or few statements that you expect to raise the exception. And you should have an except clause for that exception. There is no need to define eight_digit_binary and eight_digit_binary2, as they do the same thing. There is no need to nest these defs inside the loop. You have a lot of other unnecessarily duplicated code. There is no need to say while on == True: It is sufficient to say while on: Your program will never terminate as you never change the value of on. -- Bob Gailer 919-636-4239 Chapel Hill NC From ramit.prasad at jpmorgan.com Wed Feb 13 21:17:02 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 13 Feb 2013 20:17:02 +0000 Subject: [Tutor] Additional help In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE030D8379478F@LLN-SPP-ES-04.user01.lln.local> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418195229@SCACMX008.exchad.jpmchase.net> Ahmet Can KEPENEK wrote: > Hello, > I used regular expression module of python. I checked binary and denary numbers. If input is invalid i > ask again. I edited your code. Code is below follow as . > [snip] > ??????? if re.match("^[0-1]*\$", binary): > ??????? if re.match("^[0-9]*\$", denary2): [snip] Both of these will fail for empty strings (or '\n'). I will quote Steven D'Aprano's often quoted quotation regarding regular expressions. (Say that 5 times fast :) ) ''' Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. -- Jamie Zawinski ''' I think it would be more accurate (and easier) to convert to int and see if the conversion works. int(binary, 2) # binary = base 2 int(denary2, 10) # denary = base 10 ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From eryksun at gmail.com Wed Feb 13 23:16:20 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 13 Feb 2013 17:16:20 -0500 Subject: [Tutor] "Strange" behaviour of list comprehension In-Reply-To: References: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> Message-ID: On Wed, Feb 13, 2013 at 9:17 AM, Hugo Arts wrote: > To be more precise, the comma at the end is part of a tuple (you can omit > parentheses of a tuple in many cases). This makes the final for loop iterate > over the tuple (range(y, 10), x + y == z). You'll notice that this only > works if the variable 'z' is already defined, since the tuple isn't > constructed in the for loop. In 3.x the parser requires the parentheses in a list comprehension, but not in a for loop. And the list comprehension is compiled as a function, so you get an UnboundLocalError when trying to evaluate x+y==z. Just for fun, here's an example that makes a function from the code of a list comprehension in 3.x. The function takes the first iterator in the comprehension as an argument: >>> f = lambda: [(x,y) for x in 'ab' for y in 'cd'] >>> lcomp = type(f)(f.__code__.co_consts[1], globals()) >>> lcomp(iter('12')) [('1', 'c'), ('1', 'd'), ('2', 'c'), ('2', 'd')] Never do this. The code assumes the argument is an iterator, so it's easy to trigger a segfault: >>> lcomp('12') Segmentation fault From hugo.yoshi at gmail.com Wed Feb 13 23:45:53 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 13 Feb 2013 23:45:53 +0100 Subject: [Tutor] "Strange" behaviour of list comprehension In-Reply-To: <50BDA34A8AE5C2468A88793F841D54AB25881361@rtwedb05.lca.labcorp.com> References: <50BDA34A8AE5C2468A88793F841D54AB25880F13@rtwedb05.lca.labcorp.com> <50BDA34A8AE5C2468A88793F841D54AB25881361@rtwedb05.lca.labcorp.com> Message-ID: On Wed, Feb 13, 2013 at 10:07 PM, Mahadevan, Anand wrote: > Thanks for the good explanation, Hugo. Not sure of the protocol for > replying in this forum, when I clicked on reply it filled your id in. > Glad I could be of help :) For future reference, it's generally considered politest to send all replies over the tutor mailing list as well so we can all see them, especially if further discussion is possible. Either click "Reply All" or make sure you have tutor at python.org in your CC list. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Feb 13 23:39:26 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 13 Feb 2013 22:39:26 +0000 Subject: [Tutor] Python Lover In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4741819553A@SCACMX008.exchad.jpmchase.net> Brajesh wrote: > Hi , > > I have just subscribed mailing list to learn python. I am programming in > java for nearly 8 months, I have developed a strong love towards python > and want to learn and start making the best use of it. I want to know > where to from as i know JAVA already so where to start from. > > Regards > Brajesh Since you are from a Java background, I think it will help you to read the following articles. http://dirtsimple.org/2004/12/python-is-not-java.html And the counter article http://dirtsimple.org/2004/12/java-is-not-python-either.html I also think Doug Hellman's Module of the Week (MOTW) is an excellent reference for the standard library. http://www.doughellmann.com/PyMOTW/index.html ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From richkappler at gmail.com Thu Feb 14 00:14:57 2013 From: richkappler at gmail.com (richard kappler) Date: Wed, 13 Feb 2013 18:14:57 -0500 Subject: [Tutor] Having trouble figuring out bug Message-ID: I have tried to run the Google speech recognition code found here: https://github.com/jeysonmc/python-google-speech-scripts/blob/master/stt_google.py I am getting the following traceback: Traceback (most recent call last): File "", line 1, in File "GoogSTT.py", line 43, in listen_for_speech data = stream.read(chunk) File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 605, in read return pa.read_stream(self._stream, num_frames) which refers to this part of the code: while (True): data = stream.read(chunk) slid_win.append (abs(audioop.avg(data, 2))) if(True in [ x>THRESHOLD for x in slid_win]): if(not started): print "starting record" started = True all_m.append(data) elif (started==True): print "finished" #the limit was reached, finish capture and deliver filename = save_speech(all_m,p) stt_google_wav(filename) #reset all started = False slid_win = deque(maxlen=SILENCE_LIMIT*rel) all_m= [] print "listening ..." I have run another bit of code is very similar to the above, to wit: while 1: data = stream.read(CHUNK_SIZE) L = unpack('<' + ('h'*(len(data)/2)), data) # little endian, signed short L = array('h', L) LRtn.extend(L) and get no errors, the code runs fine and records. Please note that the line in question is virtually identical in both snippets of code, one works, one does not. To the best of my ability I have verified what I know how to, for example chunk is set with a value previous, etc. Not sure where I'm running into problems, could use some guidance. NOTE: I did not post the entire code here for brevity, but it is available at the listed website or, if it is preferred, I can post it in a follow-on email. regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Feb 14 00:56:16 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Feb 2013 10:56:16 +1100 Subject: [Tutor] Having trouble figuring out bug In-Reply-To: References: Message-ID: <511C2820.3050704@pearwood.info> On 14/02/13 10:14, richard kappler wrote: > I have tried to run the Google speech recognition code found here: > https://github.com/jeysonmc/python-google-speech-scripts/blob/master/stt_google.py > > I am getting the following traceback: > Traceback (most recent call last): > File "", line 1, in > File "GoogSTT.py", line 43, in listen_for_speech > data = stream.read(chunk) > File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 605, in read > return pa.read_stream(self._stream, num_frames) Awesome! Richard, if you hang around this mailing list for a while, you will soon see that we tutors have a lot of trouble convincing newbies to post the entire traceback, not just the error message. But this is the first time that somebody has posted the traceback EXCEPT for the error message. Well done, you win the Internet :-) Please try again and post the entire traceback, including the error message at the end. Thank you. -- Steven From steve at pearwood.info Thu Feb 14 01:51:43 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Feb 2013 11:51:43 +1100 Subject: [Tutor] Having trouble figuring out bug In-Reply-To: References: <511C2820.3050704@pearwood.info> Message-ID: <511C351F.8010207@pearwood.info> On 14/02/13 11:16, richard kappler wrote: > On Wed, Feb 13, 2013 at 6:56 PM, Steven D'Apranowrote: > >> On 14/02/13 10:14, richard kappler wrote: >> >>> I have tried to run the Google speech recognition code found here: >>> https://github.com/jeysonmc/**python-google-speech-scripts/** >>> blob/master/stt_google.py >>> >>> I am getting the following traceback: >>> Traceback (most recent call last): >>> File "", line 1, in >>> File "GoogSTT.py", line 43, in listen_for_speech >>> data = stream.read(chunk) >>> File "/usr/lib/python2.7/dist-**packages/pyaudio.py", line 605, in >>> read >>> return pa.read_stream(self._stream, num_frames) >>> >> >> >> Awesome! >> >> Richard, if you hang around this mailing list for a while, you will soon >> see that we tutors have a lot of trouble convincing newbies to post the >> entire traceback, not just the error message. But this is the first time >> that somebody has posted the traceback EXCEPT for the error message. >> >> Well done, you win the Internet :-) >> >> Please try again and post the entire traceback, including the error >> message at the end. >> >> Thank you. >> >> >> And now you see my dilemma. That's the error message, the whole bloody > thing. But for ye unbelievers out there, here's my entire screen, from the > call to the crash: > > python GoogSTT.py > ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear > ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe > ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side > ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) > BT_GET_CAPABILITIES failed : Input/output error(5) > ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) > BT_GET_CAPABILITIES failed : Input/output error(5) > ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) > BT_GET_CAPABILITIES failed : Input/output error(5) > ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) > BT_GET_CAPABILITIES failed : Input/output error(5) > ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only > playback stream > Cannot connect to server socket err = No such file or directory > Cannot connect to server request channel > jack server is not running or cannot be started > * listening. CTRL+C to finish. > starting record > ^CTraceback (most recent call last): > File "GoogSTT.py", line 108, in > listen_for_speech() > File "GoogSTT.py", line 43, in listen_for_speech > data = stream.read(chunk) > File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 605, in read > return pa.read_stream(self._stream, num_frames) > KeyboardInterrupt See that KeyboardInterrupt line? That was missing from your first post. You get that because you have hit Ctrl-C, which is Python's way of halting the running code (if possible). If you don't want this exception, then don't hit Ctrl-C. Which of course brings you to a dilemma -- the software tells you to use Ctrl-C to stop recording, but it apparently lies. I suggest that it is buggy. Looking at the source code to the library, here: https://github.com/jeysonmc/python-google-speech-scripts/blob/master/stt_google.py I'm pretty sure it is buggy. There is no attempt to catch the Ctrl-C and continue processing. I could be wrong, because I haven't actually tested it or studied it in detail, but I can't see how this could possibly work as advertised. Also the library includes something which gives me the absolute heebie-jeebies: it downloads a website from the Internet, then *executes it as code* without making any attempt to see what it is. If you run this library, you are giving Google, or anyone that manages to intercept your connection to Google, carte blanche to run ANY CODE THEY LIKE on your computer. I wouldn't touch that library with a fifty-foot pole until that is fixed. -- Steven From richkappler at gmail.com Thu Feb 14 02:03:10 2013 From: richkappler at gmail.com (richard kappler) Date: Wed, 13 Feb 2013 20:03:10 -0500 Subject: [Tutor] Having trouble figuring out bug In-Reply-To: <511C351F.8010207@pearwood.info> References: <511C2820.3050704@pearwood.info> <511C351F.8010207@pearwood.info> Message-ID: > See that KeyboardInterrupt line? That was missing from your first post. > > You get that because you have hit Ctrl-C, which is Python's way of halting > the running code (if possible). If you don't want this exception, then > don't hit Ctrl-C. > > Which of course brings you to a dilemma -- the software tells you to use > Ctrl-C to stop recording, but it apparently lies. I suggest that it is > buggy. Looking at the source code to the library, here: > > https://github.com/jeysonmc/**python-google-speech-scripts/** > blob/master/stt_google.py > > I'm pretty sure it is buggy. There is no attempt to catch the Ctrl-C and > continue processing. I could be wrong, because I haven't actually tested it > or studied it in detail, but I can't see how this could possibly work as > advertised. > > Also the library includes something which gives me the absolute > heebie-jeebies: it downloads a website from the Internet, then *executes it > as code* without making any attempt to see what it is. If you run this > library, you are giving Google, or anyone that manages to intercept your > connection to Google, carte blanche to run ANY CODE THEY LIKE on your > computer. I wouldn't touch that library with a fifty-foot pole until that > is fixed. Uh huh... That actually makes perfect sense and I'm a bit annoyed I didn't catch it. So... methinks that if I code in for the recording to end on say a second or two of silence, and get rid of the CTRL+C, then the code should proceed as necessary. Then I neeed to figure out how to make it more secure per your heebie-jeebies. Okay, once more into the breach dear tutors! thanks for the help, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From doanviettrung at gmail.com Thu Feb 14 05:08:53 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Thu, 14 Feb 2013 15:08:53 +1100 Subject: [Tutor] Python Lover In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741819553A@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF4741819553A@SCACMX008.exchad.jpmchase.net> Message-ID: I am also learning and have found it useful to learn from David Beazley's "Python In Action", parts 1 and 2. Part 2 is tough for me because I don't know other languages nor systems programming, but may be OK for you Brajesh. The slidepacks are at http://www.slideshare.net/dabeaz/presentations Trung Doan ============ On Thu, Feb 14, 2013 at 9:39 AM, Prasad, Ramit wrote: > Brajesh wrote: > > Hi , > > > > I have just subscribed mailing list to learn python. I am programming in > > java for nearly 8 months, I have developed a strong love towards python > > and want to learn and start making the best use of it. I want to know > > where to from as i know JAVA already so where to start from. > > > > Regards > > Brajesh > > Since you are from a Java background, I think it will help > you to read the following articles. > > http://dirtsimple.org/2004/12/python-is-not-java.html > And the counter article > http://dirtsimple.org/2004/12/java-is-not-python-either.html > > > I also think Doug Hellman's Module of the Week (MOTW) is an > excellent reference for the standard library. > http://www.doughellmann.com/PyMOTW/index.html > > > ~Ramit > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From richkappler at gmail.com Thu Feb 14 01:16:56 2013 From: richkappler at gmail.com (richard kappler) Date: Wed, 13 Feb 2013 19:16:56 -0500 Subject: [Tutor] Having trouble figuring out bug In-Reply-To: <511C2820.3050704@pearwood.info> References: <511C2820.3050704@pearwood.info> Message-ID: On Wed, Feb 13, 2013 at 6:56 PM, Steven D'Aprano wrote: > On 14/02/13 10:14, richard kappler wrote: > >> I have tried to run the Google speech recognition code found here: >> https://github.com/jeysonmc/**python-google-speech-scripts/** >> blob/master/stt_google.py >> >> I am getting the following traceback: >> Traceback (most recent call last): >> File "", line 1, in >> File "GoogSTT.py", line 43, in listen_for_speech >> data = stream.read(chunk) >> File "/usr/lib/python2.7/dist-**packages/pyaudio.py", line 605, in >> read >> return pa.read_stream(self._stream, num_frames) >> > > > Awesome! > > Richard, if you hang around this mailing list for a while, you will soon > see that we tutors have a lot of trouble convincing newbies to post the > entire traceback, not just the error message. But this is the first time > that somebody has posted the traceback EXCEPT for the error message. > > Well done, you win the Internet :-) > > Please try again and post the entire traceback, including the error > message at the end. > > Thank you. > > > And now you see my dilemma. That's the error message, the whole bloody thing. But for ye unbelievers out there, here's my entire screen, from the call to the crash: python GoogSTT.py ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5) ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5) ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5) ALSA lib audio/pcm_bluetooth.c:1614:(audioservice_expect) BT_GET_CAPABILITIES failed : Input/output error(5) ALSA lib pcm_dmix.c:957:(snd_pcm_dmix_open) The dmix plugin supports only playback stream Cannot connect to server socket err = No such file or directory Cannot connect to server request channel jack server is not running or cannot be started * listening. CTRL+C to finish. starting record ^CTraceback (most recent call last): File "GoogSTT.py", line 108, in listen_for_speech() File "GoogSTT.py", line 43, in listen_for_speech data = stream.read(chunk) File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 605, in read return pa.read_stream(self._stream, num_frames) KeyboardInterrupt So I call the script, when it says *listening I speak into the microphone, then hit CTRL+C and everything after starting to record spits out. When I run the script that fails not, it provides EXACTLY the same ALSA and jackserver output, but records the wav. regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From eva.bofias at gmail.com Thu Feb 14 13:57:04 2013 From: eva.bofias at gmail.com (Eva Bofias) Date: Thu, 14 Feb 2013 13:57:04 +0100 Subject: [Tutor] use of variables in re.sub Message-ID: Helo, I need to do a substitution in a regular expression that depends on a variable. To simplify I want to be able to do this substitution: text2='XX. AA YY. DD' re.sub(ur"\. (AA|BB|??","(.) \g<1>",text2) this would give as a result: 'XX(.) AA YY. DD' Which is exactly what I want. But when I try to substitute AA|BB|CC for a variable I do not know how to make it work. I wanted to use re.compile. I tryed: NP= u"AA|BB|??" reNP=re.compile(ur'%s'%NP) But if I try: reNP.match(text2) And I do not know how to use the variables in there. Should I use re.compile or is there something else that I should be using Thank you Eva Bofias -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Feb 14 18:35:40 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 14 Feb 2013 17:35:40 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> neubyr wrote: > I am not sure how to save an object in memory to a file before?exiting?the program. Any examples or > related documentation links would be really helpful. I am guessing it would be using some kind of > before teardown method, but not sure about it. Any help? Look at the pickle or shelve modules. http://www.doughellmann.com/PyMOTW/pickle/index.html http://www.doughellmann.com/PyMOTW/shelve/index.html This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From davea at davea.name Thu Feb 14 21:30:43 2013 From: davea at davea.name (Dave Angel) Date: Thu, 14 Feb 2013 15:30:43 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> Message-ID: <511D4973.7040308@davea.name> On 02/14/2013 12:35 PM, Prasad, Ramit wrote: > neubyr wrote: >> I am not sure how to save an object in memory to a file before exiting the program. Any examples or >> related documentation links would be really helpful. I am guessing it would be using some kind of >> before teardown method, but not sure about it. Any help? > > Look at the pickle or shelve modules. > http://www.doughellmann.com/PyMOTW/pickle/index.html > http://www.doughellmann.com/PyMOTW/shelve/index.html > You miss the point. The OP wants to make sure the text file is saved no matter how the program happens to exit. He's not asking how to format the file. -- DaveA From mmcconac at redhat.com Thu Feb 14 21:55:23 2013 From: mmcconac at redhat.com (Michael McConachie) Date: Thu, 14 Feb 2013 15:55:23 -0500 (EST) Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: Message-ID: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> Hello all, This is my first post here. I have tried to get answers from StackOverflow, but I realized quickly that I am too "green" for that environment. As such, I have purchased Beginning Python (2nd edition, Hetland) and also the \$29.00 course available from learnpythonthehardway(dot)com. I have been reading fervently, and have enjoyed python -- very much. I can do all the basic printing, math, substitutions, etc. Although, I am stuck when trying to combine all the new skills I have been learning over the past few weeks. Anyway, I was hoping to get some help with something NON-HOMEWORK related. (I swear.) I have a task that I have generalized due to the nature of what I am trying to do -- and it's need to remain confidential. My end goal as described on SO was: "Calculating and Plotting the Average of every (X) items in a list of (Y) total", but for now I am only stuck on the actual addition, and/or averaging items -- in a serial sense, based on the relation to the previous number, average of numbers, etc being acted on. Not the actual plotting. (Plotting is pretty EZ.) Essentially: 1. I have a list of numbers that already exist in a file. I generate this file by parsing info from logs. 2. Each line contains an integer on it (corresponding to the number of milliseconds that it takes to complete a certain repeated task). 3. There are over a million entries in this file, one per line; at any given time it can be just a few thousand, or more than a million. Example: ------- 173 1685 1152 253 1623 Eventually what I'll need to do is: 1. Index the file and/or count the lines, as to identify each line's positional relevance so that it can average any range of numbers that are sequential; one to one another. 2. Calculate the difference between any given (x) range. In order to be able to ask the program to average every 5, 10, 100, 100, or 10,000 etc. --> until completion. This includes the need to dealing with stray remainders at the end of the file that aren't divisible by that initial requested range. (ie: average some file with 3,245 entries by 100 --> not excluding the remaining 45 entries, in order to represent the remainder.) So, looking above, transaction #1 took "173" milliseconds, while transaction #2 took 1685 milliseconds. Based on this, I need to figure out how to do two things: 1. Calculate the difference of each transaction, related to the one before it AND record/capture the difference. (An array, list, dictionary -- I don't care.) 2. Starting with the very first line/entry, count the first (x number) and average (x). I can obtain a "Happy medium" for what the gradient/delta is between sets of 100 over the course of the aggregate. ie: --- Entries 1-100 = (eventualPlottedAvgTotalA) Entries 101-200 = (eventualPlottedAvgTotalB) Entries 201-300 = (eventualPlottedAvgTotalC) Entries 301-400 = (eventualPlottedAvgTotalD) >From what I can tell, I don't need to indefinitely store the values, only pass them as they are processed (in order) to the plotter. I have tried the following example to sum a range of 5 entries from the above list of 5 (which works), but I don't know how to dynamically pass the 5 at a time until completion, all the while retaining the calculated averages which will ultimately be passed to pyplot at a later time/date. What I have been able to figure out thus far is below. ex: Python 2.7.3 (default, Jul 24 2012, 10:05:38) [GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> plottedTotalA = ['173', '1685', '1152', '253', '1623'] >>> sum(float(t) for t in plottedTotalA) 4886.0 I received 2 answers from SO, but was unable to fully capture what they were trying to tell me. Unfortunately, I might need a "baby-step" / "Barney-style" mentor who is willing to guide me on this. I hope this makes sense to someone out there, and thank you in advance for any help that you can provide. I apologize in advance for being so thick if its uber-EZ. -- Mike From ramit.prasad at jpmorgan.com Thu Feb 14 22:33:26 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 14 Feb 2013 21:33:26 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <511D4973.7040308@davea.name> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> Dave Angel wrote: > On 02/14/2013 12:35 PM, Prasad, Ramit wrote: > > neubyr wrote: > >> I am not sure how to save an object in memory to a file before exiting the program. Any examples or > >> related documentation links would be really helpful. I am guessing it would be using some kind of > >> before teardown method, but not sure about it. Any help? > > > > Look at the pickle or shelve modules. > > http://www.doughellmann.com/PyMOTW/pickle/index.html > > http://www.doughellmann.com/PyMOTW/shelve/index.html > > > > You miss the point. The OP wants to make sure the text file is saved no > matter how the program happens to exit. He's not asking how to format > the file. > Hmm. Good point Dave, I did miss that point. My knee jerk response is a try/finally block, but I am sure there are better ways. # UNTESTED stored_data = {} try: stored_data = load_data() while True: # except Exception: raise # reraise exception to keep trace and still # propogate error for attention finally: store_data(stored_data) # Save data since we are exiting # (intentionally or not). ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Thu Feb 14 22:58:26 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Feb 2013 08:58:26 +1100 Subject: [Tutor] Python needs your help -- trademark under attack Message-ID: <511D5E02.7090105@pearwood.info> Hello all, The Python Software Foundation is the organisation which protects and manages the "boring" bits of keeping a big open source project alive: the legal and contractual parts, funding for projects, trademarks and copyrights. If you are based in Europe, or know somebody who uses Python in Europe, the PSF needs your help. There is a company in the UK who has applied to trademark the name "Python" and are claiming the *exclusive* right to use the word "Python" for software, servers, and web services over the entire European Union. You can read more about this here: http://pyfound.blogspot.com/2013/02/python-trademark-at-risk-in-europe-we.html If you have documentation of European user groups, trade associations, books, conferences, scans of job advertisements for Python programmers, software that uses some variation of "Python" in the name, etc. your evidence will be helpful in defeating this attempted grab of the Python name. You can also testify to the fact that when you read or hear of the name "Python" in relation to computers and the Internet, you think of Python the programming language. Thank you. -- Steven From davea at davea.name Thu Feb 14 23:01:05 2013 From: davea at davea.name (Dave Angel) Date: Thu, 14 Feb 2013 17:01:05 -0500 Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> Message-ID: <511D5EA1.8050109@davea.name> On 02/14/2013 03:55 PM, Michael McConachie wrote: > Hello all, > > This is my first post here. I have tried to get answers from StackOverflow, but I realized quickly that I am too "green" for that environment. As such, I have purchased Beginning Python (2nd edition, Hetland) and also the \$29.00 course available from learnpythonthehardway(dot)com. I have been reading fervently, and have enjoyed python -- very much. I can do all the basic printing, math, substitutions, etc. Although, I am stuck when trying to combine all the new skills I have been learning over the past few weeks. Anyway, I was hoping to get some help with something NON-HOMEWORK related. (I swear.) > > I have a task that I have generalized due to the nature of what I am trying to do -- and it's need to remain confidential. > > My end goal as described on SO was: "Calculating and Plotting the Average of every (X) items in a list of (Y) total", but for now I am only stuck on the actual addition, and/or averaging items -- in a serial sense, based on the relation to the previous number, average of numbers, etc being acted on. Not the actual plotting. (Plotting is pretty EZ.) > If you're stuck on the addition, why give us all the other parts? Your problem statement is very confused, and you don't show much actual code. > Essentially: > > 1. I have a list of numbers that already exist in a file. I generate this file by parsing info from logs. > 2. Each line contains an integer on it (corresponding to the number of milliseconds that it takes to complete a certain repeated task). > 3. There are over a million entries in this file, one per line; at any given time it can be just a few thousand, or more than a million. > > Example: > ------- > 173 > 1685 > 1152 > 253 > 1623 So write a loop that reads this file into a list of ints, converting each line. Then you can tell us you've got a list of about a million ints. > > Eventually what I'll need to do is: > > 1. Index the file and/or count the lines, as to identify each line's positional relevance so that it can average any range of numbers that are sequential; one to one another. > 2. Calculate the difference between any given (x) range. In order to be able to ask the program to average every 5, 10, 100, 100, or 10,000 etc. --> until completion. This includes the need to dealing with stray remainders at the end of the file that aren't divisible by that initial requested range. > > (ie: average some file with 3,245 entries by 100 --> not excluding the remaining 45 entries, in order to represent the remainder.) > > So, looking above, transaction #1 took "173" milliseconds, while transaction #2 took 1685 milliseconds. > > Based on this, I need to figure out how to do two things: > > 1. Calculate the difference of each transaction, related to the one before it AND record/capture the difference. (An array, list, dictionary -- I don't care.) What difference, what transaction, related how? > 2. Starting with the very first line/entry, count the first (x number) and average (x). I can obtain a "Happy medium" for what the gradient/delta is between sets of 100 over the course of the aggregate. What's an x-number? What, what, which, who ? > > ie: > --- > Entries 1-100 = (eventualPlottedAvgTotalA) > Entries 101-200 = (eventualPlottedAvgTotalB) > Entries 201-300 = (eventualPlottedAvgTotalC) > Entries 301-400 = (eventualPlottedAvgTotalD) > >>From what I can tell, I don't need to indefinitely store the values, only pass them as they are processed (in order) to the plotter. I have tried the following example to sum a range of 5 entries from the above list of 5 (which works), but I don't know how to dynamically pass the 5 at a time until completion, all the while retaining the calculated averages which will ultimately be passed to pyplot at a later time/date. > > What I have been able to figure out thus far is below. > > ex: > > Python 2.7.3 (default, Jul 24 2012, 10:05:38) > [GCC 4.7.0 20120507 (Red Hat 4.7.0-5)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> plottedTotalA = ['173', '1685', '1152', '253', '1623'] > >>> sum(float(t) for t in plottedTotalA) > 4886.0 > > I received 2 answers from SO, but was unable to fully capture what they were trying to tell me. Unfortunately, I might need a "baby-step" / "Barney-style" mentor who is willing to guide me on this. I hope this makes sense to someone out there, and thank you in advance for any help that you can provide. I apologize in advance for being so thick if its uber-EZ. > > If you want to make a sublist out of the first 2 items in a list, you can use a slice (notice the colon): allvalues = [ 173, 1685, 1152, 263, 1623, 19 ] firsttwo = allvalues[0:2] To get the 3rd such sublist, use othertwo = allvalues[4:2] If you've made such a list, you can readily use sum directly on it: mysum = sum(othertwo) -- DaveA From davea at davea.name Thu Feb 14 23:05:09 2013 From: davea at davea.name (Dave Angel) Date: Thu, 14 Feb 2013 17:05:09 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> Message-ID: <511D5F95.70606@davea.name> On 02/14/2013 04:33 PM, Prasad, Ramit wrote: > Dave Angel wrote: >> On 02/14/2013 12:35 PM, Prasad, Ramit wrote: >>> neubyr wrote: >>>> I am not sure how to save an object in memory to a file before exiting the program. Any examples or >>>> related documentation links would be really helpful. I am guessing it would be using some kind of >>>> before teardown method, but not sure about it. Any help? >>> >>> Look at the pickle or shelve modules. >>> http://www.doughellmann.com/PyMOTW/pickle/index.html >>> http://www.doughellmann.com/PyMOTW/shelve/index.html >>> >> >> You miss the point. The OP wants to make sure the text file is saved no >> matter how the program happens to exit. He's not asking how to format >> the file. >> > > Hmm. Good point Dave, I did miss that point. > > My knee jerk response is a try/finally block, but I am sure there > are better ways. > > # UNTESTED > stored_data = {} > try: > stored_data = load_data() > while True: > # > except Exception: > raise # reraise exception to keep trace and still > # propogate error for attention > finally: > store_data(stored_data) # Save data since we are exiting > # (intentionally or not). That would be my reaction as well. I would, however make it conditional on some changes having been made. That way if this program run only made queries, the effort and risk of saving can be avoided. The other thing I'd recommend is to store the data in an alternate file, and only delete the original when the alternate is ready to rename. That way, you can't readily get into trouble if something crashes while saving. -- DaveA From steve at pearwood.info Thu Feb 14 23:48:18 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 15 Feb 2013 09:48:18 +1100 Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> Message-ID: <511D69B2.9080802@pearwood.info> On 15/02/13 07:55, Michael McConachie wrote: > Essentially: > > 1. I have a list of numbers that already exist in a file. I generate this file by parsing info from logs. > 2. Each line contains an integer on it (corresponding to the number of milliseconds that it takes to complete a certain repeated task). > 3. There are over a million entries in this file, one per line; at any given time it can be just a few thousand, or more than a million. > > Example: > ------- > 173 > 1685 > 1152 > 253 > 1623 A million entries sounds like a lot to you or me, but to your computer, it's not. When you start talking tens or hundreds of millions, that's possibly a lot. Do you know how to read those numbers into a Python list? Here is the "baby step" way to do so: data = [] # Start with an empty list. f = open("filename") # Obviously you have to use the actual file name. for line in f: # Read the file one line at a time. num = int(line) # Convert each line into an integer (whole number) data.append(num) # and append it to the end of the list. f.close() # Close the file when done. Here's a more concise way to do it: with open("filename") as f: data = [int(line) for line in f] Once you have that list of numbers, you can sum the whole lot: sum(data) or just a range of the items: sum(data[:100]) # The first 100 items. sum(data[100:200]) # The second 100 items. sum(data[-50:]) # The last 50 items. sum(data[1000:]) # Item 1001 to the end. (See below.) sum(data[5:99:3]) # Every third item, starting at index 5 and ending at index 98. This is called "slicing", and it is perhaps the most powerful and useful technique that Python gives you for dealing with lists. The rules though are not necessarily the most intuitive though. A slice is either a pair of numbers separated with a colon, inside the square brackets: data[start:end] or a triple: data[start:end:step] Any of these three numbers can be left out. The default values are: start=0 end=length of the sequence being sliced step=1 They can also be negative. If start or end are negative, they are interpreted as "from the end" rather than "from the beginning". Item positions are counted from 0, which will be very familiar to C programmers. The start index is included in the slice, the end position is excluded. The model that you should think of is to imagine the sequence of items labelled with their index, starting from zero, and with a vertical line *between* each position. Here is a sequence of 26 items, showing the index in the first line and the value in the second: |0|1|2|3|4|5|6|7|8|9| ... |25| |a|b|c|d|e|f|g|h|i|j| ... |z | When you take a slice, the items are always cut at the left. So, if the above is called "letters", we have: letters[0:4] # returns "abcd" letters[2:8] # returns "cdefgh" letters[2:8:2] # returns "ceg" letters[-3:] # returns "xyz" > Eventually what I'll need to do is: > > 1. Index the file and/or count the lines, as to identify each line's positional relevance so that it can average any range of numbers that are sequential; one to one another. No need. Python already does that, automatically, when you read the data into a list. > 2. Calculate the difference between any given (x) range. In order to be able to ask the program to average every 5, 10, 100, 100, or 10,000 etc. --> until completion. This includes the need to dealing with stray remainders at the end of the file that aren't divisible by that initial requested range. I don't quite understand you here. First you say "difference", then you say "average". Can you show a sample of data, say, 10 values, and the sorts of typical calculations you want to perform, with the answers you expect to get? For example, here's 10 numbers: 103, 104, 105, 109, 111, 112, 115, 120, 123, 128 Here are the running averages of 3 values: (103+104+105)/3 (104+105+109)/3 (105+109+111)/3 (109+111+112)/3 (111+112+115)/3 (112+115+120)/3 (115+120+123)/3 (120+123+128)/3 Is that what you mean? If so, then Python can deal with this trivially, using slicing. With your data stored in list "data", as above, I can say: for i in range(0, len(data)-3): # Stop 3 from the end. print sum(data[i:i+3]) to print the running sums taking three items at a time. The rest of your post just confuses me. Until you explain exactly what calculations you are trying to perform, I can't tell you how to perform them :-) -- Steven From bgailer at gmail.com Thu Feb 14 23:06:57 2013 From: bgailer at gmail.com (bob gailer) Date: Thu, 14 Feb 2013 17:06:57 -0500 Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> Message-ID: <511D6001.1020804@gmail.com> On 2/14/2013 3:55 PM, Michael McConachie wrote: [snip] I agree with dave angel - the specification is far from clear. please clarify. perhaps a simple example that goes from input to desired output. -- Bob Gailer 919-636-4239 Chapel Hill NC From oscar.j.benjamin at gmail.com Fri Feb 15 01:29:38 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 15 Feb 2013 00:29:38 +0000 Subject: [Tutor] use of variables in re.sub In-Reply-To: References: Message-ID: On 14 February 2013 12:57, Eva Bofias wrote: > Helo, Hi, > I need to do a substitution in a regular expression that depends on a > variable. To simplify I want to be able to do this substitution: > > text2='XX. AA YY. DD' > re.sub(ur"\. (AA|BB|??","(.) \g<1>",text2) There is a missing bracket in that expression. did you mean ur"\. (AA|BB|??)"? > this would give as a result: > 'XX(.) AA YY. DD' > Which is exactly what I want. > > But when I try to substitute AA|BB|CC for a variable I do not know how to > make it work. How about this? >>> import re >>> text2='XX. AA YY. DD' >>> re.sub(ur"\. (AA|BB|??)",r"(.) \g<1>",text2) # ?Note the r"" raw string! 'XX(.) AA YY. DD' Or have I misunderstood? Oscar From neubyr at gmail.com Fri Feb 15 04:01:20 2013 From: neubyr at gmail.com (neubyr) Date: Thu, 14 Feb 2013 21:01:20 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> Message-ID: On Wed, Feb 13, 2013 at 1:55 PM, Alan Gauld wrote: > On 13/02/13 19:14, neubyr wrote: > > I am not sure how to save an object in memory to a file >> before exiting the program. Any examples or related documentation links >> would be really helpful. I am guessing it would be using some kind of >> before teardown method, but not sure about it. Any help? >> > > If using class methods or standalone functions just call them explicitly > at the start and end of your program. If you want to > be sure it gets called use a try/finally > > try: > Book.loadBooks(filename) # load the data > # do your program stuff > finally: > Book.saveBooks(filename) # save the data > > That ensures that even if there is an exception the data will always be > saved. > > > Thanks Alan! - N -------------- next part -------------- An HTML attachment was scrubbed... URL: From neubyr at gmail.com Fri Feb 15 04:09:49 2013 From: neubyr at gmail.com (neubyr) Date: Thu, 14 Feb 2013 21:09:49 -0600 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <511D5F95.70606@davea.name> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> <511D5F95.70606@davea.name> Message-ID: On Thu, Feb 14, 2013 at 4:05 PM, Dave Angel wrote: > On 02/14/2013 04:33 PM, Prasad, Ramit wrote: > >> Dave Angel wrote: >> >>> On 02/14/2013 12:35 PM, Prasad, Ramit wrote: >>> >>>> neubyr wrote: >>>> >>>>> I am not sure how to save an object in memory to a file before exiting >>>>> the program. Any examples or >>>>> related documentation links would be really helpful. I am guessing it >>>>> would be using some kind of >>>>> before teardown method, but not sure about it. Any help? >>>>> >>>> >>>> Look at the pickle or shelve modules. >>>> http://www.doughellmann.com/**PyMOTW/pickle/index.html >>>> http://www.doughellmann.com/**PyMOTW/shelve/index.html >>>> >>>> >>> You miss the point. The OP wants to make sure the text file is saved no >>> matter how the program happens to exit. He's not asking how to format >>> the file. >>> >>> >> Hmm. Good point Dave, I did miss that point. >> >> My knee jerk response is a try/finally block, but I am sure there >> are better ways. >> >> # UNTESTED >> stored_data = {} >> try: >> stored_data = load_data() >> while True: >> # >> except Exception: >> raise # reraise exception to keep trace and still >> # propogate error for attention >> finally: >> store_data(stored_data) # Save data since we are exiting >> # (intentionally or not). >> > > That would be my reaction as well. I would, however make it conditional > on some changes having been made. That way if this program run only made > queries, the effort and risk of saving can be avoided. > > The other thing I'd recommend is to store the data in an alternate file, > and only delete the original when the alternate is ready to rename. That > way, you can't readily get into trouble if something crashes while saving. > > > > > Thanks Ramit and Dave! I haven't had chance to code/learn further, but I will give play with this soon. I do have a doubt regarding this - e.g. how would I implement this if my program/application is web based. For example, loading the text file during web server start and stop. Hope to try it out soon! - N -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Feb 15 06:38:33 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 15 Feb 2013 00:38:33 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> Message-ID: On Thu, Feb 14, 2013 at 4:33 PM, Prasad, Ramit wrote: > My knee jerk response is a try/finally block, but I am sure there > are better ways. The atexit.register decorator hooks sys.exitfunc: http://docs.python.org/2/library/atexit Registered atexit functions are run early during interpreter finalization. Signal handling is still enabled (e.g. SIGINT), and you can still import. In the standard lib, logging and multiprocessing use atexit. In a C extension there's also Py_AtExit for registering a C function: http://docs.python.org/2/c-api/sys.html#Py_AtExit Calling the exitfuncs is the last task in Py_Finalize, after everything has been torn down, so they should not use the C-API. Example: import atexit from tempfile import NamedTemporaryFile from subprocess import Popen, PIPE from ctypes import CDLL, pythonapi @atexit.register def f(): print "shutdown: atexit" # register a C function with NamedTemporaryFile() as so: p = Popen(['gcc', '-xc', '-shared', '-fPIC', '-o', so.name, '-'], stdin=PIPE, stdout=so) p.communicate('''#include void fc(void) {printf("shutdown: Py_AtExit\\n");}''') fc = CDLL(so.name).fc # keep reference pythonapi.Py_AtExit(fc) try: raise RuntimeError finally: print "shutdown: finally" Output: shutdown: finally Traceback (most recent call last): File "atexit_example.py", line 20, in raise RuntimeError RuntimeError shutdown: atexit shutdown: Py_AtExit From alan.gauld at btinternet.com Fri Feb 15 09:58:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Feb 2013 08:58:40 +0000 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> <511D5F95.70606@davea.name> Message-ID: On 15/02/13 03:09, neubyr wrote: > I do have a doubt regarding this - e.g. how would I implement this if my > program/application is web based. For example, loading the text file > during web server start and stop. For a long running process like a web server this is probably the wrong approach. You probably want to save the data more regularly - maybe even at the end of every user transaction. But with a web server we have the additional problem of usually wanting to handle multiple requests in parallel so storing data in memory gets more complicated - which takes us back to using a data base which pretty much handles all of that for you. If you will only have a single request running at a time then you can use the same try/finally approach in your transaction processing code. But because they run so often I'd add the 'dirty flag' idea that somebody else mentioned too so that you don;t sabve if no changes have been made. A dirty flag is simply a global (or class) level variable (isDirty) that gets set by your code anytime you change the data. If a book changes its state it sets the flag to True. The save code then does something like with open(filename) as store if Book.isDirty: for book in Book.instances: book.save(store) That will ensure that any changes are saved but we don't waste time if no changes exist. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From michael at redhat.com Fri Feb 15 15:41:54 2013 From: michael at redhat.com (Michael J. McConachie) Date: Fri, 15 Feb 2013 09:41:54 -0500 Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <511D6001.1020804@gmail.com> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> <511D6001.1020804@gmail.com> Message-ID: <511E4932.6090102@redhat.com> @Bob @David -- I gave you all the other parts to give you a background, and context as it relates to my 'problem'. My apologies if it seems obfuscated. I took an hour to write that email, and revised it several times in an attempt to provide good information. Please disregard my OP. On 02/14/2013 05:06 PM, bob gailer wrote: > On 2/14/2013 3:55 PM, Michael McConachie wrote: > [snip] > > I agree with dave angel - the specification is far from clear. please > clarify. perhaps a simple example that goes from input to desired output. > From michael at redhat.com Fri Feb 15 15:45:05 2013 From: michael at redhat.com (Michael J. McConachie) Date: Fri, 15 Feb 2013 09:45:05 -0500 Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <511D69B2.9080802@pearwood.info> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> <511D69B2.9080802@pearwood.info> Message-ID: <511E49F1.8060901@redhat.com> @ Stephen, Thank you for the answers. I appreciate your understanding, and patience; I understand that it was confusing (unintentionally) and probably irritating to any of the seasoned tutor list members. Your examples helped greatly, and was the push I needed. Happy Friday, and thanks again, Mike On 02/14/2013 05:48 PM, Steven D'Aprano wrote: > On 15/02/13 07:55, Michael McConachie wrote: > >> Essentially: >> >> 1. I have a list of numbers that already exist in a file. I >> generate this file by parsing info from logs. >> 2. Each line contains an integer on it (corresponding to the number >> of milliseconds that it takes to complete a certain repeated task). >> 3. There are over a million entries in this file, one per line; at >> any given time it can be just a few thousand, or more than a million. >> >> Example: >> ------- >> 173 >> 1685 >> 1152 >> 253 >> 1623 > > > A million entries sounds like a lot to you or me, but to your > computer, it's not. When you start talking tens or hundreds of > millions, that's possibly a lot. > > Do you know how to read those numbers into a Python list? Here is the > "baby step" way to do so: > > > data = [] # Start with an empty list. > f = open("filename") # Obviously you have to use the actual file name. > for line in f: # Read the file one line at a time. > num = int(line) # Convert each line into an integer (whole number) > data.append(num) # and append it to the end of the list. > f.close() # Close the file when done. > > > Here's a more concise way to do it: > > with open("filename") as f: > data = [int(line) for line in f] > > > > Once you have that list of numbers, you can sum the whole lot: > > sum(data) > > > or just a range of the items: > > sum(data[:100]) # The first 100 items. > > sum(data[100:200]) # The second 100 items. > > sum(data[-50:]) # The last 50 items. > > sum(data[1000:]) # Item 1001 to the end. (See below.) > > sum(data[5:99:3]) # Every third item, starting at index 5 and ending > at index 98. > > > > This is called "slicing", and it is perhaps the most powerful and > useful technique that Python gives you for dealing with lists. The > rules though are not necessarily the most intuitive though. > > > A slice is either a pair of numbers separated with a colon, inside the > square brackets: > > data[start:end] > > or a triple: > > data[start:end:step] > > Any of these three numbers can be left out. The default values are: > > start=0 > end=length of the sequence being sliced > step=1 > > They can also be negative. If start or end are negative, they are > interpreted as "from the end" rather than "from the beginning". > > Item positions are counted from 0, which will be very familiar to C > programmers. The start index is included in the slice, the end > position is excluded. > > The model that you should think of is to imagine the sequence of items > labelled with their index, starting from zero, and with a vertical > line *between* each position. Here is a sequence of 26 items, showing > the index in the first line and the value in the second: > > > |0|1|2|3|4|5|6|7|8|9| ... |25| > |a|b|c|d|e|f|g|h|i|j| ... |z | > > When you take a slice, the items are always cut at the left. So, if > the above is called "letters", we have: > > letters[0:4] # returns "abcd" > > letters[2:8] # returns "cdefgh" > > letters[2:8:2] # returns "ceg" > > letters[-3:] # returns "xyz" > > > >> Eventually what I'll need to do is: >> >> 1. Index the file and/or count the lines, as to identify each line's >> positional relevance so that it can average any range of numbers that >> are sequential; one to one another. > > > No need. Python already does that, automatically, when you read the > data into a list. > > > >> 2. Calculate the difference between any given (x) range. In order >> to be able to ask the program to average every 5, 10, 100, 100, or >> 10,000 etc. --> until completion. This includes the need to dealing >> with stray remainders at the end of the file that aren't divisible by >> that initial requested range. > > I don't quite understand you here. First you say "difference", then > you say "average". Can you show a sample of data, say, 10 values, and > the sorts of typical calculations you want to perform, with the > answers you expect to get? > > > For example, here's 10 numbers: > > > 103, 104, 105, 109, 111, 112, 115, 120, 123, 128 > > > Here are the running averages of 3 values: > > (103+104+105)/3 > > (104+105+109)/3 > > (105+109+111)/3 > > (109+111+112)/3 > > (111+112+115)/3 > > (112+115+120)/3 > > (115+120+123)/3 > > (120+123+128)/3 > > > Is that what you mean? If so, then Python can deal with this > trivially, using slicing. With your data stored in list "data", as > above, I can say: > > > for i in range(0, len(data)-3): # Stop 3 from the end. > print sum(data[i:i+3]) > > > to print the running sums taking three items at a time. > > > > The rest of your post just confuses me. Until you explain exactly what > calculations you are trying to perform, I can't tell you how to > perform them :-) > > > > From fomcl at yahoo.com Fri Feb 15 22:03:00 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 15 Feb 2013 13:03:00 -0800 (PST) Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> Message-ID: <1360962180.92259.YahooMailNeo@web163803.mail.gq1.yahoo.com> > Eventually what I'll need to do is: > > 1.? Index the file and/or count the lines, as to identify each line's > positional relevance so that it can average any range of numbers that are > sequential; one to one another. In other words: you would like to down-sample your data? For example, reduce a sampling frequency from 1000 samples/second (1KHz) to 100, by averaging every ten sequential data points? > 2.? Calculate the difference between any given (x) range.? In order to be able > to ask the program to average every 5, 10, 100, 100, or 10,000 etc. --> until > completion.? This includes the need to dealing with stray remainders at the end > of the file that aren't divisible by that initial requested range. In other words: you would like to calculate a running/moving average, with window size as a parameter? From michael at redhat.com Fri Feb 15 23:00:55 2013 From: michael at redhat.com (Michael J. McConachie) Date: Fri, 15 Feb 2013 17:00:55 -0500 Subject: [Tutor] Newbie Here -- Averaging & Adding Madness Over a Given (x) Range?!?! In-Reply-To: <1360962180.92259.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <766423498.1712009.1360875323937.JavaMail.root@redhat.com> <1360962180.92259.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <511EB017.5020705@redhat.com> On 02/15/2013 04:03 PM, Albert-Jan Roskam wrote: > >> Eventually what I'll need to do is: >> 1. Index the file and/or count the lines, as to identify each line's >> positional relevance so that it can average any range of numbers that are >> sequential; one to one another. > In other words: you would like to down-sample your data? For example, reduce a sampling frequency from 1000 samples/second (1KHz) to 100, by averaging every ten sequential data points? I think so. When I said 'index' in my OP, I wasn't sure how to explain that each line would be used positionally to identify each group of (x) among themselves. (That's all I meant.) I am trying to identify gradient(s) in order to determine performance 'thresholds' if they exist. We are noting that as the number of tasks (already performed) increases, a noticeable decrease in the performance of a certain repeated task exists. I am trying to determine that point/elbow in the performance curve. I have been asked to identify, and plot the overall 'average performance' with varying levels of granularity. (Averaging 10, by 100, by 1000, etc.) The file I mentioned in my OP contains the measurement of time it takes to complete these repeated tasks. Each entry is on it's own line. The recorded data is in literal order of completion. I am averaging those (ms time entries) in sets of (x) to keep from having to compute the difference in time for each completed task individually. ie: Lines 1-10, (11-20, 21-30 --> to completion) are averaged and read into a list, or hash in order. or: Lines 1-100, (101-200, 201-300 --> to completion) are averaged and read into a list, or hash in order. or: Lines 1-1000, (1001-2000, 2001-3000 --> to completion) are averaged and read into a list, or hash in order. etc, etc. >> 2. Calculate the difference between any given (x) range. In order to be able >> to ask the program to average every 5, 10, 100, 100, or 10,000 etc. --> until >> completion. This includes the need to dealing with stray remainders at the end >> of the file that aren't divisible by that initial requested range. > In other words: you would like to calculate a running/moving average, with window size as a parameter? Yes. From joel.goldstick at gmail.com Fri Feb 15 23:05:51 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Feb 2013 17:05:51 -0500 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski wrote: > > > On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick wrote: > >> >> >> >> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >> spiceninja4u at gmail.com> wrote: >> >>> Hi, >>> >>> >>> I am very new to Python, I am using the e-book "Python Programming for >>> the Absolute Beginner" and am starting with a simple "Game Over" Program. >>> This is the code:which is extremely simple! >>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>> >> >> welcome Nicholas >> >> >> One important thing about python is indentation is important. You have >> presented your code in a way that can't be. Can you actually copy your >> program and paste it into an email message. Also, Windows, Linux, Mac? >> >> >> >>> That's it. It is supposed to bring up a window that says "Game Over" and >>> at the bottom say "Press enter Key to exit" and when you press the enter >>> key it is supposed to exit(big suprise). >>> But all it does is highlight "raw_input" and says "invalid syntax" Now, >>> if I just put "print "Game Over"" then it says Game Over UNDERNEATH the >>> code I just printed! >>> now I am following the book to the *pixel* and that is not what is >>> supposed to happen! >>> Please email me back as soon as you get this...(if you are not to busy). >>> >>> Thanks,Nicholas >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >>> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> > > > Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 > Here is the code in exact form > print "Game Over" > raw_input("\n\nPress Enter Key to Exit") > Thanks, > Nicholas You need to unindent the raw_input like so: print "Game Over" raw_input("\n\nPress Enter Key to Exit") In python you indent code blocks (like for loops, if statements, function blocks, etc.). You can't just indent from one line to the next in sequential code or you will be told its a syntax error -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Feb 15 23:12:58 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Feb 2013 17:12:58 -0500 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski wrote: > It Didn't work. First of all, reply to all. You are sending messages to me only, not to the group. Other's may be able to help you better than I can. Second. "It didn't work" is not a useful answer. So you have a file with two lines in it. The first has a print statement. The second has a raw_input statement. When you run it, what happens exactly? Do you get a traceback message telling you what the error is, and on what line? > > > On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick wrote: > >> >> >> >> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >> spiceninja4u at gmail.com> wrote: >> >>> >>> >>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>> joel.goldstick at gmail.com> wrote: >>> >>>> >>>> >>>> >>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>> spiceninja4u at gmail.com> wrote: >>>> >>>>> Hi, >>>>> >>>>> >>>>> I am very new to Python, I am using the e-book "Python Programming for >>>>> the Absolute Beginner" and am starting with a simple "Game Over" Program. >>>>> This is the code:which is extremely simple! >>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>> >>>> >>>> welcome Nicholas >>>> >>>> >>>> One important thing about python is indentation is important. You have >>>> presented your code in a way that can't be. Can you actually copy your >>>> program and paste it into an email message. Also, Windows, Linux, Mac? >>>> >>>> >>>> >>>>> That's it. It is supposed to bring up a window that says "Game Over" >>>>> and at the bottom say "Press enter Key to exit" and when you press the >>>>> enter key it is supposed to exit(big suprise). >>>>> But all it does is highlight "raw_input" and says "invalid syntax" >>>>> Now, if I just put "print "Game Over"" then it says Game Over UNDERNEATH >>>>> the code I just printed! >>>>> now I am following the book to the *pixel* and that is not what is >>>>> supposed to happen! >>>>> Please email me back as soon as you get this...(if you are not to >>>>> busy). >>>>> >>>>> Thanks,Nicholas >>>>> >>>>> -- >>>>> http://mail.python.org/mailman/listinfo/python-list >>>>> >>>>> >>>> >>>> >>>> -- >>>> Joel Goldstick >>>> http://joelgoldstick.com >>>> >>> >>> >>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>> Here is the code in exact form >>> print "Game Over" >>> raw_input("\n\nPress Enter Key to Exit") >>> Thanks, >>> Nicholas >> >> >> You need to unindent the raw_input like so: >> >> >> print "Game Over" >> raw_input("\n\nPress Enter Key to Exit") >> >> In python you indent code blocks (like for loops, if statements, function >> blocks, etc.). You can't just indent from one line to the next in >> sequential code or you will be told its a syntax error >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> > > > > -- > Nicholas J. Piotrowski -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Feb 15 23:29:53 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Feb 2013 17:29:53 -0500 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: Are you using python 2 or python 3? On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski wrote: > Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New Window" > and type in the code: > print "Game Over" > raw_input("\n\nPress Enter Key to exit") > and save the file on my desktop. > I double-click it and it opens a black window with gray text for a split > second and if you look quickly enough then you can see "Invalid Sytnax". > If I do the same code in the Interactive Window then it highlights > "raw_input" and says "Invalid Syntax" > > Are you using python 2 or python 3? > > On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick wrote: > >> >> >> >> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < >> spiceninja4u at gmail.com> wrote: >> >>> It Didn't work. >> >> >> First of all, reply to all. You are sending messages to me only, not to >> the group. Other's may be able to help you better than I can. >> >> Second. "It didn't work" is not a useful answer. >> >> So you have a file with two lines in it. The first has a print >> statement. The second has a raw_input statement. When you run it, what >> happens exactly? Do you get a traceback message telling you what the error >> is, and on what line? >> >> >> >>> >>> >>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < >>> joel.goldstick at gmail.com> wrote: >>> >>>> >>>> >>>> >>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >>>> spiceninja4u at gmail.com> wrote: >>>> >>>>> >>>>> >>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>>>> joel.goldstick at gmail.com> wrote: >>>>> >>>>>> >>>>>> >>>>>> >>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>>>> spiceninja4u at gmail.com> wrote: >>>>>> >>>>>>> Hi, >>>>>>> >>>>>>> >>>>>>> I am very new to Python, I am using the e-book "Python Programming >>>>>>> for the Absolute Beginner" and am starting with a simple "Game Over" >>>>>>> Program. This is the code:which is extremely simple! >>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>>>> >>>>>> >>>>>> welcome Nicholas >>>>>> >>>>>> >>>>>> One important thing about python is indentation is important. You >>>>>> have presented your code in a way that can't be. Can you actually copy >>>>>> your program and paste it into an email message. Also, Windows, Linux, Mac? >>>>>> >>>>>> >>>>>> >>>>>>> That's it. It is supposed to bring up a window that says "Game Over" >>>>>>> and at the bottom say "Press enter Key to exit" and when you press the >>>>>>> enter key it is supposed to exit(big suprise). >>>>>>> But all it does is highlight "raw_input" and says "invalid syntax" >>>>>>> Now, if I just put "print "Game Over"" then it says Game Over UNDERNEATH >>>>>>> the code I just printed! >>>>>>> now I am following the book to the *pixel* and that is not what is >>>>>>> supposed to happen! >>>>>>> Please email me back as soon as you get this...(if you are not to >>>>>>> busy). >>>>>>> >>>>>>> Thanks,Nicholas >>>>>>> >>>>>>> -- >>>>>>> http://mail.python.org/mailman/listinfo/python-list >>>>>>> >>>>>>> >>>>>> >>>>>> >>>>>> -- >>>>>> Joel Goldstick >>>>>> http://joelgoldstick.com >>>>>> >>>>> >>>>> >>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>>>> Here is the code in exact form >>>>> print "Game Over" >>>>> raw_input("\n\nPress Enter Key to Exit") >>>>> Thanks, >>>>> Nicholas >>>> >>>> >>>> You need to unindent the raw_input like so: >>>> >>>> >>>> print "Game Over" >>>> raw_input("\n\nPress Enter Key to Exit") >>>> >>>> In python you indent code blocks (like for loops, if statements, >>>> function blocks, etc.). You can't just indent from one line to the next in >>>> sequential code or you will be told its a syntax error >>>> >>>> >>>> >>>> -- >>>> Joel Goldstick >>>> http://joelgoldstick.com >>>> >>> >>> >>> >>> -- >>> Nicholas J. Piotrowski >> >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> > > > > -- > Nicholas J. Piotrowski > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Feb 15 23:31:54 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Feb 2013 17:31:54 -0500 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: On Fri, Feb 15, 2013 at 5:29 PM, Joel Goldstick wrote: > Are you using python 2 or python 3? > > > On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski < > spiceninja4u at gmail.com> wrote: > >> Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New >> Window" and type in the code: >> print "Game Over" >> raw_input("\n\nPress Enter Key to exit") >> and save the file on my desktop. >> I double-click it and it opens a black window with gray text for a split >> second and if you look quickly enough then you can see "Invalid Sytnax". >> If I do the same code in the Interactive Window then it highlights >> "raw_input" and says "Invalid Syntax" >> >> Are you using python 2 or python 3? > Sorry, you said above python 3. In python 3 raw_input was changed to input. so change that and it will work for you. There are some differences between 2 and 3 that you will need to look out for. Go to the python.org site to learn about them. Your book was written for python 2 it seems > >> On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick > > wrote: >> >>> >>> >>> >>> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < >>> spiceninja4u at gmail.com> wrote: >>> >>>> It Didn't work. >>> >>> >>> First of all, reply to all. You are sending messages to me only, not to >>> the group. Other's may be able to help you better than I can. >>> >>> Second. "It didn't work" is not a useful answer. >>> >>> So you have a file with two lines in it. The first has a print >>> statement. The second has a raw_input statement. When you run it, what >>> happens exactly? Do you get a traceback message telling you what the error >>> is, and on what line? >>> >>> >>> >>>> >>>> >>>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < >>>> joel.goldstick at gmail.com> wrote: >>>> >>>>> >>>>> >>>>> >>>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >>>>> spiceninja4u at gmail.com> wrote: >>>>> >>>>>> >>>>>> >>>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>>>>> joel.goldstick at gmail.com> wrote: >>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>> >>>>>>>> Hi, >>>>>>>> >>>>>>>> >>>>>>>> I am very new to Python, I am using the e-book "Python Programming >>>>>>>> for the Absolute Beginner" and am starting with a simple "Game Over" >>>>>>>> Program. This is the code:which is extremely simple! >>>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>>>>> >>>>>>> >>>>>>> welcome Nicholas >>>>>>> >>>>>>> >>>>>>> One important thing about python is indentation is important. You >>>>>>> have presented your code in a way that can't be. Can you actually copy >>>>>>> your program and paste it into an email message. Also, Windows, Linux, Mac? >>>>>>> >>>>>>> >>>>>>> >>>>>>>> That's it. It is supposed to bring up a window that says "Game >>>>>>>> Over" and at the bottom say "Press enter Key to exit" and when you press >>>>>>>> the enter key it is supposed to exit(big suprise). >>>>>>>> But all it does is highlight "raw_input" and says "invalid syntax" >>>>>>>> Now, if I just put "print "Game Over"" then it says Game Over UNDERNEATH >>>>>>>> the code I just printed! >>>>>>>> now I am following the book to the *pixel* and that is not what is >>>>>>>> supposed to happen! >>>>>>>> Please email me back as soon as you get this...(if you are not to >>>>>>>> busy). >>>>>>>> >>>>>>>> Thanks,Nicholas >>>>>>>> >>>>>>>> -- >>>>>>>> http://mail.python.org/mailman/listinfo/python-list >>>>>>>> >>>>>>>> >>>>>>> >>>>>>> >>>>>>> -- >>>>>>> Joel Goldstick >>>>>>> http://joelgoldstick.com >>>>>>> >>>>>> >>>>>> >>>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>>>>> Here is the code in exact form >>>>>> print "Game Over" >>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>> Thanks, >>>>>> Nicholas >>>>> >>>>> >>>>> You need to unindent the raw_input like so: >>>>> >>>>> >>>>> print "Game Over" >>>>> raw_input("\n\nPress Enter Key to Exit") >>>>> >>>>> In python you indent code blocks (like for loops, if statements, >>>>> function blocks, etc.). You can't just indent from one line to the next in >>>>> sequential code or you will be told its a syntax error >>>>> >>>>> >>>>> >>>>> -- >>>>> Joel Goldstick >>>>> http://joelgoldstick.com >>>>> >>>> >>>> >>>> >>>> -- >>>> Nicholas J. Piotrowski >>> >>> >>> >>> >>> -- >>> Joel Goldstick >>> http://joelgoldstick.com >>> >> >> >> >> -- >> Nicholas J. Piotrowski >> > > > > -- > Joel Goldstick > http://joelgoldstick.com > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Feb 15 23:44:11 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 15 Feb 2013 17:44:11 -0500 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: so copy the code and the error message here On Fri, Feb 15, 2013 at 5:42 PM, Deborah Piotrowski wrote: > I did what you said, nothing changed. > same errors, same syntax message. > I suggest you run it on your IDLE to see if it works. > > > On Fri, Feb 15, 2013 at 3:31 PM, Joel Goldstick wrote: > >> >> >> >> On Fri, Feb 15, 2013 at 5:29 PM, Joel Goldstick > > wrote: >> >>> Are you using python 2 or python 3? >>> >>> >>> On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski < >>> spiceninja4u at gmail.com> wrote: >>> >>>> Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New >>>> Window" and type in the code: >>>> print "Game Over" >>>> raw_input("\n\nPress Enter Key to exit") >>>> and save the file on my desktop. >>>> I double-click it and it opens a black window with gray text for a >>>> split second and if you look quickly enough then you can see "Invalid >>>> Sytnax". >>>> If I do the same code in the Interactive Window then it highlights >>>> "raw_input" and says "Invalid Syntax" >>>> >>>> Are you using python 2 or python 3? >>> >> >> Sorry, you said above python 3. In python 3 raw_input was changed to >> input. so change that and it will work for you. >> There are some differences between 2 and 3 that you will need to look out >> for. Go to the python.org site to learn about them. Your book was >> written for python 2 it seems >> >> >>> >>>> On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick < >>>> joel.goldstick at gmail.com> wrote: >>>> >>>>> >>>>> >>>>> >>>>> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < >>>>> spiceninja4u at gmail.com> wrote: >>>>> >>>>>> It Didn't work. >>>>> >>>>> >>>>> First of all, reply to all. You are sending messages to me only, not >>>>> to the group. Other's may be able to help you better than I can. >>>>> >>>>> Second. "It didn't work" is not a useful answer. >>>>> >>>>> So you have a file with two lines in it. The first has a print >>>>> statement. The second has a raw_input statement. When you run it, what >>>>> happens exactly? Do you get a traceback message telling you what the error >>>>> is, and on what line? >>>>> >>>>> >>>>> >>>>>> >>>>>> >>>>>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < >>>>>> joel.goldstick at gmail.com> wrote: >>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>> >>>>>>>>>> Hi, >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> I am very new to Python, I am using the e-book "Python >>>>>>>>>> Programming for the Absolute Beginner" and am starting with a simple "Game >>>>>>>>>> Over" Program. This is the code:which is extremely simple! >>>>>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>>>>>>> >>>>>>>>> >>>>>>>>> welcome Nicholas >>>>>>>>> >>>>>>>>> >>>>>>>>> One important thing about python is indentation is important. You >>>>>>>>> have presented your code in a way that can't be. Can you actually copy >>>>>>>>> your program and paste it into an email message. Also, Windows, Linux, Mac? >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>>> That's it. It is supposed to bring up a window that says "Game >>>>>>>>>> Over" and at the bottom say "Press enter Key to exit" and when you press >>>>>>>>>> the enter key it is supposed to exit(big suprise). >>>>>>>>>> But all it does is highlight "raw_input" and says "invalid >>>>>>>>>> syntax" Now, if I just put "print "Game Over"" then it says Game Over >>>>>>>>>> UNDERNEATH the code I just printed! >>>>>>>>>> now I am following the book to the *pixel* and that is not what >>>>>>>>>> is supposed to happen! >>>>>>>>>> Please email me back as soon as you get this...(if you are not to >>>>>>>>>> busy). >>>>>>>>>> >>>>>>>>>> Thanks,Nicholas >>>>>>>>>> >>>>>>>>>> -- >>>>>>>>>> http://mail.python.org/mailman/listinfo/python-list >>>>>>>>>> >>>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> -- >>>>>>>>> Joel Goldstick >>>>>>>>> http://joelgoldstick.com >>>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>>>>>>> Here is the code in exact form >>>>>>>> print "Game Over" >>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>> Thanks, >>>>>>>> Nicholas >>>>>>> >>>>>>> >>>>>>> You need to unindent the raw_input like so: >>>>>>> >>>>>>> >>>>>>> print "Game Over" >>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>> >>>>>>> In python you indent code blocks (like for loops, if statements, >>>>>>> function blocks, etc.). You can't just indent from one line to the next in >>>>>>> sequential code or you will be told its a syntax error >>>>>>> >>>>>>> >>>>>>> >>>>>>> -- >>>>>>> Joel Goldstick >>>>>>> http://joelgoldstick.com >>>>>>> >>>>>> >>>>>> >>>>>> >>>>>> -- >>>>>> Nicholas J. Piotrowski >>>>> >>>>> >>>>> >>>>> >>>>> -- >>>>> Joel Goldstick >>>>> http://joelgoldstick.com >>>>> >>>> >>>> >>>> >>>> -- >>>> Nicholas J. Piotrowski >>>> >>> >>> >>> >>> -- >>> Joel Goldstick >>> http://joelgoldstick.com >>> >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> > > > > -- > Nicholas J. Piotrowski > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From joskerc at gmail.com Sat Feb 16 00:10:21 2013 From: joskerc at gmail.com (Jos Kerc) Date: Sat, 16 Feb 2013 00:10:21 +0100 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: No, not same. At lea On Fri, Feb 15, 2013 at 11:44 PM, Joel Goldstick wrote: > so copy the code and the error message here > > > On Fri, Feb 15, 2013 at 5:42 PM, Deborah Piotrowski < > spiceninja4u at gmail.com> wrote: > >> I did what you said, nothing changed. >> same errors, same syntax message. >> I suggest you run it on your IDLE to see if it works. >> >> >> On Fri, Feb 15, 2013 at 3:31 PM, Joel Goldstick > > wrote: >> >>> >>> >>> >>> On Fri, Feb 15, 2013 at 5:29 PM, Joel Goldstick < >>> joel.goldstick at gmail.com> wrote: >>> >>>> Are you using python 2 or python 3? >>>> >>>> >>>> On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski < >>>> spiceninja4u at gmail.com> wrote: >>>> >>>>> Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New >>>>> Window" and type in the code: >>>>> print "Game Over" >>>>> raw_input("\n\nPress Enter Key to exit") >>>>> and save the file on my desktop. >>>>> I double-click it and it opens a black window with gray text for a >>>>> split second and if you look quickly enough then you can see "Invalid >>>>> Sytnax". >>>>> If I do the same code in the Interactive Window then it highlights >>>>> "raw_input" and says "Invalid Syntax" >>>>> >>>>> Are you using python 2 or python 3? >>>> >>> >>> Sorry, you said above python 3. In python 3 raw_input was changed to >>> input. so change that and it will work for you. >>> There are some differences between 2 and 3 that you will need to look >>> out for. Go to the python.org site to learn about them. Your book was >>> written for python 2 it seems >>> >>> >>>> >>>>> On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick < >>>>> joel.goldstick at gmail.com> wrote: >>>>> >>>>>> >>>>>> >>>>>> >>>>>> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < >>>>>> spiceninja4u at gmail.com> wrote: >>>>>> >>>>>>> It Didn't work. >>>>>> >>>>>> >>>>>> First of all, reply to all. You are sending messages to me only, not >>>>>> to the group. Other's may be able to help you better than I can. >>>>>> >>>>>> Second. "It didn't work" is not a useful answer. >>>>>> >>>>>> So you have a file with two lines in it. The first has a print >>>>>> statement. The second has a raw_input statement. When you run it, what >>>>>> happens exactly? Do you get a traceback message telling you what the error >>>>>> is, and on what line? >>>>>> >>>>>> >>>>>> >>>>>>> >>>>>>> >>>>>>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < >>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>>> >>>>>>>>>>> Hi, >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> I am very new to Python, I am using the e-book "Python >>>>>>>>>>> Programming for the Absolute Beginner" and am starting with a simple "Game >>>>>>>>>>> Over" Program. This is the code:which is extremely simple! >>>>>>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>>>>>>>> >>>>>>>>>> >>>>>>>>>> welcome Nicholas >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> One important thing about python is indentation is important. >>>>>>>>>> You have presented your code in a way that can't be. Can you actually copy >>>>>>>>>> your program and paste it into an email message. Also, Windows, Linux, Mac? >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>>> That's it. It is supposed to bring up a window that says "Game >>>>>>>>>>> Over" and at the bottom say "Press enter Key to exit" and when you press >>>>>>>>>>> the enter key it is supposed to exit(big suprise). >>>>>>>>>>> But all it does is highlight "raw_input" and says "invalid >>>>>>>>>>> syntax" Now, if I just put "print "Game Over"" then it says Game Over >>>>>>>>>>> UNDERNEATH the code I just printed! >>>>>>>>>>> now I am following the book to the *pixel* and that is not what >>>>>>>>>>> is supposed to happen! >>>>>>>>>>> Please email me back as soon as you get this...(if you are not >>>>>>>>>>> to busy). >>>>>>>>>>> >>>>>>>>>>> Thanks,Nicholas >>>>>>>>>>> >>>>>>>>>>> -- >>>>>>>>>>> http://mail.python.org/mailman/listinfo/python-list >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> -- >>>>>>>>>> Joel Goldstick >>>>>>>>>> http://joelgoldstick.com >>>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>>>>>>>> Here is the code in exact form >>>>>>>>> print "Game Over" >>>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>>> Thanks, >>>>>>>>> Nicholas >>>>>>>> >>>>>>>> >>>>>>>> You need to unindent the raw_input like so: >>>>>>>> >>>>>>>> >>>>>>>> print "Game Over" >>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>> >>>>>>>> In python you indent code blocks (like for loops, if statements, >>>>>>>> function blocks, etc.). You can't just indent from one line to the next in >>>>>>>> sequential code or you will be told its a syntax error >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> -- >>>>>>>> Joel Goldstick >>>>>>>> http://joelgoldstick.com >>>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>> -- >>>>>>> Nicholas J. Piotrowski >>>>>> >>>>>> >>>>>> >>>>>> >>>>>> -- >>>>>> Joel Goldstick >>>>>> http://joelgoldstick.com >>>>>> >>>>> >>>>> >>>>> >>>>> -- >>>>> Nicholas J. Piotrowski >>>>> >>>> >>>> >>>> >>>> -- >>>> Joel Goldstick >>>> http://joelgoldstick.com >>>> >>> >>> >>> >>> -- >>> Joel Goldstick >>> http://joelgoldstick.com >>> >> >> >> >> -- >> Nicholas J. Piotrowski >> > > > > -- > Joel Goldstick > http://joelgoldstick.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joskerc at gmail.com Sat Feb 16 00:14:15 2013 From: joskerc at gmail.com (Jos Kerc) Date: Sat, 16 Feb 2013 00:14:15 +0100 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: Sorry, sent before finishing... If you changed raw_input, as asked. Now, it complains about print 'Game Over' Should become print('Game Over') On Sat, Feb 16, 2013 at 12:10 AM, Jos Kerc wrote: > No, not same. At lea > > > On Fri, Feb 15, 2013 at 11:44 PM, Joel Goldstick > wrote: > >> so copy the code and the error message here >> >> >> On Fri, Feb 15, 2013 at 5:42 PM, Deborah Piotrowski < >> spiceninja4u at gmail.com> wrote: >> >>> I did what you said, nothing changed. >>> same errors, same syntax message. >>> I suggest you run it on your IDLE to see if it works. >>> >>> >>> On Fri, Feb 15, 2013 at 3:31 PM, Joel Goldstick < >>> joel.goldstick at gmail.com> wrote: >>> >>>> >>>> >>>> >>>> On Fri, Feb 15, 2013 at 5:29 PM, Joel Goldstick < >>>> joel.goldstick at gmail.com> wrote: >>>> >>>>> Are you using python 2 or python 3? >>>>> >>>>> >>>>> On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski < >>>>> spiceninja4u at gmail.com> wrote: >>>>> >>>>>> Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New >>>>>> Window" and type in the code: >>>>>> print "Game Over" >>>>>> raw_input("\n\nPress Enter Key to exit") >>>>>> and save the file on my desktop. >>>>>> I double-click it and it opens a black window with gray text for a >>>>>> split second and if you look quickly enough then you can see "Invalid >>>>>> Sytnax". >>>>>> If I do the same code in the Interactive Window then it highlights >>>>>> "raw_input" and says "Invalid Syntax" >>>>>> >>>>>> Are you using python 2 or python 3? >>>>> >>>> >>>> Sorry, you said above python 3. In python 3 raw_input was changed to >>>> input. so change that and it will work for you. >>>> There are some differences between 2 and 3 that you will need to look >>>> out for. Go to the python.org site to learn about them. Your book >>>> was written for python 2 it seems >>>> >>>> >>>>> >>>>>> On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick < >>>>>> joel.goldstick at gmail.com> wrote: >>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < >>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>> >>>>>>>> It Didn't work. >>>>>>> >>>>>>> >>>>>>> First of all, reply to all. You are sending messages to me only, >>>>>>> not to the group. Other's may be able to help you better than I can. >>>>>>> >>>>>>> Second. "It didn't work" is not a useful answer. >>>>>>> >>>>>>> So you have a file with two lines in it. The first has a print >>>>>>> statement. The second has a raw_input statement. When you run it, what >>>>>>> happens exactly? Do you get a traceback message telling you what the error >>>>>>> is, and on what line? >>>>>>> >>>>>>> >>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < >>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>>>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>>>> >>>>>>>>>>>> Hi, >>>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>>> I am very new to Python, I am using the e-book "Python >>>>>>>>>>>> Programming for the Absolute Beginner" and am starting with a simple "Game >>>>>>>>>>>> Over" Program. This is the code:which is extremely simple! >>>>>>>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> welcome Nicholas >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> One important thing about python is indentation is important. >>>>>>>>>>> You have presented your code in a way that can't be. Can you actually copy >>>>>>>>>>> your program and paste it into an email message. Also, Windows, Linux, Mac? >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>>> That's it. It is supposed to bring up a window that says "Game >>>>>>>>>>>> Over" and at the bottom say "Press enter Key to exit" and when you press >>>>>>>>>>>> the enter key it is supposed to exit(big suprise). >>>>>>>>>>>> But all it does is highlight "raw_input" and says "invalid >>>>>>>>>>>> syntax" Now, if I just put "print "Game Over"" then it says Game Over >>>>>>>>>>>> UNDERNEATH the code I just printed! >>>>>>>>>>>> now I am following the book to the *pixel* and that is not >>>>>>>>>>>> what is supposed to happen! >>>>>>>>>>>> Please email me back as soon as you get this...(if you are not >>>>>>>>>>>> to busy). >>>>>>>>>>>> >>>>>>>>>>>> Thanks,Nicholas >>>>>>>>>>>> >>>>>>>>>>>> -- >>>>>>>>>>>> http://mail.python.org/mailman/listinfo/python-list >>>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> -- >>>>>>>>>>> Joel Goldstick >>>>>>>>>>> http://joelgoldstick.com >>>>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>>>>>>>>> Here is the code in exact form >>>>>>>>>> print "Game Over" >>>>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>>>> Thanks, >>>>>>>>>> Nicholas >>>>>>>>> >>>>>>>>> >>>>>>>>> You need to unindent the raw_input like so: >>>>>>>>> >>>>>>>>> >>>>>>>>> print "Game Over" >>>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>>> >>>>>>>>> In python you indent code blocks (like for loops, if statements, >>>>>>>>> function blocks, etc.). You can't just indent from one line to the next in >>>>>>>>> sequential code or you will be told its a syntax error >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> -- >>>>>>>>> Joel Goldstick >>>>>>>>> http://joelgoldstick.com >>>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> -- >>>>>>>> Nicholas J. Piotrowski >>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>> -- >>>>>>> Joel Goldstick >>>>>>> http://joelgoldstick.com >>>>>>> >>>>>> >>>>>> >>>>>> >>>>>> -- >>>>>> Nicholas J. Piotrowski >>>>>> >>>>> >>>>> >>>>> >>>>> -- >>>>> Joel Goldstick >>>>> http://joelgoldstick.com >>>>> >>>> >>>> >>>> >>>> -- >>>> Joel Goldstick >>>> http://joelgoldstick.com >>>> >>> >>> >>> >>> -- >>> Nicholas J. Piotrowski >>> >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Feb 16 00:28:23 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 15 Feb 2013 23:28:23 +0000 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: On 15/02/2013 22:31, Joel Goldstick wrote: > > Sorry, you said above python 3. In python 3 raw_input was changed to > input. so change that and it will work for you. > There are some differences between 2 and 3 that you will need to look > out for. Go to the python.org site to learn about > them. Your book was written for python 2 it seems > In Python 3 the syntax error is caused by print not having brackets, not the as it happens the incorrect call to raw_input. -- Cheers. Mark Lawrence From joskerc at gmail.com Sat Feb 16 02:03:22 2013 From: joskerc at gmail.com (Jos Kerc) Date: Sat, 16 Feb 2013 02:03:22 +0100 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: On Sat, Feb 16, 2013 at 12:20 AM, Deborah Piotrowski wrote: > It works, but it doesn't open a window. It just says that stuff under the > code. How do you open a window? Depends... How do you run the script? From Idle, command prompt? > > > On Fri, Feb 15, 2013 at 4:14 PM, Jos Kerc wrote: > >> Sorry, sent before finishing... >> >> If you changed raw_input, as asked. >> Now, it complains about print 'Game Over' >> Should become print('Game Over') >> >> >> On Sat, Feb 16, 2013 at 12:10 AM, Jos Kerc wrote: >> >>> No, not same. At lea >>> >>> >>> On Fri, Feb 15, 2013 at 11:44 PM, Joel Goldstick < >>> joel.goldstick at gmail.com> wrote: >>> >>>> so copy the code and the error message here >>>> >>>> >>>> On Fri, Feb 15, 2013 at 5:42 PM, Deborah Piotrowski < >>>> spiceninja4u at gmail.com> wrote: >>>> >>>>> I did what you said, nothing changed. >>>>> same errors, same syntax message. >>>>> I suggest you run it on your IDLE to see if it works. >>>>> >>>>> >>>>> On Fri, Feb 15, 2013 at 3:31 PM, Joel Goldstick < >>>>> joel.goldstick at gmail.com> wrote: >>>>> >>>>>> >>>>>> >>>>>> >>>>>> On Fri, Feb 15, 2013 at 5:29 PM, Joel Goldstick < >>>>>> joel.goldstick at gmail.com> wrote: >>>>>> >>>>>>> Are you using python 2 or python 3? >>>>>>> >>>>>>> >>>>>>> On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski < >>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>> >>>>>>>> Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New >>>>>>>> Window" and type in the code: >>>>>>>> print "Game Over" >>>>>>>> raw_input("\n\nPress Enter Key to exit") >>>>>>>> and save the file on my desktop. >>>>>>>> I double-click it and it opens a black window with gray text for a >>>>>>>> split second and if you look quickly enough then you can see "Invalid >>>>>>>> Sytnax". >>>>>>>> If I do the same code in the Interactive Window then it highlights >>>>>>>> "raw_input" and says "Invalid Syntax" >>>>>>>> >>>>>>>> Are you using python 2 or python 3? >>>>>>> >>>>>> >>>>>> Sorry, you said above python 3. In python 3 raw_input was changed to >>>>>> input. so change that and it will work for you. >>>>>> There are some differences between 2 and 3 that you will need to look >>>>>> out for. Go to the python.org site to learn about them. Your book >>>>>> was written for python 2 it seems >>>>>> >>>>>> >>>>>>> >>>>>>>> On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick < >>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < >>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>> >>>>>>>>>> It Didn't work. >>>>>>>>> >>>>>>>>> >>>>>>>>> First of all, reply to all. You are sending messages to me only, >>>>>>>>> not to the group. Other's may be able to help you better than I can. >>>>>>>>> >>>>>>>>> Second. "It didn't work" is not a useful answer. >>>>>>>>> >>>>>>>>> So you have a file with two lines in it. The first has a print >>>>>>>>> statement. The second has a raw_input statement. When you run it, what >>>>>>>>> happens exactly? Do you get a traceback message telling you what the error >>>>>>>>> is, and on what line? >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < >>>>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < >>>>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < >>>>>>>>>>>> joel.goldstick at gmail.com> wrote: >>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < >>>>>>>>>>>>> spiceninja4u at gmail.com> wrote: >>>>>>>>>>>>> >>>>>>>>>>>>>> Hi, >>>>>>>>>>>>>> >>>>>>>>>>>>>> >>>>>>>>>>>>>> I am very new to Python, I am using the e-book "Python >>>>>>>>>>>>>> Programming for the Absolute Beginner" and am starting with a simple "Game >>>>>>>>>>>>>> Over" Program. This is the code:which is extremely simple! >>>>>>>>>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") >>>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> welcome Nicholas >>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> One important thing about python is indentation is important. >>>>>>>>>>>>> You have presented your code in a way that can't be. Can you actually copy >>>>>>>>>>>>> your program and paste it into an email message. Also, Windows, Linux, Mac? >>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>>> That's it. It is supposed to bring up a window that says >>>>>>>>>>>>>> "Game Over" and at the bottom say "Press enter Key to exit" and when you >>>>>>>>>>>>>> press the enter key it is supposed to exit(big suprise). >>>>>>>>>>>>>> But all it does is highlight "raw_input" and says "invalid >>>>>>>>>>>>>> syntax" Now, if I just put "print "Game Over"" then it says Game Over >>>>>>>>>>>>>> UNDERNEATH the code I just printed! >>>>>>>>>>>>>> now I am following the book to the *pixel* and that is not >>>>>>>>>>>>>> what is supposed to happen! >>>>>>>>>>>>>> Please email me back as soon as you get this...(if you are >>>>>>>>>>>>>> not to busy). >>>>>>>>>>>>>> >>>>>>>>>>>>>> Thanks,Nicholas >>>>>>>>>>>>>> >>>>>>>>>>>>>> -- >>>>>>>>>>>>>> http://mail.python.org/mailman/listinfo/python-list >>>>>>>>>>>>>> >>>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> >>>>>>>>>>>>> -- >>>>>>>>>>>>> Joel Goldstick >>>>>>>>>>>>> http://joelgoldstick.com >>>>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>>> >>>>>>>>>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 >>>>>>>>>>>> Here is the code in exact form >>>>>>>>>>>> print "Game Over" >>>>>>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>>>>>> Thanks, >>>>>>>>>>>> Nicholas >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> You need to unindent the raw_input like so: >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> print "Game Over" >>>>>>>>>>> raw_input("\n\nPress Enter Key to Exit") >>>>>>>>>>> >>>>>>>>>>> In python you indent code blocks (like for loops, if statements, >>>>>>>>>>> function blocks, etc.). You can't just indent from one line to the next in >>>>>>>>>>> sequential code or you will be told its a syntax error >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> >>>>>>>>>>> -- >>>>>>>>>>> Joel Goldstick >>>>>>>>>>> http://joelgoldstick.com >>>>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> >>>>>>>>>> -- >>>>>>>>>> Nicholas J. Piotrowski >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> >>>>>>>>> -- >>>>>>>>> Joel Goldstick >>>>>>>>> http://joelgoldstick.com >>>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> >>>>>>>> -- >>>>>>>> Nicholas J. Piotrowski >>>>>>>> >>>>>>> >>>>>>> >>>>>>> >>>>>>> -- >>>>>>> Joel Goldstick >>>>>>> http://joelgoldstick.com >>>>>>> >>>>>> >>>>>> >>>>>> >>>>>> -- >>>>>> Joel Goldstick >>>>>> http://joelgoldstick.com >>>>>> >>>>> >>>>> >>>>> >>>>> -- >>>>> Nicholas J. Piotrowski >>>>> >>>> >>>> >>>> >>>> -- >>>> Joel Goldstick >>>> http://joelgoldstick.com >>>> >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>> >> > > > -- > Nicholas J. Piotrowski -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sat Feb 16 03:29:34 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Feb 2013 21:29:34 -0500 Subject: [Tutor] New User-Need-Help In-Reply-To: References: Message-ID: <511EEF0E.60203@davea.name> On 02/15/2013 06:28 PM, Mark Lawrence wrote: > On 15/02/2013 22:31, Joel Goldstick wrote: >> >> Sorry, you said above python 3. In python 3 raw_input was changed to >> input. so change that and it will work for you. >> There are some differences between 2 and 3 that you will need to look >> out for. Go to the python.org site to learn about >> them. Your book was written for python 2 it seems >> > > In Python 3 the syntax error is caused by print not having brackets, not > the as it happens the incorrect call to raw_input. > Can we please kill this thread? Somehow it got transported from python-list to tutor, but all the OP posts are on python-list. That combined with top-posting and the OP using a different name in their signature than in the email address makes the whole thing very confusing. Besides, three hours ago, the OP (Nicholas/Deborah) posted a "Solved" message: > WAIT!! It works now, I just needed to save it in script. > Thank you guys so much!! > My best regards, Nicholas -- DaveA From waveclaira at gmail.com Sat Feb 16 04:09:44 2013 From: waveclaira at gmail.com (Claira) Date: Fri, 15 Feb 2013 21:09:44 -0600 Subject: [Tutor] Tutor Digest, Vol 108, Issue 58 In-Reply-To: References: Message-ID: Hi, I signed up a while ago, but I didn't really understand anything. I have a basic question that maybe someone can help with. I'll like to integrate yelp data -- http://www.programmableweb.com/api/yelp -- onto google maps -- http://www.programmableweb.com/api/google-maps -- like how http://www.trulia.com/real_estate/New_York-New_York has it under "Amenities". But I want it on maps.google.com because I have no idea how to put the map on a separate webpage. I'll like to know if I need python for this :) On Fri, Feb 15, 2013 at 7:03 PM, 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: New User-Need-Help (Mark Lawrence) > 2. Re: New User-Need-Help (Jos Kerc) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 15 Feb 2013 23:28:23 +0000 > From: Mark Lawrence > To: tutor at python.org > Subject: Re: [Tutor] New User-Need-Help > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 15/02/2013 22:31, Joel Goldstick wrote: > > > > Sorry, you said above python 3. In python 3 raw_input was changed to > > input. so change that and it will work for you. > > There are some differences between 2 and 3 that you will need to look > > out for. Go to the python.org site to learn about > > them. Your book was written for python 2 it seems > > > > In Python 3 the syntax error is caused by print not having brackets, not > the as it happens the incorrect call to raw_input. > > -- > Cheers. > > Mark Lawrence > > > > ------------------------------ > > Message: 2 > Date: Sat, 16 Feb 2013 02:03:22 +0100 > From: Jos Kerc > To: Deborah Piotrowski > Cc: "tutor at python.org" > Subject: Re: [Tutor] New User-Need-Help > Message-ID: > D-PnXu0xOMtXQ2yx7g at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Sat, Feb 16, 2013 at 12:20 AM, Deborah Piotrowski < > spiceninja4u at gmail.com > > wrote: > > > It works, but it doesn't open a window. It just says that stuff under the > > code. How do you open a window? > > > > > > Depends... > How do you run the script? From Idle, command prompt? > > > > > > > On Fri, Feb 15, 2013 at 4:14 PM, Jos Kerc wrote: > > > >> Sorry, sent before finishing... > >> > >> If you changed raw_input, as asked. > >> Now, it complains about print 'Game Over' > >> Should become print('Game Over') > >> > >> > >> On Sat, Feb 16, 2013 at 12:10 AM, Jos Kerc wrote: > >> > >>> No, not same. At lea > >>> > >>> > >>> On Fri, Feb 15, 2013 at 11:44 PM, Joel Goldstick < > >>> joel.goldstick at gmail.com> wrote: > >>> > >>>> so copy the code and the error message here > >>>> > >>>> > >>>> On Fri, Feb 15, 2013 at 5:42 PM, Deborah Piotrowski < > >>>> spiceninja4u at gmail.com> wrote: > >>>> > >>>>> I did what you said, nothing changed. > >>>>> same errors, same syntax message. > >>>>> I suggest you run it on your IDLE to see if it works. > >>>>> > >>>>> > >>>>> On Fri, Feb 15, 2013 at 3:31 PM, Joel Goldstick < > >>>>> joel.goldstick at gmail.com> wrote: > >>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> On Fri, Feb 15, 2013 at 5:29 PM, Joel Goldstick < > >>>>>> joel.goldstick at gmail.com> wrote: > >>>>>> > >>>>>>> Are you using python 2 or python 3? > >>>>>>> > >>>>>>> > >>>>>>> On Fri, Feb 15, 2013 at 5:28 PM, Deborah Piotrowski < > >>>>>>> spiceninja4u at gmail.com> wrote: > >>>>>>> > >>>>>>>> Ok, so I made a shortcut to IDLE(GUI) and I open it up. click "New > >>>>>>>> Window" and type in the code: > >>>>>>>> print "Game Over" > >>>>>>>> raw_input("\n\nPress Enter Key to exit") > >>>>>>>> and save the file on my desktop. > >>>>>>>> I double-click it and it opens a black window with gray text for a > >>>>>>>> split second and if you look quickly enough then you can see > "Invalid > >>>>>>>> Sytnax". > >>>>>>>> If I do the same code in the Interactive Window then it highlights > >>>>>>>> "raw_input" and says "Invalid Syntax" > >>>>>>>> > >>>>>>>> Are you using python 2 or python 3? > >>>>>>> > >>>>>> > >>>>>> Sorry, you said above python 3. In python 3 raw_input was changed > to > >>>>>> input. so change that and it will work for you. > >>>>>> There are some differences between 2 and 3 that you will need to > look > >>>>>> out for. Go to the python.org site to learn about them. Your book > >>>>>> was written for python 2 it seems > >>>>>> > >>>>>> > >>>>>>> > >>>>>>>> On Fri, Feb 15, 2013 at 3:12 PM, Joel Goldstick < > >>>>>>>> joel.goldstick at gmail.com> wrote: > >>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> On Fri, Feb 15, 2013 at 5:09 PM, Deborah Piotrowski < > >>>>>>>>> spiceninja4u at gmail.com> wrote: > >>>>>>>>> > >>>>>>>>>> It Didn't work. > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> First of all, reply to all. You are sending messages to me only, > >>>>>>>>> not to the group. Other's may be able to help you better than I > can. > >>>>>>>>> > >>>>>>>>> Second. "It didn't work" is not a useful answer. > >>>>>>>>> > >>>>>>>>> So you have a file with two lines in it. The first has a print > >>>>>>>>> statement. The second has a raw_input statement. When you run > it, what > >>>>>>>>> happens exactly? Do you get a traceback message telling you what > the error > >>>>>>>>> is, and on what line? > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> On Fri, Feb 15, 2013 at 3:05 PM, Joel Goldstick < > >>>>>>>>>> joel.goldstick at gmail.com> wrote: > >>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> On Fri, Feb 15, 2013 at 5:03 PM, Deborah Piotrowski < > >>>>>>>>>>> spiceninja4u at gmail.com> wrote: > >>>>>>>>>>> > >>>>>>>>>>>> > >>>>>>>>>>>> > >>>>>>>>>>>> On Fri, Feb 15, 2013 at 2:58 PM, Joel Goldstick < > >>>>>>>>>>>> joel.goldstick at gmail.com> wrote: > >>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> On Fri, Feb 15, 2013 at 4:45 PM, Deborah Piotrowski < > >>>>>>>>>>>>> spiceninja4u at gmail.com> wrote: > >>>>>>>>>>>>> > >>>>>>>>>>>>>> Hi, > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> I am very new to Python, I am using the e-book "Python > >>>>>>>>>>>>>> Programming for the Absolute Beginner" and am starting with > a simple "Game > >>>>>>>>>>>>>> Over" Program. This is the code:which is extremely simple! > >>>>>>>>>>>>>> print"Game Over" raw_input("\n\nPress Enter Key to exit") > >>>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> welcome Nicholas > >>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> One important thing about python is indentation is important. > >>>>>>>>>>>>> You have presented your code in a way that can't be. Can > you actually copy > >>>>>>>>>>>>> your program and paste it into an email message. Also, > Windows, Linux, Mac? > >>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>>> That's it. It is supposed to bring up a window that says > >>>>>>>>>>>>>> "Game Over" and at the bottom say "Press enter Key to exit" > and when you > >>>>>>>>>>>>>> press the enter key it is supposed to exit(big suprise). > >>>>>>>>>>>>>> But all it does is highlight "raw_input" and says "invalid > >>>>>>>>>>>>>> syntax" Now, if I just put "print "Game Over"" then it says > Game Over > >>>>>>>>>>>>>> UNDERNEATH the code I just printed! > >>>>>>>>>>>>>> now I am following the book to the *pixel* and that is not > >>>>>>>>>>>>>> what is supposed to happen! > >>>>>>>>>>>>>> Please email me back as soon as you get this...(if you are > >>>>>>>>>>>>>> not to busy). > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> Thanks,Nicholas > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> -- > >>>>>>>>>>>>>> http://mail.python.org/mailman/listinfo/python-list > >>>>>>>>>>>>>> > >>>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> > >>>>>>>>>>>>> -- > >>>>>>>>>>>>> Joel Goldstick > >>>>>>>>>>>>> http://joelgoldstick.com > >>>>>>>>>>>>> > >>>>>>>>>>>> > >>>>>>>>>>>> > >>>>>>>>>>>> Sorry, I am using Windows 7 Ultimate 32-bit with Python 3.3 > >>>>>>>>>>>> Here is the code in exact form > >>>>>>>>>>>> print "Game Over" > >>>>>>>>>>>> raw_input("\n\nPress Enter Key to Exit") > >>>>>>>>>>>> Thanks, > >>>>>>>>>>>> Nicholas > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> You need to unindent the raw_input like so: > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> print "Game Over" > >>>>>>>>>>> raw_input("\n\nPress Enter Key to Exit") > >>>>>>>>>>> > >>>>>>>>>>> In python you indent code blocks (like for loops, if > statements, > >>>>>>>>>>> function blocks, etc.). You can't just indent from one line > to the next in > >>>>>>>>>>> sequential code or you will be told its a syntax error > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> > >>>>>>>>>>> -- > >>>>>>>>>>> Joel Goldstick > >>>>>>>>>>> http://joelgoldstick.com > >>>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> > >>>>>>>>>> -- > >>>>>>>>>> Nicholas J. Piotrowski > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> > >>>>>>>>> -- > >>>>>>>>> Joel Goldstick > >>>>>>>>> http://joelgoldstick.com > >>>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> > >>>>>>>> -- > >>>>>>>> Nicholas J. Piotrowski > >>>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> > >>>>>>> -- > >>>>>>> Joel Goldstick > >>>>>>> http://joelgoldstick.com > >>>>>>> > >>>>>> > >>>>>> > >>>>>> > >>>>>> -- > >>>>>> Joel Goldstick > >>>>>> http://joelgoldstick.com > >>>>>> > >>>>> > >>>>> > >>>>> > >>>>> -- > >>>>> Nicholas J. Piotrowski > >>>>> > >>>> > >>>> > >>>> > >>>> -- > >>>> Joel Goldstick > >>>> http://joelgoldstick.com > >>>> > >>>> _______________________________________________ > >>>> Tutor maillist - Tutor at python.org > >>>> To unsubscribe or change subscription options: > >>>> http://mail.python.org/mailman/listinfo/tutor > >>>> > >>>> > >>> > >> > > > > > > -- > > Nicholas J. Piotrowski > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130216/c5f049b8/attachment.html > > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 108, Issue 58 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Feb 16 07:21:52 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 16 Feb 2013 17:21:52 +1100 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> Message-ID: <511F2580.5090707@pearwood.info> On 15/02/13 16:38, eryksun wrote: > On Thu, Feb 14, 2013 at 4:33 PM, Prasad, Ramit > wrote: >> My knee jerk response is a try/finally block, but I am sure there >> are better ways. > > The atexit.register decorator hooks sys.exitfunc: > > http://docs.python.org/2/library/atexit I find a try...finally block more readable and obvious than a hidden atexit function. At least the try...finally block is explicit: try: main() finally: do_stuff() while atexit can be set anywhere and isn't obvious. It's also somewhat risky, since you never know when some library you import will silently replace it with their own hook. Also, keep in mind that you can't rely on atexit hooks to run. Or the finally block for that matter. They can fail to run when: - the Python process is killed from the outside, say using "kill -9" under Linux; - or the entire computer goes down, say after a power failure; - or the operating system crashes and takes everything else down; - or something calls os._exit() while your code is running, say some external library. So if you're serious about saving data, you cannot afford to wait until the program quits before saving the user's work. You should be saving whenever the user makes some change. -- Steven From eryksun at gmail.com Sat Feb 16 09:32:29 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 16 Feb 2013 03:32:29 -0500 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: <511F2580.5090707@pearwood.info> References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> <511F2580.5090707@pearwood.info> Message-ID: On Sat, Feb 16, 2013 at 1:21 AM, Steven D'Aprano wrote: > while atexit can be set anywhere and isn't obvious. It's also somewhat > risky, since you never know when some library you import will silently > replace it with their own hook. Use try/finally if the task is clearer that way. atexit is better suited to libraries. logging uses atexit (flushing/closing handlers) as does multiprocessing (terminating/joining active child processes). As to the risk, atexit was added in 2.0 and directly using sys.exitfunc was deprecated in 2.4. From alan.gauld at btinternet.com Sat Feb 16 10:12:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Feb 2013 09:12:18 +0000 Subject: [Tutor] Web programming question: Re: Tutor Digest, Vol 108, Issue 58 In-Reply-To: References: Message-ID: Please start new topics with a new post (ie a fresh mail to tutor at python.org) Please do not reply to digests without trimming out all irrelevant content - some people pay by the byte. Please choose a sensible subject line not "Tutor Digest..." On 16/02/13 03:09, Claira wrote: > Hi, I signed up a while ago, but I didn't really understand anything. I > have a basic question that maybe someone can help with. I'll like to > integrate yelp data -- http://www.programmableweb.com/api/yelp -- onto > google maps -- http://www.programmableweb.com/api/google-maps -- like > how http://www.trulia.com/real_estate/New_York-New_York has it under > "Amenities". Lots of web sites do this and Google provide an API to support it. > But I want it on maps.google.com Then you will need to persuade Google to do it for you. They own that web site and you cannot modify it, only they can do that. I should think its highly unlikely they would agree. > because I have no idea how to put the map on a separate webpage. That's no excuse, you just need to learn how. > I'll like to know if I need python for this :) No, you could use pretty much any programming language you choose from Ada to ZPL... But python would certainly be a contender. Start reading about how to build websites in Python and then study the Google maps API. http://docs.python.org/2/howto/webservers.html http://econym.org.uk/gmap/ HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Feb 16 11:21:36 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 16 Feb 2013 21:21:36 +1100 Subject: [Tutor] associating two objects without ORM and processing a text file In-Reply-To: References: <51193A3A.2080907@davea.name> <51199C24.1060708@pearwood.info> <511AC8B8.80207@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741819C9B2@SCACMX008.exchad.jpmchase.net> <511D4973.7040308@davea.name> <5B80DD153D7D744689F57F4FB69AF4741819D3C0@SCACMX008.exchad.jpmchase.net> <511F2580.5090707@pearwood.info> Message-ID: <511F5DB0.4000005@pearwood.info> On 16/02/13 19:32, eryksun wrote: > On Sat, Feb 16, 2013 at 1:21 AM, Steven D'Aprano wrote: >> while atexit can be set anywhere and isn't obvious. It's also somewhat >> risky, since you never know when some library you import will silently >> replace it with their own hook. > > Use try/finally if the task is clearer that way. atexit is better > suited to libraries. logging uses atexit (flushing/closing handlers) > as does multiprocessing (terminating/joining active child processes). > > As to the risk, atexit was added in 2.0 and directly using > sys.exitfunc was deprecated in 2.4. Ah yes, atexit doesn't *replace* the hook, it allows multiple hooks. Correction noted. -- Steven From dyoo at hashcollision.org Sat Feb 16 20:31:44 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 16 Feb 2013 12:31:44 -0700 Subject: [Tutor] Web programming question: Re: Tutor Digest, Vol 108, Issue 58 In-Reply-To: References: Message-ID: >> Hi, I signed up a while ago, but I didn't really understand anything. I >> have a basic question that maybe someone can help with. I'll like to >> integrate yelp data -- http://www.programmableweb.com/api/yelp -- onto >> google maps -- http://www.programmableweb.com/api/google-maps -- like >> how http://www.trulia.com/real_estate/New_York-New_York has it under >> "Amenities". > > > Lots of web sites do this and Google provide an API to support it. > >> But I want it on maps.google.com For a web mashup like this, doing it in JavaScript would probably be the most direct approach. Google provides access to the Google Maps API, and it's documented: https://developers.google.com/maps/ You'd use this API to bring up a Google Maps page, and drive its display with other sources of data. Yelp provides an accessible API for query: http://www.yelp.com/developers/documentation/v2/overview JavaScript is not Python, but that doesn't make it a bad thing. If I were to do a web mashup, I'd look into JavaScript-ing it rather than try to make the web tools through Python alone. That being said, if Python is a hard requirement here, you can look into a project like pymaps: http://code.google.com/p/pymaps/ From waveclaira at gmail.com Sun Feb 17 01:11:12 2013 From: waveclaira at gmail.com (Claira) Date: Sat, 16 Feb 2013 18:11:12 -0600 Subject: [Tutor] Python API Message-ID: I dont know how this mailing list thing works, first time on it, they should have something that makes sense like quora.com For the question I asked, I didn't know you had to do all that just to get a map. What happens if I use http://mapbox.com + Python + Yelp API ? I thought that google maps lets you add stuff, and I just want that stuff to be stuff accessible from the yelp api -- since google won't enable you to do that, then if I continue with this, will I be able to do this on mapbox without having to make a website? ------------------------------ > > Message: 3 > Date: Sat, 16 Feb 2013 09:12:18 +0000 > From: Alan Gauld > To: tutor at python.org > Subject: [Tutor] Web programming question: Re: Tutor Digest, Vol 108, > Issue 58 > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Please start new topics with a new post > (ie a fresh mail to tutor at python.org) > > Please do not reply to digests without trimming out all irrelevant > content - some people pay by the byte. > > Please choose a sensible subject line not "Tutor Digest..." > > On 16/02/13 03:09, Claira wrote: > > Hi, I signed up a while ago, but I didn't really understand anything. I > > have a basic question that maybe someone can help with. I'll like to > > integrate yelp data -- http://www.programmableweb.com/api/yelp -- onto > > google maps -- http://www.programmableweb.com/api/google-maps -- like > > how http://www.trulia.com/real_estate/New_York-New_York has it under > > "Amenities". > > Lots of web sites do this and Google provide an API to support it. > > > But I want it on maps.google.com > > Then you will need to persuade Google to do it for you. They own that > web site and you cannot modify it, only they can do that. I should think > its highly unlikely they would agree. > > > because I have no idea how to put the map on a separate webpage. > > That's no excuse, you just need to learn how. > > > I'll like to know if I need python for this :) > > No, you could use pretty much any programming language you > choose from Ada to ZPL... But python would certainly be a > contender. > > Start reading about how to build websites in Python and > then study the Google maps API. > > http://docs.python.org/2/howto/webservers.html > > http://econym.org.uk/gmap/ > > > HTH > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Sun Feb 17 01:35:01 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sat, 16 Feb 2013 17:35:01 -0700 Subject: [Tutor] Python API In-Reply-To: References: Message-ID: On Sat, Feb 16, 2013 at 5:11 PM, Claira wrote: > I dont know how this mailing list thing works, first time on it, they > should have something that makes sense like quora.com > > Be aware that mailing lists have a pretty long history, at least in computing terms. You might be interested in reading: http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html sometime. When you say that mailing lists don't make sense, it's analogous to a traveler who says that the foreign country they visit doesn't make sense. Sure, it might be true, but it does have echoes of the "ugly American" stereotype. And there is a difference between mailing lists like Python Tutor vs. sites like Quora: the mailing list has a public-access archive. http://mail.python.org/pipermail/tutor/ In contrast, Quora requires that you get an account from them to even _look_ at their database. For the question I asked, I didn't know you had to do all that just to get > a map. What happens if I use http://mapbox.com + Python + Yelp API ? > > I thought that google maps lets you add stuff, and I just want that stuff > to be stuff accessible from the yelp api -- since google won't enable you > to do that, then if I continue with this, will I be able to do this > on mapbox without having to make a website? > Hmmm... Does mapbox provide a programmable API? It looks like it may: http://mapbox.com/developers/api/ but if I'm reading it correctly, it's a JavaScript API that depends on a web browser, not one that's natively accessible from Python. I don't think it's accessible without a website, so I see no advantage over using Google Maps. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waveclaira at gmail.com Sun Feb 17 01:58:45 2013 From: waveclaira at gmail.com (Claira) Date: Sat, 16 Feb 2013 18:58:45 -0600 Subject: [Tutor] Python API In-Reply-To: References: Message-ID: On Sat, Feb 16, 2013 at 6:35 PM, Danny Yoo wrote: > > > On Sat, Feb 16, 2013 at 5:11 PM, Claira wrote: > >> I dont know how this mailing list thing works, first time on it, they >> should have something that makes sense like quora.com >> >> > Be aware that mailing lists have a pretty long history, at least in > computing terms. You might be interested in reading: > > http://www.gweep.ca/~edmonds/usenet/ml-etiquette.html > > sometime. When you say that mailing lists don't make sense, it's > analogous to a traveler who says that the foreign country they visit > doesn't make sense. Sure, it might be true, but it does have echoes of the > "ugly American" stereotype. > > And there is a difference between mailing lists like Python Tutor vs. > sites like Quora: the mailing list has a public-access archive. > http://mail.python.org/pipermail/tutor/ In contrast, Quora requires that > you get an account from them to even _look_ at their database. > > :) But when I google, google never takes me to the open python.org -- and > I don't know any of sterotypes since you're the one in America. > > For the question I asked, I didn't know you had to do all that just to get >> a map. What happens if I use http://mapbox.com + Python + Yelp API ? >> >> I thought that google maps lets you add stuff, and I just want that stuff >> to be stuff accessible from the yelp api -- since google won't enable you >> to do that, then if I continue with this, will I be able to do this >> on mapbox without having to make a website? >> > > Hmmm... Does mapbox provide a programmable API? It looks like it may: > > http://mapbox.com/developers/api/ > > but if I'm reading it correctly, it's a JavaScript API that depends on a > web browser, not one that's natively accessible from Python. I don't think > it's accessible without a website, so I see no advantage over using Google > Maps. > :) Ok I'll ask those on the mapbox site about this and see how to go about this. Thanks!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 17 02:34:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Feb 2013 01:34:15 +0000 Subject: [Tutor] Python API In-Reply-To: References: Message-ID: On 17/02/13 00:11, Claira wrote: > I don't know how this mailing list thing works, Most mailing lists work the same way. You sign up and any mails that get sent to the server get relayed to all of the members. That's about all there is to it. But there are some social conventions in the way people behave, mostly designed for the convenience of all - like adding good subject lines, not sending unnecessary data etc > For the question I asked, I didn't know you had to do all that just to > get a map. What happens if I use http://mapbox.com + Python + Yelp API ? All what? You need a web site - even if its only on your local PC. That's how web pages get displayed (unless its just static html/Javascript). You can certainly build a web site with mapbox+Python+Yelp. > I thought that google maps lets you add stuff, It does but not on the Googlemaps web site. You have to use their interface to fetch the information and display their maps on your website. You can use layers and iFrames to display the maps on one layer and superimpose another layer with your data on top, but frankly that's harder than using the API... > stuff to be stuff accessible from the yelp api An API is a programmers interface. You can use the yelp api to interact with the yelp site, but I don;t think it will let you do anything with the Google website. You need to do that with the Google API. > -- since google won't enable you to do that, then if I continue > with this, will I be able to do this on mapbox No idea. I've never heard of mapbox. A quick Google later and it seems to enable you to create custom maps and publish them *to your website*. So you still need to create a web site, the only difference from Google is that you get to design your own maps instead of using Google style. > without having to make a website? It's unusual for any website to allow other people to change it. It would have horrendous security ramifications and could get their site closed down. But, a web site doesn't need to be public or big, it can run on your own PC. You just need to install/configure the web server software. It's probably already available in your OS. It might help if we had some background info: 1) Can you already program in any language or are you a complete beginner? 2) Have you ever created a web site of any kind before? 3) Have you ever created web pages using HTML before? That will give us some idea of where to pitch our responses/explanations. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Feb 17 04:21:22 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 17 Feb 2013 14:21:22 +1100 Subject: [Tutor] Python API In-Reply-To: References: Message-ID: <51204CB2.4030801@pearwood.info> On 17/02/13 12:34, Alan Gauld wrote: > It's unusual for any website to allow other people to change it. *cough* You may have heard of a little site called "Wikipedia"... ? http://en.wikipedia.org/wiki/Main_Page A very, very small selection of other collaborative wikis: http://c2.com/cgi/wiki http://www.wikispaces.com/ http://tvtropes.org/ http://rationalwiki.org/wiki/Main_Page http://www.conservapedia.com/Main_Page http://starwars.wikia.com/wiki/Main_Page http://discworld.wikia.com/wiki/Main_Page http://wiki.lspace.org/mediawiki/index.php/Main_Page http://stackoverflow.com/ Some of these require a login account, but since there are few or no restrictions on who can get an account, that is not a big deal. -- Steven From alan.gauld at btinternet.com Sun Feb 17 10:01:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Feb 2013 09:01:59 +0000 Subject: [Tutor] Python API In-Reply-To: <51204CB2.4030801@pearwood.info> References: <51204CB2.4030801@pearwood.info> Message-ID: On 17/02/13 03:21, Steven D'Aprano wrote: > On 17/02/13 12:34, Alan Gauld wrote: > >> It's unusual for any website to allow other people to change it. > > *cough* > > You may have heard of a little site called "Wikipedia"... ? Yep, that's why I said 'unusual' not 'unknown'. :-) But wiki's are a very special type of web site. You could argue the same for Facebook etc although they work more like collections of web sites. > Some of these require a login account, but since there are few or no > restrictions on who can get an account, that is not a big deal. There are few restrictions on access but there are often restrictions on what you can do to them. You can't go onto wikipedia and change the style or layout of the pages. Also many are moderated before posts show up. I doubt very much if you could just go in and overlay a wikipedia page with an iFrame containing an Encyclopedia Britannica article on the same subject. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From brajesh_pant at hotmail.com Sun Feb 17 10:14:14 2013 From: brajesh_pant at hotmail.com (Brajesh pant) Date: Sun, 17 Feb 2013 14:44:14 +0530 Subject: [Tutor] Invoking python script Message-ID: Hello there .. I want to know is there any python module which can tell when a cut command or copy command is invoked. Actually i want to build a utility such that a when a file or folder is copied i want to automatically run my python script .. Thanks Brajesh Pant From steve at pearwood.info Sun Feb 17 11:13:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 17 Feb 2013 21:13:17 +1100 Subject: [Tutor] Invoking python script In-Reply-To: References: Message-ID: <5120AD3D.9050909@pearwood.info> On 17/02/13 20:14, Brajesh pant wrote: > Hello there .. > I want to know is there any python module which can tell when a cut >command or copy command is invoked. Invoked by what? What program is doing the copy or cut? > Actually i want to build a utility such that a when a file or folder >is copied i want to automatically run my python script .. That depends on what facilities your desktop environment is running. You may not even have a desktop environment. What are you running? Irix Interactive Desktop Apple Finder TDE/KDE 3 KDE 4 Gnome CDE XFCE LXDE ROX IceWM Sugar Cinnamon Mezzo to mention only a few. -- Steven From alan.gauld at btinternet.com Sun Feb 17 16:57:39 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Feb 2013 15:57:39 +0000 Subject: [Tutor] Invoking python script In-Reply-To: References: Message-ID: On 17/02/13 09:14, Brajesh pant wrote: > Hello there .. > I want to know is there any python module which can tell > when a cut command or copy command is invoked. There are but probably not trivially. but you need to understand what you are asking for. A cut/copy command is a desktop environment thing that is specific to the GUI and the application you are using. It would include any cut/copy action including manipulating text in a word processor or numbers in a spreadsheet. These are commands to an application to do something to its underlying data model. In the case of a File explorer that model is the file system, in a web browser its the screen artifacts being displayed (actually the DOM). So just because you detected cut/paste commands in the GUI that would not necessarily be the commands you are interested in, and there ay be other ways of modifying the files (eg via command line) that cut/copy would not detect. In fact if you used a different file explorer (eg a KDE v a Gnome based one) you probably wouldn't detect those events. Unless you are doing something atbthe GUI level that is almost certainly the wrong starting point! > Actually i want to build a utility such that a when a file or folder > is copied i want to automatically run my python script .. > And this is a far different thing because you specifically want to monitor the file-system regardless of how the files get moved. This is very dependent on the OS and even the file-system. For example with a journalling file-system it will be much easier to do this than with the old DOS FAT based system or even older Unix systems like ext2. And I don;t know of any Python modules that would help directly, I suspect you need to get down 'n dirty with the OS itself. I'll be interested to see what other folks suggest on this one. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jf_byrnes at comcast.net Sun Feb 17 17:50:11 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 17 Feb 2013 10:50:11 -0600 Subject: [Tutor] Need help with sqlite3 in python Message-ID: I am writing a small database CRUD app using python 2.7, pythoncard, sqlite3 on Ubuntu 12.04. So far I can retrieve data fine but I cannot do inserts. In my first attempt I used parameter substitution. When that did not work I thought I didn't understand it and decided to try a simple insert. I modeled the code after the example on the python sqlite3 page. Here is the code that does not work. Note: Don't mind the title, the delete button had no code yet and seemed to be the easiest place to run this simple test. def on_buttonDelete_mouseClick(self, event): conn = sqlite3.connect("/home/jfb/MyProgs/Pwds/passwords") cur = conn.cursor() cur.execute("INSERT INTO pwds VALUES ('WebSites', 'xMe', 'me', 'you', 'here', 'there')") conn.commit() conn.close() print 'done' When this code is run, done prints in the terminal, there is no error message, the row is not inserted and the file modified time is not changed. The permissions set on the file are -rw -rw -rw. Sqlite3 is imported and if I mangle the path or execute line it complains. If I run the same sql in Sqliteman the row is inserted as expected. Appreciate it if someone could give me an idea of what I am doing wrong. Thanks, Jim From alan.gauld at btinternet.com Sun Feb 17 19:31:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Feb 2013 18:31:52 +0000 Subject: [Tutor] Need help with sqlite3 in python In-Reply-To: References: Message-ID: On 17/02/13 16:50, Jim Byrnes wrote: > cur.execute("INSERT INTO pwds VALUES ('WebSites', 'xMe', 'me', > 'you', 'here', 'there')") > > When this code is run, done prints in the terminal, there is no error Can you do selects properly? Can you extract data put in manually? That would prove the connection from Python to SQLite was working... Usually when I get errors like that its because the values do not match the number of fields/types in the table definition, but if the manual sql works with the same query that shouldn't be the issue so I'd suspect the connection... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jf_byrnes at comcast.net Sun Feb 17 20:47:04 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Sun, 17 Feb 2013 13:47:04 -0600 Subject: [Tutor] Need help with sqlite3 in python In-Reply-To: References: Message-ID: On 02/17/2013 12:31 PM, Alan Gauld wrote: > On 17/02/13 16:50, Jim Byrnes wrote: > >> cur.execute("INSERT INTO pwds VALUES ('WebSites', 'xMe', 'me', >> 'you', 'here', 'there')") >> >> When this code is run, done prints in the terminal, there is no error > > Can you do selects properly? > Can you extract data put in manually? That would prove the connection > from Python to SQLite was working... Thank you Alan. Your question led me to the solution. So many times it is dumb little mistakes that trip you up. I had moved a copy of the db into the directory I was developing in but was inserting in the working copy. The insertions were there I was just looking at the wrong db with Sqliteman. > Usually when I get errors like that its because the values do not match > the number of fields/types in the table definition, but if the manual > sql works with the same query that shouldn't be the issue so I'd suspect > the connection... > Regards, Jim From oscar.j.benjamin at gmail.com Mon Feb 18 00:27:33 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 17 Feb 2013 23:27:33 +0000 Subject: [Tutor] Invoking python script In-Reply-To: References: Message-ID: On 17 February 2013 15:57, Alan Gauld wrote: > On 17/02/13 09:14, Brajesh pant wrote: >> >> Actually i want to build a utility such that a when a file or folder > >> is copied i want to automatically run my python script .. >> > > And this is a far different thing because you specifically want to monitor > the file-system regardless of how the files get moved. > This is very dependent on the OS and even the file-system. For example with > a journalling file-system it will be much easier to do this than with the > old DOS FAT based system or even older Unix systems like ext2. > And I don;t know of any Python modules that would help directly, I suspect > you need to get down 'n dirty with the OS itself. > > I'll be interested to see what other folks suggest on this one. I would suggest watchdog: http://pypi.python.org/pypi/watchdog There are other packages that do this but watchdog is the only one that I have used. This is a Python package that enables you to watch for changes in a directory. I've used it on Linux but it claims to work on Windows, OSX and BSD as well. Using this you can run any Python code you like when a change occurs. The way it works is that you have a script that imports and uses the watchdog module. You run that script telling it to watch a particular folder and while it is running it will be notified of any changes and will run the code that you specify for each event. Oscar From michael at seomoz.org Mon Feb 18 08:36:25 2013 From: michael at seomoz.org (Michael O'Leary) Date: Sun, 17 Feb 2013 23:36:25 -0800 Subject: [Tutor] Class-based generator Message-ID: I wrote some code to create tasks to be run in a queue based system last week. It consisted of a big monolithic function that consisted of two parts: 1) read data from a file and create dictionaries and lists to iterate through 2) iterate through the lists creating a job data file and a task for the queue one at a time until all of the data is dealt with My boss reviewed my code and said that it would be more reusable and Pythonic if I refactored it as a generator that created job data files and iterated by calling the generator and putting a task on the queue for each job data file that was obtained. This made sense to me, and since the code does a bunch of conversion of the data in the input file(s) to make it easier and faster to iterate through the data, I decided to create a class for the generator and put that conversion code into its __init__ function. So the class looked like this: class JobFileGenerator: def __init__(self, filedata, output_file_prefix, job_size): def next(self): while : The problem is that the generator object is not created until you call next(), so the calling code has to look like this: gen = JobFileGenerator(data, "output_", 20).next() for datafile in gen.next(): This code works OK, but I don't like that it needs to call next() once to get a generator and then call next() again repeatedly to get the data for the jobs. If I were to write this without a class as a single generator function, it would not have to do this, but it would have the monolithic structure that my boss objected to. Would it work to do this: for datafile in JobFileGenerator(data, "output_", 20).next(): or would that cause the JobFileGenerator's __init__ function to be called more than once? Are there examples I could look at of generator functions defined on classes similar to this, or is it considered a bad idea to mix the two paradigms? Thanks, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Feb 18 09:58:35 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 18 Feb 2013 08:58:35 +0000 Subject: [Tutor] Class-based generator In-Reply-To: References: Message-ID: On 18 February 2013 07:36, Michael O'Leary wrote: > I wrote some code to create tasks to be run in a queue based system last > week. It consisted of a big monolithic function that consisted of two parts: > 1) read data from a file and create dictionaries and lists to iterate > through > 2) iterate through the lists creating a job data file and a task for the > queue one at a time until all of the data is dealt with > > My boss reviewed my code and said that it would be more reusable and > Pythonic if I refactored it as a generator that created job data files and > iterated by calling the generator and putting a task on the queue for each > job data file that was obtained. > > This made sense to me, and since the code does a bunch of conversion of the > data in the input file(s) to make it easier and faster to iterate through > the data, I decided to create a class for the generator and put that > conversion code into its __init__ function. So the class looked like this: It's not a "generator" if you create a class for it. Your class is (trying to be) an iterator. > class JobFileGenerator: > def __init__(self, filedata, output_file_prefix, job_size): > > > def next(self): > while : > next() should return a single item not a generator that yields items. If you perhaps rename the next function as __iter__ then it will be a proper iterator. I suspect however that your boss just wants you to write a single generator function rather than an iterator class. For example: def generate_jobs(): while : yield for job in generate_jobs(): From __peter__ at web.de Mon Feb 18 10:00:47 2013 From: __peter__ at web.de (Peter Otten) Date: Mon, 18 Feb 2013 10:00:47 +0100 Subject: [Tutor] Class-based generator References: Message-ID: Michael O'Leary wrote: > I wrote some code to create tasks to be run in a queue based system last > week. It consisted of a big monolithic function that consisted of two > parts: 1) read data from a file and create dictionaries and lists to > iterate through > 2) iterate through the lists creating a job data file and a task for the > queue one at a time until all of the data is dealt with > > My boss reviewed my code and said that it would be more reusable and > Pythonic if I refactored it as a generator that created job data files and > iterated by calling the generator and putting a task on the queue for each > job data file that was obtained. > > This made sense to me, and since the code does a bunch of conversion of > the data in the input file(s) to make it easier and faster to iterate > through the data, I decided to create a class for the generator and put > that conversion code into its __init__ function. So the class looked like > this: > > class JobFileGenerator: > def __init__(self, filedata, output_file_prefix, job_size): > > > def next(self): > while : > > > The problem is that the generator object is not created until you call > next(), so the calling code has to look like this: > > gen = JobFileGenerator(data, "output_", 20).next() > for datafile in gen.next(): > > > This code works OK, but I don't like that it needs to call next() once to > get a generator and then call next() again repeatedly to get the data for > the jobs. If I were to write this without a class as a single generator > function, it would not have to do this, but it would have the monolithic > structure that my boss objected to. > > Would it work to do this: > > for datafile in JobFileGenerator(data, "output_", 20).next(): > > > or would that cause the JobFileGenerator's __init__ function to be called > more than once? Are there examples I could look at of generator functions > defined on classes similar to this, or is it considered a bad idea to mix > the two paradigms? > Thanks, > Mike You are abusing the next method; it is called once to build a generator. The convention for that is to use either a descriptive name (jobs() or somesuch) or __iter__(): class JobFile: def __init__(self, filedata, output_file_prefix, job_size): def __iter__(self): while : for job in JobFile(data, "output_", 20): Here the generator is created by the implicit call to JobFile.__iter__() at the start of the for loop. Subsequent iterations call next() on the generator returned by that call. If you want the class itself to generate items you need a different approach: class JobFileIter: def __init__(self, filedata, output_file_prefix, job_size): self._done = False def __iter__(self): return self def next(self): if self._done or : self._done = True raise StopIteration return for job in JobFileIter(data, "output_", 20): Here __iter__() returns the JobFileIter instance, so for every iteration of the for loop JobFileIter.next() will be called -- until a StopIteration is raised. That said, it is often sufficient to refactor complex code into a few dedicated functions -- Python is not Java, after all. PS I'm assuming Python 2 -- for Python 3 the next() method must be replaced by __next__(). From chigga101 at gmail.com Mon Feb 18 18:30:58 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 18 Feb 2013 17:30:58 +0000 Subject: [Tutor] following on Message-ID: hey guys ive been learning programming/python for less than a year. i feel very comfortable with it now. After the initial beginners guide i asked on here what to learn next. I started learning a GUI library and also pygame. i decided to learn more about OOP also. My problem is yes i can attempt to use these libraries/frameworks/modules provided but how can i build or get better at creating/building my own tools? i do ok in programming conversations until they start talking about "the standard etc wasnt good enough so i built my own! i did this, i this and i did that!" or hey i built my own engine, my own language!! etc... i become absolutely lost and thought i would like to do that! The extra OOP has given me hints on what i need to do, but i was wondering if anyone could point me out to some good books or online tutorials that can teach me how to create my own modules, libraries that others could use. This is what is called software engineering right? or is that something else? I decided not to sit around and ponder so i decided on a project (when im bored) that could help. i wanted to code a custom class that will create custom instances and have these instances behave like normal python objects. I want my program to basically do EVETYTHING that python already does but in my own way. On the objects i'd like to perform stuff like __add__ or __cmp__ on them, but without actually using __add__ or __cmp__, get it?. ill attempt my own built-ins also, like summed() instead of sum()... is this a constructive exercise or a waste of time? i honestly dont know, i guess i'd just like a better understanding of how everything works. like how can i make my own custom container and not have it subclass list(), and still act like a list()? would i need to use stuff like __next__ and __iter__ or could i create my own that acts the same way ill drop the project if its a bad idea but if it isnt, its simply a work in progress(barely started). my __init__ sp far only accepts ints right now but ill attempt to make the class accept any type of python object, and offer custom behaviour for that specific object type. so please point me out to some good books or online tutorials that can teach me how to create my own software that others could use. Also what is the correct term for this type of programming? Also if you have any personal advice you could offer me, please do.. Thanks From alan.gauld at btinternet.com Mon Feb 18 19:22:42 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Feb 2013 18:22:42 +0000 Subject: [Tutor] following on In-Reply-To: References: Message-ID: On 18/02/13 17:30, Matthew Ngaha wrote: > i can attempt to use these libraries/frameworks/modules provided but > how can i build or get better at creating/building my own tools? practice. Just build a lot of stuff. Its the only way. > and i did that!" or hey i built my own engine, my own language!! That doesn't happen all that often, usually people just extend the existing language. > etc... i become absolutely lost and thought i would like to do that! What? Get absolutely lost?! :-) > wondering if anyone could point me out to some good books or online > tutorials that can teach me how to create my own modules, libraries > that others could use. In python this is almost trivial. Just create a Python script that has functions or classes in it. That's it. Make it available for import by putting it somewhere in your import path. job done. There is a little bit more to creating a package rather than a module but its easy once you've got the hang of making modules. > This is what is called software engineering No, its a part of software engineering. Software engineering is an attempt to apply traditional engineering discipline to software development in the hope that it will make the development process more predictable, reliable and consistent. So far it's pretty much failed because most "software engineers" don't really like doing hard math when they could be writing code, and doing hard math before building anything is pretty much what makes it engineering... (This is why some US states refuse to acknowledge software engineering as 'real' engineering.) But it also includes things like creating modular designs and performing comprehensive tests and documenting the design in standard formats etc. Those aspects have caught on in varying degrees. > > create custom instances and have these instances behave like normal > python objects. Thats good. > I want my program to basically do EVETYTHING that > python already does but in my own way. On the objects i'd like to > perform stuff like __add__ or __cmp__ on them, but without actually > using __add__ or __cmp__, get it?. No, that's probably not good. > I'll attempt my own built-ins also, And that's almost certainly even worse. > like summed() instead of sum()... is this a constructive exercise or a > waste of time? Its a waste of time given where you are on your learning journey. Maybe some day you will have a valid need to create your own language but this is almost certainly not it! > understanding of how everything works. Use it., Experiment with it. Break it. Thats the best way. Read the source code its all available in Python or C. > like how can i make my own custom container and not have it > subclass list(), and still act like a list()? That's a more sensible option especially if you make it a type of container that Python doesn't already have. Maybe a bag or a stack or even a circular list. But there is no shame in inheriting from list if that makes sense. That would be good software engineering - don't reinvent the wheel! > would i need to use stuff like __next__ and __iter__ or could > i create my own that acts the same way You need to implement all the special methods that give Python objects their built-in behaviour. Or at least all the ones that matter, or make sense, for your data type. > ill drop the project if its a bad idea but if it isnt, its simply a > work in progress(barely started). I'd forget trying to rewrite Python in python. Even as a learning project it has limited value and as a practical proposition no value at all. Better to build something meaningful that pushes the envelope with python. > so please point me out to some good books or online tutorials that can > teach me how to create my own software that others could use. Also > what is the correct term for this type of programming? Just programming. Its what we should all be doing all the time! > have any personal advice you could offer me, please do.. Thanks When building reusable code start from the perspective of the user. Write some tests that use the new creation even though it doesn't exist yet. Make the code as easy to use as possible. Once you know how to use it, start building the thing so that it can be used the way you want it to work. The hard effort should be in building the reusable code not in using it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From n.rautenhaus at gmx.de Mon Feb 18 19:22:54 2013 From: n.rautenhaus at gmx.de (Niclas Rautenhaus) Date: Mon, 18 Feb 2013 19:22:54 +0100 Subject: [Tutor] if/else option for making a choice Message-ID: <002101ce0e04\$f90a4160\$eb1ec420\$@rautenhaus@gmx.de> Hello folks, I would be very pleased if someone is able to help me. I wrote a small programm, to calculate the grand total for a car. A basic price can be entered. Given that basic price, a tax peercentage is calculated and added tot he grand total. But unfortunately I am stuck with giving the user the choice to select an additional option! The extra items have got set values, but at the moment they all get summarized, but i want to choose. AFAIK I already tried: Print raw_input ((?Would you like to have leather??) ? then yes or no If raw_input == yes Print Leather (Leather) ? displaying the variables value Plus adding the item at the end to concatenate it with the basic value. I hope it is clear where my problem is. Regards, Niclas My code I already wrote: ----------------------------- #Car price calculator # Set variables for additional items Leather = (500) int (Leather) Clima = (1500) int (Clima) Hifi = (250) int (Hifi) Electrics = (750) int (Electrics) Comfort = (2500) int (Comfort) print "\t\t\tWelcome to the car price calculator!" print "\t\t\tCredits belong to Niclas Rautenhaus" print "\n\nPlease enter the basic price: " basic = int (raw_input()) # Tax is a percentage of the basic car price Tax = basic * 5 / 100 int (Tax) print "\nAdded items:" # Here the user should have the possibility to pick either yes or no print "\n\nLeather",(Leather) print "Clima",(Clima) print "Hifi", (Hifi) print "Electrics", (Electrics) print "Comfort", (Comfort) print "Tax", (Tax) # Last step: the picked items shall be summarized print "\n\nTotal grand:", basic + Leather + Clima + Hifi \ + Electrics + Comfort + Tax raw_input ("\nPress the enter key to exit!") -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Mon Feb 18 20:01:02 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 18 Feb 2013 19:01:02 +0000 Subject: [Tutor] following on In-Reply-To: References: Message-ID: >> understanding of how everything works. > > Use it., Experiment with it. Break it. > Thats the best way. Read the source code its all available in > Python or C. > Hey can you please tell me which source code youre referring too? The initial files that come with Python? also the C code, where can i locate this? is C something worth learning? why is Python code available in C? > >> like how can i make my own custom container and not have it >> subclass list(), and still act like a list()? > > That's a more sensible option especially if you make it a type of container > that Python doesn't already have. Maybe a bag or a stack > or even a circular list. But there is no shame in inheriting from > list if that makes sense. That would be good software engineering - don't > reinvent the wheel! > When building reusable code start from the perspective of the user. Write yes i will try not to reinvent the wheel, a lot of tutorials ive read seem to always point this out. Just out of curiousity what is a bag, stack or circular list? what is needed to create something like this? i sort of heard about a stack its a C/C++ thing i think? From steve at alchemy.com Mon Feb 18 20:22:22 2013 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 18 Feb 2013 11:22:22 -0800 Subject: [Tutor] following on In-Reply-To: References: Message-ID: <20130218192222.GB38727@dragon.alchemy.com> On Mon, Feb 18, 2013 at 07:01:02PM +0000, Matthew Ngaha wrote: > >> understanding of how everything works. > > > > Use it., Experiment with it. Break it. > > Thats the best way. Read the source code its all available in > > Python or C. > > > > Hey can you please tell me which source code youre referring too? The > initial files that come with Python? also the C code, where can i > locate this? is C something worth learning? why is Python code > available in C? C is definitely worth learning. So is LISP. And a handful of other languages we could enumerate. It's worth learning if it adds something useful to your understanding of how computers operate on the instructions you give them, or if it changes your approach to creating software in a fundamental way. Actually using those languages in daily life is not the point. C, however, is still very useful in a number of situations. Python programmers can get leverage from its strengths by--for example--writing performance-critical modules in C and then calling them from their Python programs. Python itself (well, the standard implementation of it anyway) is written in C. It has to be written in something that ultimately compiles down to the machine language which the computer actually uses. That C code interprets your Python code so you have a much nicer, high-level programming environment to work with. But the computer itself doesn't directly understand Python. > yes i will try not to reinvent the wheel, a lot of tutorials ive read > seem to always point this out. Just out of curiousity what is a bag, > stack or circular list? what is needed to create something like this? > i sort of heard about a stack its a C/C++ thing i think? None of these are C/C++ things. They are basic building-blocks of Computer Science and data structures you'll use regardless of language. I'd really recommend investing some time reading up on these and other fundamental data structures. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From steve at alchemy.com Mon Feb 18 20:15:23 2013 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 18 Feb 2013 11:15:23 -0800 Subject: [Tutor] if/else option for making a choice In-Reply-To: <002101ce0e04\$f90a4160\$eb1ec420\$@rautenhaus@gmx.de> References: <002101ce0e04\$f90a4160\$eb1ec420\$@rautenhaus@gmx.de> Message-ID: <20130218191523.GA38727@dragon.alchemy.com> On Mon, Feb 18, 2013 at 07:22:54PM +0100, Niclas Rautenhaus wrote: > Hello folks, > I hope it is clear where my problem is. Not completely, but let's take a look at what you have so far. > # Set variables for additional items > Leather = (500) > int (Leather) > Clima = (1500) > int (Clima) ... You don't need to put parens around the values, but more importantly note that the "int" lines don't do anything here. When you say: > Hifi = (250) > int (Hifi) You set Hifi to the value 250 in the first line, which is fine, but then you call int() to turn the integer 250 into the integer 250, and then promptly discard that value. If you had, for example, a string "250" and wanted to turn it into an integer, you could do something like Hifi = int("250") But simply saying int(250) accomplishes nothing. Do you see why? > print "\n\nPlease enter the basic price: " > > basic = int (raw_input()) I'm curious why the price of the car has to be an integer. Couldn't it be something like 15999.95? > # Tax is a percentage of the basic car price > > Tax = basic * 5 / 100 You would be better off using floats here if you want a real number as the answer. You're working in integers. > int (Tax) Or maybe you really want integers only to keep the numbers easier or something. Fair enough, but again this line does absolutely nothing. You truncate Tax to an integer but then discard that integer value as soon as it's created. > print "\nAdded items:" > # Here the user should have the possibility to pick either yes or no > print "\n\nLeather",(Leather) The parentheses are unnecessary here. To have them choose, you need some kind of "if" statement. Maybe something like choice = raw_input("Would you like windows?") if choice == 'yes': windows = 150 There are certainly more sophisticated ways to do this as well, when you get past the basics of how conditionals (if statements) work. For example, making a function that asks each question and handles all the different ways the user might answer other than typing precisely "yes". Or putting the choices in a list instead of repeating the choice-asking code over and over. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From alan.gauld at btinternet.com Mon Feb 18 20:49:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Feb 2013 19:49:22 +0000 Subject: [Tutor] following on In-Reply-To: References: Message-ID: On 18/02/13 19:01, Matthew Ngaha wrote: > initial files that come with Python? also the C code, where can i > locate this? Look in the python.org download page and you will find a link to the source for that release. For 3.3 it's here: http://www.python.org/download/releases/3.3.0/ Look at the first 3 bullets item under the Download header. > is C something worth learning? why is Python code > available in C? Because the core Python language is written in C. And many of the library modules have been written in C for performance reasons. Its worth getting a basic understanding of C, enough to read it if not enough to write it(much harder). > seem to always point this out. Just out of curiousity what is a bag, > stack or circular list? Use Wikipedia, it will explain what these standard computer science containers are and how they work. Wikipedia is a fantastic learning tool for would be programmers. > what is needed to create something like this? Any general purpose programming language, such as Python. > i sort of heard about a stack its a C/C++ thing i think? No, its a computing thing. It can be done in any common programming language. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 18 21:08:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 18 Feb 2013 20:08:14 +0000 Subject: [Tutor] if/else option for making a choice In-Reply-To: <13859.4154421755\$1361213413@news.gmane.org> References: <13859.4154421755\$1361213413@news.gmane.org> Message-ID: On 18/02/13 18:22, Niclas Rautenhaus wrote: > But unfortunately I am stuck with giving the user the choice to select > an additional option! > The extra items have got set values, but at the moment they all get > summarized, but i want to choose. > > AFAIK I already tried: > > Print raw_input ((?Would you like to have leather??) ? then yes or no > > If raw_input == yes > > Print Leather (Leather) ? displaying the variables value > This isn't Python code and nothing like it appears in the code you posted below. There are several problems with the code above: - print does not start with uppercase P. - You have two (( at the raw_input - if starts lower case i - raw_input is a function so you shouldn't compare it to yes - you don't assign the input value to a variable(although you do in the code below so you know you should...) - you compare to yes but it probably should be "yes" - a string. - The Print Leather line makes no sense at all. If you are going to post code post real code. Or else make it clear its pseudo code. Now on to the code you did post... > I hope it is clear where my problem is. Not really. Did you try running it? Did you get an error? If so what? > #Car price calculator > > # Set variables for additional items > Leather = (500) Why in ()? you don;t need them > int (Leather) And this does nothing - its already an int - and you ignore the result. > Clima = (1500) > int (Clima) > Hifi = (250) > int (Hifi) > Electrics = (750) > int (Electrics) > Comfort = (2500) > int (Comfort) See above for all of these. > print "\t\t\tWelcome to the car price calculator!" > print "\t\t\tCredits belong to Niclas Rautenhaus" > print "\n\nPlease enter the basic price: " > basic = int (raw_input()) Now the last line is what your code above should have looked like. > # Tax is a percentage of the basic car price > Tax = basic * 5 / 100 > int (Tax) The int() gets thrown away but thats probably good because you don't want to lose the fractional part of the tax value, which is what int() would do. > print "\nAdded items:" > # Here the user should have the possibility to pick either yes or no > print "\n\nLeather",(Leather) > print "Clima",(Clima) > print "Hifi", (Hifi) > print "Electrics", (Electrics) > print "Comfort", (Comfort) > print "Tax", (Tax) Again you don't need those parentheses > # Last step: the picked items shall be summarized > print "\n\nTotal grand:", basic + Leather + Clima + Hifi \ > + Electrics + Comfort + Tax > > raw_input ("\nPress the enter key to exit!") Personally I'd have split it at the comma: print "\n\nTotal grand:", \ basic + Leather + Clima + Hifi + Electrics + Comfort + Tax But that's a minor quibble. Ironically I might also have used parentheses to group the additions, like so: print "\n\nTotal grand:", (basic + Leather + Clima + Hifi + Electrics + Comfort + Tax) Or perhaps better still put them in a list and used sum() items = [basic, Leather, Clima, Hifi, Electrics, Comfort, Tax] print "\n\nTotal grand:", sum(items) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 18 23:58:59 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 18 Feb 2013 22:58:59 +0000 (GMT) Subject: [Tutor] Fw: if/else option for making a choice In-Reply-To: <001b01ce0e1c\$2e766fb0\$8b634f10\$@rautenhaus@gmx.de> References: <13859.4154421755\$1361213413@news.gmane.org> <001b01ce0e1c\$2e766fb0\$8b634f10\$@rautenhaus@gmx.de> Message-ID: <1361228339.78636.YahooMailNeo@web186002.mail.ir2.yahoo.com> forwarding to the group. please use reply all to respond to list messages. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ----- >From: Niclas Rautenhaus >To: 'Alan Gauld' >Sent: Monday, 18 February 2013, 21:09 >Subject: Re: [Tutor] if/else option for making a choice > >Thanks for your corrections :) > >Well, first at all I sticked to my book, minor mistakes are my bad, I tried >to write it on my own. > >>This isn't Python code and nothing like it appears in the code you posted >below. There are several problems with the code above: > > >The typos are a result of my e-mail program, I do know, that these commands >do not start with a capital letter. > >>- You have two (( at the raw_input >Thanks. > >> raw_input is a function so you shouldn't compare it to yes >That is not the point. I do know so. The result oft he user input (yes or >no) shall trigger a 'yes' or a 'no" event. > >> you don't assign the input value to a variable(although you >? do in the code below so you know you should...) >The input value is clearly working. I can type in different amounts. > >> The Print Leather line makes no sense at all. >The programm should give me a hint that the 'yes' input has been recogniced. > >>Did you try running it? Did you get an error? >I did'nt get any errors. The programm runs fine. > >Trying to clarify what I want to do: >The programm runs fine. The items (leather, hifi and so on) have set values. >I >Think of customizing a car for your needs. What do you want, interior, hifi, >engine; at each step the configurator asks you what you want to pick. >So to put it in a nutshell, the programm should ask, whether an option is >chosen, or not. > >Each optional feature (the ones with the set values) shall print a line: "Do >you want this item?" "Yes or no" and demanding an user input. >Referring to this user input, the programm adds (ore take it easy, prints >the item) or skips it. > >I appreciate your help, > >Niclas > > > > >-----Urspr?ngliche Nachricht----- >Von: Tutor [mailto:tutor-bounces+n.rautenhaus=gmx.de at python.org] Im Auftrag >von Alan Gauld >Gesendet: Montag, 18. Februar 2013 21:08 >An: tutor at python.org >Betreff: Re: [Tutor] if/else option for making a choice > > >This isn't Python code and nothing like it appears in the code you posted >below. There are several problems with the code above: > >- print does not start with uppercase P. >- You have two (( at the raw_input >- if starts lower case i >- raw_input is a function so you shouldn't compare it to yes >- you don't assign the input value to a variable(although you >? do in the code below so you know you should...) >- you compare to yes but it probably should be "yes" - a string. >- The Print Leather line makes no sense at all. > >If you are going to post code post real code. >Or else make it clear its pseudo code. > >Now on to the code you did post... > >> I hope it is clear where my problem is. > >Not really. >Did you try running it? Did you get an error? >If so what? > >> #Car price calculator >> >> # Set variables for additional items >> Leather = (500) > >Why in ()? you don;t need them > >> int (Leather) > >And this does nothing - its already an int - and you ignore the result. > >> Clima = (1500) >> int (Clima) >> Hifi = (250) >> int (Hifi) >> Electrics = (750) >> int (Electrics) >> Comfort = (2500) >> int (Comfort) > >See above for all of these. > >> print "\t\t\tWelcome to the car price calculator!" >> print "\t\t\tCredits belong to Niclas Rautenhaus" >> print "\n\nPlease enter the basic price: " >> basic = int (raw_input()) > >Now the last line is what your code above should have looked like. > >> # Tax is a percentage of the basic car price Tax = basic * 5 / 100 int >> (Tax) > >The int() gets thrown away but thats probably good because you don't want to >lose the fractional part of the tax value, which is what int() would do. > >> print "\nAdded items:" >> # Here the user should have the possibility to pick either yes or no >> print "\n\nLeather",(Leather) print "Clima",(Clima) print "Hifi", >> (Hifi) print "Electrics", (Electrics) >> print "Comfort", (Comfort) >> print "Tax", (Tax) > >Again you don't need those parentheses > >> # Last step: the picked items shall be summarized print "\n\nTotal >> grand:", basic + Leather + Clima + Hifi \ >>? ? ? ? + Electrics + Comfort + Tax >> >> raw_input ("\nPress the enter key to exit!") > >Personally I'd have split it at the comma: > >print "\n\nTotal grand:", \ >? ? ? ? basic + Leather + Clima + Hifi + Electrics + Comfort + Tax > >But that's a minor quibble. > >Ironically I might also have used parentheses to group the additions, like >so: > >print "\n\nTotal grand:", (basic + Leather + >? ? ? ? ? ? ? ? ? ? ? ? ? ? Clima + Hifi + >? ? ? ? ? ? ? ? ? ? ? ? ? ? Electrics + Comfort + >? ? ? ? ? ? ? ? ? ? ? ? ? ? Tax) > >Or perhaps better still put them in a list and used sum() > >items = [basic, Leather, Clima, Hifi, Electrics, Comfort, Tax] print >"\n\nTotal grand:", sum(items) > >HTH > >-- >Alan G >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > >_______________________________________________ >Tutor maillist? -? Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Tue Feb 19 00:48:08 2013 From: wescpy at gmail.com (wesley chun) Date: Mon, 18 Feb 2013 15:48:08 -0800 Subject: [Tutor] if/else option for making a choice In-Reply-To: <512277d4.68acc20a.6047.5061SMTPIN_ADDED_BROKEN@mx.google.com> References: <512277d4.68acc20a.6047.5061SMTPIN_ADDED_BROKEN@mx.google.com> Message-ID: On Mon, Feb 18, 2013 at 10:22 AM, Niclas Rautenhaus wrote: > Hello folks,**** > > ** ** > > I would be very pleased if someone is able to help me.**** > > I wrote a small programm, to calculate the grand total for a car.**** > > A basic price can be entered. Given that basic price, a tax peercentage is > calculated and added tot he grand total.**** > > > But unfortunately I am stuck with giving the user the choice to select an > additional option! > The extra items have got set values, but at the moment they all get > summarized, but i want to choose. > > ** > greetings Niclas, and welcome to Python! while i'll let the others comment on your code specifically, i can give some overall suggestions/guidance. you're trying to create an overall price calculator correct? while it's straightforward providing a base price, the complexity in your app (and real life) is the set of options that customers can choose from. in your situation, i think it would be more "Pythonic" to maintain the extras as a vector of options and prices. you then loop through those, prompting the user to enter Yes or No, and add either the cost or zero, respectively. that will help keep your code less complex as well. you would just be maintaining a running total until the user is done with all their selections. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Tue Feb 19 01:01:02 2013 From: akleider at sonic.net (akleider at sonic.net) Date: Mon, 18 Feb 2013 16:01:02 -0800 Subject: [Tutor] if/else option for making a choice In-Reply-To: References: <512277d4.68acc20a.6047.5061SMTPIN_ADDED_BROKEN@mx.google.com> Message-ID: > On Mon, Feb 18, 2013 at 10:22 AM, Niclas Rautenhaus > wrote: > >> Hello folks,**** >> >> ** ** >> >> I would be very pleased if someone is able to help me.**** >> >> I wrote a small programm, to calculate the grand total for a car.**** >> >> A basic price can be entered. Given that basic price, a tax peercentage >> is >> calculated and added tot he grand total.**** >> >> >> But unfortunately I am stuck with giving the user the choice to select >> an >> additional option! >> The extra items have got set values, but at the moment they all get >> summarized, but i want to choose. >> >> ** >> > > > greetings Niclas, and welcome to Python! while i'll let the others comment > on your code specifically, i can give some overall suggestions/guidance. > > you're trying to create an overall price calculator correct? while it's > straightforward providing a base price, the complexity in your app (and > real life) is the set of options that customers can choose from. > > in your situation, i think it would be more "Pythonic" to maintain the > extras as a vector of options and prices. you then loop through those, > prompting the user to enter Yes or No, and add either the cost or zero, > respectively. that will help keep your code less complex as well. you > would > just be maintaining a running total until the user is done with all their > selections. > > good luck! > -- wesley I'd be interested in knowing exactly what you mean by the term "vector" in the above discussion. When I saw the problem I thought dict would serve as in options = { "leather" : 1600, "alloy_wheels" : 1200, # and so on } Comments? From wescpy at gmail.com Tue Feb 19 01:34:47 2013 From: wescpy at gmail.com (wesley chun) Date: Mon, 18 Feb 2013 16:34:47 -0800 Subject: [Tutor] if/else option for making a choice In-Reply-To: References: <512277d4.68acc20a.6047.5061SMTPIN_ADDED_BROKEN@mx.google.com> Message-ID: > in your situation, i think it would be more "Pythonic" to maintain the > > extras as a vector of options and prices. you then loop through those, > > prompting the user to enter Yes or No, and add either the cost or zero, > > respectively. that will help keep your code less complex as well. you > > would > > just be maintaining a running total until the user is done with all their > > selections. > > > > good luck! > > -- wesley > > I'd be interested in knowing exactly what you mean by the term "vector" in > the above discussion. When I saw the problem I thought dict would serve > as in > > options = { "leather" : 1600, "alloy_wheels" : 1200, > # and so on > } perfectly fine if order doesn't matter. if it does, then a tuple will serve a similar purposes however, it's easy to move back-n-forth between either via dict(), dict.items(), iter/zip(), etc. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Feb 19 02:10:12 2013 From: davea at davea.name (Dave Angel) Date: Mon, 18 Feb 2013 20:10:12 -0500 Subject: [Tutor] following on In-Reply-To: References: Message-ID: <5122D0F4.5000305@davea.name> On 02/18/2013 02:01 PM, Matthew Ngaha wrote: >>> >> > i sort of heard about a stack its a C/C++ thing i think? > A stack is fundamental to modern programming languages. The only two machines I've used that didn't have a stack implemented at the machine level were the CDC 6000 series, and the IBM 360. Both products of the 60's. Processors like the Intel Pentium series have a stack microcoded into their lowest level instruction set. When the processor itself is calling a subroutine, the current address is pushed onto the stack, and the return instruction pops it back off and jumps there. Other instructions for manipulating it exist at the same level. Typically all local variables in a function are stored in the current stack frame. The stack makes recursive functions practical, at a minimum. Having multiple stacks makes multithreading practical as well. Recursion and multithreading was very tricky on the CDC, since it stored return addresses right into the running code. Usually a programming language will provide a stack-like data structure, for manipulating data that needs similar behavior. -- DaveA From robert.sjoblom at gmail.com Tue Feb 19 02:46:42 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 19 Feb 2013 02:46:42 +0100 Subject: [Tutor] following on In-Reply-To: <5122D0F4.5000305@davea.name> References: <5122D0F4.5000305@davea.name> Message-ID: >> i sort of heard about a stack its a C/C++ thing i think? > > A stack is fundamental to modern programming languages. The only two > machines I've used that didn't have a stack implemented at the machine level > were the CDC 6000 series, and the IBM 360. Both products of the 60's. A while back, while researching something else entirely, I came upon a useful article explaining recursion. In it he briefly touches on how a stack functions, and the explanation is well worth reading (as is the article!). You can find it here: http://inventwithpython.com/blog/2011/08/11/recursion-explained-with-the-flood-fill-algorithm-and-zombies-and-cats/ If you just want to read the stack explanation, scroll down to "Recursion is Just a Fancy Way of Using a Stack" -- best regards, Robert S. From steve at pearwood.info Tue Feb 19 03:15:00 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 19 Feb 2013 13:15:00 +1100 Subject: [Tutor] following on In-Reply-To: References: Message-ID: <5122E024.3080404@pearwood.info> On 19/02/13 06:01, Matthew Ngaha wrote: >>> understanding of how everything works. >> >> Use it., Experiment with it. Break it. >> Thats the best way. Read the source code its all available in >> Python or C. >> > > Hey can you please tell me which source code youre referring too? The > initial files that come with Python? also the C code, where can i > locate this? is C something worth learning? why is Python code > available in C? If you want to learn Python programming, read other Python programs. You will find many Python programs, of greatly variable quality, here: http://code.activestate.com/recipes/langs/python/ You might also like to read this book: http://shop.oreilly.com/product/9780596007973.do You can see the source code used by Python modules by searching for them on your computer, then opening them in a text editor. But beware that you don't accidentally modify them, because you may break your Python installation. Another alternative is to read the source on-line. Many pages in the Python docs link directly to the source code. E.g. this page: http://docs.python.org/2/library/string.html links directly to the source code: http://hg.python.org/cpython/file/2.7/Lib/string.py You can learn a lot from the source code of Python modules. The source code of the Python interpreter, on the other hand, is much, much more complicated. You will probably have a lot of trouble with it, since you are unfamiliar with C, and unfamiliar with the internal C libraries used in the interpreter. But if you are feeling masochistic and want to give it a go, you will find the source code here: http://hg.python.org/cpython Click the "Browse" link to get to the latest version. Many people will advise that learning C is a good idea. I understand their arguments, but as an old curmudgeon I can say I don't like C and I think the world would be much better without it :-) The Python interpreter may be written in many different languages. C is only the most common language. The "Big Four" Python interpreters are written in four different languages: CPython (what you probably think of when you say "Python"): C Jython: Java IronPython: Microsoft .Net CLR PyPy: RPython ("Restricted Python") but there are others: CLPython: Common Lisp Burp and Hope: Haskell Nuitka: C++ Pynie: Parrot Vyper: Ocaml Skulpt: Javascript although some of these may be experimental, obsolete or abandoned. > yes i will try not to reinvent the wheel, a lot of tutorials ive read > seem to always point this out. Just out of curiousity what is a bag, > stack or circular list? what is needed to create something like this? > i sort of heard about a stack its a C/C++ thing i think? You can read about data structures like stack, bag (multiset) and circular list here: http://en.wikipedia.org/wiki/List_of_data_structures -- Steven From chigga101 at gmail.com Tue Feb 19 03:54:29 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 19 Feb 2013 02:54:29 +0000 Subject: [Tutor] following on In-Reply-To: <5122E024.3080404@pearwood.info> References: <5122E024.3080404@pearwood.info> Message-ID: Hey, a Big thanks to everyone that has offered their input. I really appreciate it. Also thanks for all the additional links, i will definately start to read up on data structures , source code and everything else that was suggested From sunil.techspk at gmail.com Tue Feb 19 08:30:40 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Tue, 19 Feb 2013 13:00:40 +0530 Subject: [Tutor] Query String Message-ID: Hi All, I thank you all, for all the responses. & teaching us to learn Python. Here i request, can you tell me what is Query String with some examples? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 19 10:14:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Feb 2013 09:14:45 +0000 Subject: [Tutor] Query String In-Reply-To: References: Message-ID: On 19/02/13 07:30, Sunil Tech wrote: > > Here i request, can you tell me what is Query String with some examples? It depends on the context but I suspect you mean in the context of a web app? In that case a query string is the bit at the end of a URL that includes the search parameters etc. Thus if I do a search on Google for "query string" the url used is: https://www.google.co.uk/#hl=en&sugexp=les%3B&gs_rn=3&gs_ri=psy- ab&tok=XeR8I7yoZ93k_zpsfFWQeg&cp=8&gs_id=i7&xhr=t&q=query+string& es_nrs=true&pf=p&tbo=d&biw=1375&bih=897&sclient=psy-ab&oq=query+st& gs_l=&pbx=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&bvm=bv.42553238,d.d2k& fp=e58955d3a8f3f3a1 And everything after the uk/ is the query string. That particular search brings back lots of links about query strings. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sunil.techspk at gmail.com Tue Feb 19 11:53:37 2013 From: sunil.techspk at gmail.com (Sunil Tech) Date: Tue, 19 Feb 2013 16:23:37 +0530 Subject: [Tutor] Query String In-Reply-To: References: Message-ID: Thank you Alan. On Tue, Feb 19, 2013 at 2:44 PM, Alan Gauld wrote: > On 19/02/13 07:30, Sunil Tech wrote: > >> >> Here i request, can you tell me what is Query String with some examples? >> > > It depends on the context but I suspect you mean in the context of a web > app? In that case a query string is the bit at the end of a URL that > includes the search parameters etc. Thus if I do a search on Google for > "query string" the url used is: > > https://www.google.co.uk/#hl=**en&sugexp=les%3B&gs_rn=3&gs_**ri=psy- > ab&tok=XeR8I7yoZ93k_zpsfFWQeg&**cp=8&gs_id=i7&xhr=t&q=query+**string& > es_nrs=true&pf=p&tbo=d&biw=**1375&bih=897&sclient=psy-ab&**oq=query+st& > gs_l=&pbx=1&bav=on.2,or.r_gc.**r_pw.r_cp.r_qf.&bvm=bv.**42553238,d.d2k& > fp=e58955d3a8f3f3a1 > > And everything after the uk/ is the query string. > > That particular search brings back lots of links about query strings. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Feb 19 12:35:24 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 19 Feb 2013 06:35:24 -0500 Subject: [Tutor] Query String In-Reply-To: References: Message-ID: On Tue, Feb 19, 2013 at 4:14 AM, Alan Gauld wrote: > > https://www.google.co.uk/#hl=en Just to clarify, using a fragment (#) like that isn't a standard query. It's a JavaScript trick for manipulating browser history based on location.hash, so one can do AJAX page refreshes without breaking the back button. You can see the actual query URL ('.../search?hl=en') if you view the background GET (e.g. in the Firefox web console). urlparse.urlsplit parses 'hl=en' as the fragment in this case: >>> urlparse.urlsplit('https://www.google.co.uk/#hl=en') SplitResult(scheme='https', netloc='www.google.co.uk', path='/', query='', fragment='hl=en') From sydney.shall at kcl.ac.uk Tue Feb 19 12:27:43 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Tue, 19 Feb 2013 11:27:43 +0000 Subject: [Tutor] following on In-Reply-To: <5122E024.3080404@pearwood.info> References: <5122E024.3080404@pearwood.info> Message-ID: <512361AF.6010408@kcl.ac.uk> On 19/02/2013 02:15, Steven D'Aprano wrote:hon modules. > > > Many people will advise that learning C is a good idea. I understand > their arguments, but as an old curmudgeon I can say I don't like C and > I think the world would be much better without it :-) > Does this comment extend to C++? :-) Could the experts, please, recommend a beginner's book to learn the principles of good programming? Ta muchly, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From ghasemmg01 at leedslearning.net Tue Feb 19 13:36:55 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Tue, 19 Feb 2013 12:36:55 +0000 Subject: [Tutor] help with storing money variable Message-ID: <010FB2F3C55002408EE1404538D1B6AE034F3C7E126F@LLN-SPP-ES-04.user01.lln.local> Hi guys, Iam halfway through my vending machine program that I started earlier. I ran into a problem. When the user inserts some money, The money variable is not stored for until the user buys an item. So what happens is when the users inserts some coins and then trys to buy an item the money they inserted is not stored till they buy item.Can you tell me how this can be overcome, so that when the user trys to buy an item,the vending machine correctly looks at the amount of money they have and vends the item depending on the amound of money they have. Here is the code: def printMenu(): print ("|__________________________|") print ("|Menu: |") print ("|--------------------------|") print ("| 1. Display all Items |") print ("| 2. Insert 10p |") print ("| 3. Insert 20p |") print ("| 4. Insert 50p |") print ("| 5. Insert ?1 |") print ("| 6. Buy an item |") print ("| 7. Print Current Amount |") print ("| 8. Exit |") print ("|__________________________|") while True: printMenu() choice = input("enter an option from the menu: ") if choice == '1': print("========================================") print(" A B C ") print(" 1.[ Vimtos ] [ Chewits ] [ Mars Bar ]") print(" [ 50p ] [ 40p ] [ 50p ]") print("========================================") print(" 2.[ Doritos ] [ Mentos ]") print(" [ 60p ] [ 50p ]") print("========================================") elif choice == '2': money = 0 number = int(input("how many 10p: ")) money += number * 1/10 print("your newly updated credit is ?" + str(money) + "0") elif choice == '3': money = 0 number2 = int(input("how many 20p: ")) money += number2 * 2/10 print("your newly updated credit is ?" + str(money) + "0") elif choice == '4': money = 0 number3 = int(input("how many 50p: ")) money += number3 * 5/10 print("your newly updated credit is ?" + str(money) + "0") elif choice == '5': money = 0 number4 = int(input("how many ?1: ")) money += number4 * 1 print("your newly updated credit is ?" + str(money)) elif choice == '6': code = input("Enter the code of item you want to buy e.g. for Vimtos = a1: ") money = 0 pricea1 = 0.50 pricea2 = 0.60 priceb1 = 0.40 priceb2 = 0.50 pricec1 = 0.50 if code == 'a1': if money > pricea1: print("you have bought a packet of Vimtos and your newly updated balance is " + str(money - pricea1)) money -= pricea1 else: print("you can't buy that item as your credit is too low") if code == 'a2': if money > pricea2: print("you have bought a packet of Doritos and your newly updated balance is" + str(money - pricea2)) money -= pricea2 else: print("you can't buy that item as your credit is too low") if code == 'b1': if money > priceb1: print("you have bought a packet of Chewits and your newly updated balance is" + str(money - priceb1)) money -= priceb1 else: print("you can't buy that item as your credit is too low") if code == 'b2': if money > priceb2: print("you have bought a packet of Mentos and your newly updated balance is" + str(money - pricea2)) money -= priceb2 else: print("you can't buy that item as your credit is too low") if code == 'c1': if money > pricec1: print("you have bought a Mars Bar and your newly updated balance is" + str(money - pricea2)) money -= priceb2 else: print("you can't buy that item as your credit is too low") From davea at davea.name Tue Feb 19 13:51:28 2013 From: davea at davea.name (Dave Angel) Date: Tue, 19 Feb 2013 07:51:28 -0500 Subject: [Tutor] help with storing money variable In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE034F3C7E126F@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE034F3C7E126F@LLN-SPP-ES-04.user01.lln.local> Message-ID: <51237550.8050001@davea.name> On 02/19/2013 07:36 AM, Ghadir Ghasemi wrote: > Hi guys, Iam halfway through my vending machine program that I started earlier. I ran into a problem. When the user inserts some money, The money variable is not stored for until the user buys an item. So what happens is when the users inserts some coins and then trys to buy an item the money they inserted is not stored till they buy item.Can you tell me how this can be overcome, so that when the user trys to buy an item,the vending machine correctly looks at the amount of money they have and vends the item depending on the amound of money they have. Here is the code: > > > > def printMenu(): > print ("|__________________________|") > print ("|Menu: |") > print ("|--------------------------|") > print ("| 1. Display all Items |") > print ("| 2. Insert 10p |") > print ("| 3. Insert 20p |") > print ("| 4. Insert 50p |") > print ("| 5. Insert ?1 |") > print ("| 6. Buy an item |") > print ("| 7. Print Current Amount |") > print ("| 8. Exit |") > print ("|__________________________|") > > while True: > printMenu() > choice = input("enter an option from the menu: ") > > > > if choice == '1': > print("========================================") > print(" A B C ") > print(" 1.[ Vimtos ] [ Chewits ] [ Mars Bar ]") > print(" [ 50p ] [ 40p ] [ 50p ]") > print("========================================") > print(" 2.[ Doritos ] [ Mentos ]") > print(" [ 60p ] [ 50p ]") > print("========================================") > > > > elif choice == '2': > money = 0 > number = int(input("how many 10p: ")) > money += number * 1/10 > print("your newly updated credit is ?" + str(money) + "0") > > > elif choice == '3': > money = 0 > number2 = int(input("how many 20p: ")) > money += number2 * 2/10 > print("your newly updated credit is ?" + str(money) + "0") > > > elif choice == '4': > money = 0 > number3 = int(input("how many 50p: ")) > money += number3 * 5/10 > print("your newly updated credit is ?" + str(money) + "0") > > > elif choice == '5': > money = 0 > number4 = int(input("how many ?1: ")) > money += number4 * 1 > print("your newly updated credit is ?" + str(money)) > > > > elif choice == '6': > code = input("Enter the code of item you want to buy e.g. for Vimtos = a1: ") > money = 0 > pricea1 = 0.50 > pricea2 = 0.60 > priceb1 = 0.40 > priceb2 = 0.50 > pricec1 = 0.50 > > if code == 'a1': > > if money > pricea1: > print("you have bought a packet of Vimtos and your newly updated balance is " + str(money - pricea1)) > money -= pricea1 > else: > print("you can't buy that item as your credit is too low") > > if code == 'a2': > if money > pricea2: > print("you have bought a packet of Doritos and your newly updated balance is" + str(money - pricea2)) > money -= pricea2 > else: > print("you can't buy that item as your credit is too low") > > if code == 'b1': > if money > priceb1: > print("you have bought a packet of Chewits and your newly updated balance is" + str(money - priceb1)) > money -= priceb1 > else: > print("you can't buy that item as your credit is too low") > > if code == 'b2': > if money > priceb2: > print("you have bought a packet of Mentos and your newly updated balance is" + str(money - pricea2)) > money -= priceb2 > else: > print("you can't buy that item as your credit is too low") > > if code == 'c1': > if money > pricec1: > print("you have bought a Mars Bar and your newly updated balance is" + str(money - pricea2)) > money -= priceb2 > else: > print("you can't buy that item as your credit is too low") How did you conclude that the money they deposit isn't "stored" till they try to buy something? Are you really saying it isn't visible to the user? Could it be because you forgot the elif code == "7" case? (And the "8" one as well.) The other problem I see is that many of those choices zero the value bound to "money". That should be zeroed before the while loop, not inside any place somebody deposits something. -- DaveA From robert.sjoblom at gmail.com Tue Feb 19 14:01:43 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 19 Feb 2013 14:01:43 +0100 Subject: [Tutor] following on In-Reply-To: <512361AF.6010408@kcl.ac.uk> References: <5122E024.3080404@pearwood.info> <512361AF.6010408@kcl.ac.uk> Message-ID: > Could the experts, please, recommend a beginner's book to learn the > principles of good programming? I don't know about expert, but I found the Head First Lab's approach to be really good. The Python book is structured like so: -Lists introduction -(PyPi)/creating modules -- this I hope has been changed in future editions of the book, because PyPi now has a test server for those learning to use it, instead of people uploading to the official PyPi server (if you've ever wondered why there are so many modules for printing lists within lists (nester.py)). -Error handling -Saving data -Work on data -OOP -Web development -Mobile App development -Handling input -Scaling your webapp (which you built in the web development chapter) -Handling complexity Each chapter consists of a challenge that you'll work; the work on data one has a "Coach Kelly" giving you his files on runner times, wanting it formatted. So first you'll learn to read it in, sanitize it and everything, and after that you move on to OOP design, where you create a new class (let's see if I recall it): class Athlete: def __init__(self, name, dob=None, times=[]): self.name = name self.dob = dob self.times = times def add_time(self, time): self.times.append(time) def add_times(self, times): self.times.extend(times) After you've designed the class yourself they go on to mention that instead of building functionality that already exists -- self.times.extend(times) -- it's probably better to create a class that inherits from list, like so: class AthleteList(list): def __init__(self, name, dob=None, times=[]): list.__init__([]) self.name = name self.dob = dob self.extend(times) In each chapter they go through various approaches on things that crop up; for error handling it's the add extra logic/ask forgiveness, for classes it's custom class or inherited class, for saving data it's custom code vs off the shelf solutions, why you want to create functions instead of duplicate code and so on. It's well structured, readable, and have quite enjoyable challenges (compared to the usual "Hello World" approach that many other books do). So yes, they teach you Python, but they also teach you the principles of good programming. I recommend it to anyone who wants to learn Python, but there are probably better books for *specifically* programming principles -- this book is more of a bundled deal. -- best regards, Robert S. From alan.gauld at btinternet.com Tue Feb 19 19:55:23 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Feb 2013 18:55:23 +0000 Subject: [Tutor] Query String In-Reply-To: References: Message-ID: On 19/02/13 11:35, eryksun wrote: > On Tue, Feb 19, 2013 at 4:14 AM, Alan Gauld wrote: >> >> https://www.google.co.uk/#hl=en > > Just to clarify, using a fragment (#) like that isn't a standard > query. Yes I noticed the anomaly but I chose that particular query for a reason :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 19 19:58:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Feb 2013 18:58:56 +0000 Subject: [Tutor] help with storing money variable In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE034F3C7E126F@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE034F3C7E126F@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 19/02/13 12:36, Ghadir Ghasemi wrote: > def printMenu(): > print ("|__________________________|") > print ("| 2. Insert 10p |") > print ("| 3. Insert 20p |") > print ("| 4. Insert 50p |") > print ("|__________________________|") > > while True: > elif choice == '2': > money = 0 > number = int(input("how many 10p: ")) > money += number * 1/10 > elif choice == '3': > money = 0 > number2 = int(input("how many 20p: ")) > money += number2 * 2/10 > elif choice == '4': > money = 0 > number3 = int(input("how many 50p: ")) > money += number3 * 5/10 In each case you start by zeroing money thus losing any credit they had built up. If a real machine did that to me I'd me mighty annoyed. Just a thought... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Feb 19 20:03:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 19 Feb 2013 19:03:06 +0000 Subject: [Tutor] following on In-Reply-To: <512361AF.6010408@kcl.ac.uk> References: <5122E024.3080404@pearwood.info> <512361AF.6010408@kcl.ac.uk> Message-ID: On 19/02/13 11:27, Shall, Sydney wrote: > Could the experts, please, recommend a beginner's book to learn the > principles of good programming? Thats exactly what my book tries to do although it focuses on Python. But its really more about the general principles than learning the idioms of the language. The bad news is that it's now 12 years old and the language has moved on, although most (all?) of the code will still work in Python 2.7. Should be available through your local library or cheap on Amazon marketplace... The good news is that an updated and extended version is on the web (see the.sig) and is free! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dyoo at hashcollision.org Tue Feb 19 22:18:59 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 19 Feb 2013 14:18:59 -0700 Subject: [Tutor] following on In-Reply-To: <512361AF.6010408@kcl.ac.uk> References: <5122E024.3080404@pearwood.info> <512361AF.6010408@kcl.ac.uk> Message-ID: > Does this comment extend to C++? :-) > > Could the experts, please, recommend a beginner's book to learn the > principles of good programming? I'm partial to How to Design Programs as a beginner's textbook: http://www.ccs.neu.edu/home/matthias/HtDP2e/ because it emphasizes a systematic approach to designing programs. Basically, it's a Polya's "How to Solve It" for programmers, with an expanded treatment on how data structures inform the shape of the functions that work on that data. From fomcl at yahoo.com Wed Feb 20 11:53:58 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 20 Feb 2013 02:53:58 -0800 (PST) Subject: [Tutor] locale.set/getlocale asymmetry Message-ID: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> Hi, ? There?is an?asymmetry in getlocale and setlocale. What is returned by getlocale cannot be used as argument for setlocale. It is important to mention that this is on Windows 7.? Setlocale appears to use a Linux/Posix locale specification (yaay, harmony!), but, disappointingly, getlocale still returns the windows-specific locale specification.?Why is this? Is this some historical anomaly? ? Background: I occasionally need to use a french locale because that locale uses a space as a thousand separator. So I'd like to temporarily change that,?then fire up Excel, which hopefully ensures the numbers are displayed as desired. ? #Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32 >>> import platform >>> platform.platform()? 'Windows-7-6.1.7601-SP1' >>> import locale >>> locale.getlocale() ('Dutch_Netherlands', '1252') >>> locale.setlocale(locale.LC_ALL, "French_France") 'French_France.1252'>>> locale.getlocale() ('fr_FR', 'cp1252') >>> locale.setlocale(locale.LC_ALL, ('fr_FR', 'cp1252')) Traceback (most recent call last): ? File "", line 1, in ??? locale.setlocale(locale.LC_ALL, ('fr_FR', 'cp1252')) ? File "C:\Python27\lib\locale.py", line 531, in setlocale ??? return _setlocale(category, locale) Error: unsupported locale setting Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?? From fomcl at yahoo.com Wed Feb 20 11:55:59 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 20 Feb 2013 02:55:59 -0800 (PST) Subject: [Tutor] Python needs your help -- trademark under attack --> PUT THIS ON FB, LINKEDIN!! References: <511D5E02.7090105@pearwood.info> Message-ID: <1361357759.40683.YahooMailNeo@web163804.mail.gq1.yahoo.com> > The Python Software Foundation is the organisation which protects and manages > the "boring" bits of keeping a big open source project alive: the > legal and contractual parts, funding for projects, trademarks and copyrights. > > If you are based in Europe, or know somebody who uses Python in Europe, the PSF > needs your help. > > There is a company in the UK who has applied to trademark the name > "Python" and are claiming the *exclusive* right to use the word > "Python" for software, servers, and web services over the entire > European Union. > > You can read more about this here: > > http://pyfound.blogspot.com/2013/02/python-trademark-at-risk-in-europe-we.html > > If you have documentation of European user groups, trade associations, books, > conferences, scans of job advertisements for Python programmers, software that > uses some variation of "Python" in the name, etc. your evidence will > be helpful in defeating this attempted grab of the Python name. > > You can also testify to the fact that when you read or hear of the name > "Python" in relation to computers and the Internet, you think of > Python the programming language. Thanks for posting this. \$@#@, first the attack on PyPi, now this! Would also be good to disseminate this message through Facebook, LinkedIn etc. I'll try and get a letter from my company. This sucks. ? Albert-Jan From eryksun at gmail.com Wed Feb 20 13:37:14 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 20 Feb 2013 07:37:14 -0500 Subject: [Tutor] locale.set/getlocale asymmetry In-Reply-To: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> References: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: On Wed, Feb 20, 2013 at 5:53 AM, Albert-Jan Roskam wrote: > There is an asymmetry in getlocale and setlocale. What is returned by > getlocale cannot be used as argument for setlocale. getlocale executes localename = _setlocale(category), where _setlocale wraps the C runtime setlocale. Then it transforms the return string to a tuple using _parse_localename, which calls locale.normalize. The latter changes the language and encoding incorrectly on Windows. Instead, you could save the unparsed locale string: old_locale = setlocale(LC_ALL). From fomcl at yahoo.com Wed Feb 20 14:14:15 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 20 Feb 2013 05:14:15 -0800 (PST) Subject: [Tutor] locale.set/getlocale asymmetry In-Reply-To: References: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: <1361366055.28245.YahooMailNeo@web163801.mail.gq1.yahoo.com> ----- Original Message ----- > From: eryksun > To: Albert-Jan Roskam > Cc: Python Mailing List > Sent: Wednesday, February 20, 2013 1:37 PM > Subject: Re: [Tutor] locale.set/getlocale asymmetry > > On Wed, Feb 20, 2013 at 5:53 AM, Albert-Jan Roskam > wrote: >> There is an asymmetry in getlocale and setlocale. What is returned by >> getlocale cannot be used as argument for setlocale. > > getlocale executes localename = _setlocale(category), where _setlocale > wraps the C runtime setlocale. Then it transforms the return string to > a tuple using _parse_localename, which calls locale.normalize. The > latter changes the language and encoding incorrectly on Windows. > Instead, you could save the unparsed locale string: old_locale = > setlocale(LC_ALL). Hi Eryksun, Thank you. So can I simply use the function below to replace locale.getlocale()? Will this never cause problems? The thing I remember about setlocale is that "thou shalt never call setlocale anywhere else but in the beginning of a script". Or am I wrong here? I am always a little reluctant to mess with the host locale. ? def getlocale(category=locale.LC_ALL): ?? ?return locale.setlocale(category) From eryksun at gmail.com Wed Feb 20 17:16:17 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 20 Feb 2013 11:16:17 -0500 Subject: [Tutor] locale.set/getlocale asymmetry In-Reply-To: <1361366055.28245.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> <1361366055.28245.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Wed, Feb 20, 2013 at 8:14 AM, Albert-Jan Roskam wrote: > Thank you. So can I simply use the function below to replace locale.getlocale()? > Will this never cause problems? The thing I remember about setlocale is that > "thou shalt never call setlocale anywhere else but in the beginning of a script". > Or am I wrong here? I am always a little reluctant to mess with the host locale. > > def getlocale(category=locale.LC_ALL): > return locale.setlocale(category) That's fine. If you only pass in the category it's just a query. locale.getlocale defaults to a single category (LC_CTYPE) because of the parsing it does to create the tuple. The issue is that an LC_ALL query returns all of the categories, delimited by semicolons, if they're not all the same. In this case locale.getlocale(LC_ALL) raises a TypeError. But there's no problem using such a locale string with setlocale LC_ALL. Also, on Windows locale.getdefaultlocale uses win32 GetLocaleInfo, set to return ISO 639/3166 language/country codes. These codes don't work with the MS CRT setlocale, so locale.resetlocale fails. setlocale(LC_ALL, '') is supported to reset to the default. More here: setlocale http://msdn.microsoft.com/en-us/library/x99tb11d language strings http://msdn.microsoft.com/en-us/library/39cwe7zf country/region strings http://msdn.microsoft.com/en-us/library/cdax410z From fomcl at yahoo.com Wed Feb 20 21:56:36 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 20 Feb 2013 12:56:36 -0800 (PST) Subject: [Tutor] locale.set/getlocale asymmetry In-Reply-To: References: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> <1361366055.28245.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <1361393796.15604.YahooMailNeo@web163806.mail.gq1.yahoo.com> > locale.getlocale defaults to a single category (LC_CTYPE) because of > the parsing it does to create the tuple. The issue is that an LC_ALL > query returns all of the categories, delimited by semicolons, if > they're not all the same. In this case locale.getlocale(LC_ALL) raises > a TypeError. But there's no problem using such a locale string with > setlocale LC_ALL. > > Also, on Windows locale.getdefaultlocale uses win32 GetLocaleInfo, set > to return ISO 639/3166 language/country codes. These codes don't work > with the MS CRT setlocale, so locale.resetlocale fails. > setlocale(LC_ALL, '') is supported to reset to the default. More here: Ah, I always wondered about that. So getdefaultlocale() always returns the same as getlocale() on Linux? Python 2.7.3 (default, Sep 26 2012, 21:53:58) [GCC 4.7.2] on linux2 >>> import locale >>> locale.getdefaultlocale() ('en_US', 'UTF-8') >>> locale.getlocale() ('en_US', 'UTF-8') ? > setlocale > http://msdn.microsoft.com/en-us/library/x99tb11d > > language strings > http://msdn.microsoft.com/en-us/library/39cwe7zf > > country/region strings > http://msdn.microsoft.com/en-us/library/cdax410z > This article [http://docs.moodle.org/dev/Table_of_locales]? specifies locales for windows (column: localewin) and other OS. While this Unix article [http://osr507doc.sco.com/en/man/html.M/locale.M.html] has a table with old and new locale names (e.g. old Unix: english_uk.8859; new Unix: en_GB.ISO8859-1). And this Windows list is just like Unix [http://msdn.microsoft.com/en-us/library/39cwe7zf] So basically, the locale specification may differ: [A] between OS families (Unix, Windows, ...) [B] between OS versions (Windows XP, Windows 7, ...)? Woaaah, that's confusing! ISO, SIL, and IETF/BCP language codes...a dash of IANA. And the same variation for codepage defintions? These guys in Switzerland should put the 'S' back in ISO! ;-) One additional question: when is it REALLY necessary to specify a locale variant modifier, e.g. en_US.cp1252 at euro, or perhaps the more eccentric nl_NL.cp874 at preeuro (dutch locale, thai/latin codepage ;-) From eryksun at gmail.com Thu Feb 21 07:33:14 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 21 Feb 2013 01:33:14 -0500 Subject: [Tutor] locale.set/getlocale asymmetry In-Reply-To: <1361393796.15604.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1361357638.4236.YahooMailNeo@web163802.mail.gq1.yahoo.com> <1361366055.28245.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1361393796.15604.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Wed, Feb 20, 2013 at 3:56 PM, Albert-Jan Roskam wrote: > Ah, I always wondered about that. So getdefaultlocale() always returns > the same as getlocale() on Linux? On Linux, getdefaultlocale looks for the locale name in environment variables (LC_ALL, LC_CTYPE, LANG, and LANGUAGE), with a default of 'C', and parses the name with _parse_localename. It can't use setlocale(LC_ALL, '') because that would actually set the default state. getlocale() returns the parsed locale for the current LC_CTYPE config, not the system default locale. > So basically, the locale specification may differ: > [A] between OS families (Unix, Windows, ...) > [B] between OS versions (Windows XP, Windows 7, ...)? For a GUI application, your toolkit may have tools to abstract away platform details. For example Qt QLocale: >>> # set API v1 QString for this example ... import sip; sip.setapi('QString', 1) >>> from PyQt4.QtCore import QLocale, QString >>> QLocale.setDefault(QLocale('nl_NL')) >>> QString('1234,56').toDouble() (1234.56, True) > One additional question: when is it REALLY necessary to specify a > locale variant modifier, e.g. en_US.cp1252 at euro, or perhaps the > more eccentric nl_NL.cp874 at preeuro (dutch locale, thai/latin codepage ;-) It's for clowns like me to do this: >>> setlocale(LC_ALL, 'en_US.UTF-8 at yadnom') 'en_US.UTF-8 at yadnom' >>> calendar.day_name[0] 'yadnoM' >>> calendar.day_abbr[0] 'noM' On Debian Linux, I copied the original en_US to /usr/local/share/i18n/locales/en_US at yadnom, modified the LC_TIME config, updated /etc/locale.gen, and ran the locale-gen script to update /usr/lib/locale/locale-archive. More seriously, a system administrator may have a good reason to create a modified locale for LC_MESSAGES, etc, so I guess you should ask sys admins if/how they use this. From schooluse1992 at yahoo.com Thu Feb 21 13:16:33 2013 From: schooluse1992 at yahoo.com (Mara Kelly) Date: Thu, 21 Feb 2013 12:16:33 +0000 (GMT) Subject: [Tutor] distance between cities matrix Message-ID: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> Hi everyone,?Here is the question I was given...Consider the (20x20) array of numbers?here(I wrote all of the numbers in my program). Lets say this represents a matrix A of distances (in kilometers) between cities. Note that A is symmetric A(i,j) = A(j,i) and all its diagonal elements are zero. Suppose Vladimir from city i and Petra from city j want to meet up in some third city k (i, j and k are all different). Conscious about their carbon footprint (!), they want k to be as near as possible: specifically the sum of the distances both has to travel should be minimum. Given i and j, write a program in PYTHON that determines what k should be. (In PYTHON you can store the matrix as a list of lists). Do not worry in your program about "reading in" A: Just hard-wire it in to the code. You should read in from the user the two cities (i and j) where Vladimir and Petra live. From your program, calculate the answer for1) i=5, j=112)i=10, j=13 I think my program is correct, but I'm not sure what they want us to do with the two conditions given above. I also don't know what to enter when I run the program to test these. I am working in Python 3. Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: 20x20matrix Type: application/octet-stream Size: 3563 bytes Desc: not available URL: From alan.gauld at btinternet.com Thu Feb 21 16:10:46 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Feb 2013 15:10:46 +0000 Subject: [Tutor] distance between cities matrix In-Reply-To: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> References: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> Message-ID: On 21/02/13 12:16, Mara Kelly wrote: > Consider the (20x20) array of numbers here > matrix A of distances (in kilometers) between cities. Note that A is > symmetric A(i,j) = A(j,i) and all its diagonal elements are zero. > Suppose Vladimir from city i and Petra from city j want to meet up in > some third city k (i, j and k are all different). Conscious about their > carbon footprint (!), they want k to be as near as possible: > specifically the sum of the distances both has to travel should be > minimum. So you can extract a list of distances for i and another for j. You then want to find the smallest pair of values in those lists. Here is a smaller example: i = [2,4,6] j = [3,2,1] the pairs are (2,3), (4,2), (6,1) The sums of pairs are therefore: 5, 6, 7 So the smallest pair is the first one. So which ever city the first one represents is the city where they should meet. > where Vladimir and Petra live. From your program, calculate the answer for > > 1) i=5, j=11 > 2)i=10, j=13 > > > I think my program is correct, but I'm not sure what they want us to do > with the two conditions given above. You plug those into your program as the values for the two start cities. So you should wind up with two answers. > I also don't know what to enter > when I run the program to test these. You enter (depending on how you code it) either the city names corresponding to this numbers in your matrix or you enter in the numbers directly (if you used a numbered menu, say). HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Thu Feb 21 16:42:24 2013 From: davea at davea.name (Dave Angel) Date: Thu, 21 Feb 2013 10:42:24 -0500 Subject: [Tutor] distance between cities matrix In-Reply-To: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> References: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> Message-ID: <51264060.7090900@davea.name> On 02/21/2013 07:16 AM, Mara Kelly wrote: > Hi everyone, Here is the question I was given...Consider the (20x20) array of numbers here(I wrote all of the numbers in my program). Lets say this represents a matrix A of distances (in kilometers) between cities. Note that A is symmetric A(i,j) = A(j,i) and all its diagonal elements are zero. Suppose Vladimir from city i and Petra from city j want to meet up in some third city k (i, j and k are all different). Conscious about their carbon footprint (!), they want k to be as near as possible: specifically the sum of the distances both has to travel should be minimum. Given i and j, write a program in PYTHON that determines what k should be. (In PYTHON you can store the matrix as a list of lists). Do not worry in your program about "reading in" A: Just hard-wire it in to the code. You should read in from the user the two cities (i and j) where Vladimir and Petra live. From your program, calculate the answer for1) i=5, j=112)i=10, j=13 > I think my program is correct, but I'm not sure what they want us to do with the two conditions given above. I also don't know what to enter when I run the program to test these. I am working in Python 3. Thank you! > This is a text mailing list. By posting as html, you made it pretty difficult to make sense out of those two long paragraphs. Please send your emails as text. I don't know what two particular conditions you're asking about. Could you be explicit, instead of just saying 'given above" ? Lots of conditions were given above. Some comments on your code: It's customary to name the file with an extension of .py As written, the code doesn't do anything. You define two functions, but never call them. At a minimum, you need to use input() to get two number strings from the user, and int() to convert each to an integer. Then you need to call the distance() function with those two numbers. Then you need to test it once by having the user input the numbers 5,112 and again with 10, 13. The first case will get an exception of course, since there aren't 112 cities. > #Python Program to calculate the city equidistant between two given cities That's not what was in the assignment, nor is it what you did. > #Sort the cities by arranging the distances from greatest to least I think you're actually sorting from least to greatest, which is fine. But if so, the comment is wrong. > #Range is a pre defined 20 by 20 matrix No, range(0,20) builds a 1 by 20 list, not any kind of matrix. perhaps you meant to refer to cities, which you are building here. > #For entry within the matrix if that value happens to be of type list, then it will append a value to that list If you're referring to the cities matrix, all the values are of type list, so I'm not sure what you're trying to say here. > for b in cities[i]: > for c in cities[j]: > sums.append(b+c) No idea what this is supposed to accomplish. But the code works better without it. > sums[i] = 0 > sums[j] = 0 By zeroing them, you make them the minimum distance. Instead you might want to make them very large. I used a million, and that worked. It's not at all clear to me what the numbers in the original matrix represented, since if they were really the tallying of the shortest route between each pair of cities, then the answer would already be a direct lookup (cities[i][j]). But if it's the shortest distance between two cities that doesn't go near any other city, then this program is set up to calculate the shortest route that goes through exactly one intermediate city (the 'k' city). It still is not necessarily the shortest route that might go through several intermediates. -- DaveA From dyoo at hashcollision.org Thu Feb 21 22:06:31 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 21 Feb 2013 14:06:31 -0700 Subject: [Tutor] distance between cities matrix In-Reply-To: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> References: <1361448993.30483.YahooMailClassic@web171605.mail.ir2.yahoo.com> Message-ID: > Consider the (20x20) array of numbers here(I wrote all of the numbers in > my program). Lets say this represents a matrix A of distances (in > kilometers) between cities. Note that A is symmetric A(i,j) = A(j,i) and all > its diagonal elements are zero. Suppose Vladimir from city i and Petra from > city j want to meet up in some third city k (i, j and k are all different). > Conscious about their carbon footprint (!), they want k to be as near as > possible: specifically the sum of the distances both has to travel should be > minimum. Given i and j, write a program in PYTHON that determines what k > should be. This sounds like a fairly straightforward CS graph algorithms question. Is there a unique meeting point k that satisfies these conditions, or can there be several possibilities? How is this problem different from a standard shortest-path search? Ah, I think I see it. I'm assuming the difference is that it's in the shape of the legal solutions. Solutions must be in the form of only two direct hops: from i to k, and from k to j and not some path of arbitrary length. You ask the question: how do I test this? Here's one approach: create your own simple distance matrix for a very small map that you construct. Make your own test data. Have it have four cities (or fewer!). That way, you can know in advance what the answer is supposed to be for any two pairs. Then you can write test cases and see that your algorithm is doing what you expect it to. From michael at seomoz.org Fri Feb 22 02:22:19 2013 From: michael at seomoz.org (Michael O'Leary) Date: Thu, 21 Feb 2013 17:22:19 -0800 Subject: [Tutor] Setting log directory from a command line argument Message-ID: I have added logging to a Python program I have been working on by putting this in the module's __init__.py file: ########## import logging logger = logging.getLogger('ranking_factors') formatter = logging.Formatter('[%(asctime)s] %(levelname)s in %(module)s:%(funcName)s@%(lineno)s => %(message)s') handler = logging.FileHandler('ranking_factors.log') handler.setLevel(logging.DEBUG) handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.INFO) ########## I would like to provide a way for different users to specify the directory where the log files are written, and perhaps also the log file names, through command line arguments. Is there a way that I can do that? I can access the logger variable in the files of the application with from . import logger logger.info("Some message") Could I import logger in the file where the command line arguments are processed and change its handler to use a different filename? If I can do that, will that change logger globally, so that logging statements in other files of the application also write logging to the new file location? If this wouldn't work, is there a different way that I could accomplish this task? Thanks, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Fri Feb 22 02:47:21 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Thu, 21 Feb 2013 19:47:21 -0600 Subject: [Tutor] sqlite3 does it support limit in a delete clause? Message-ID: ubuntu 12.04 python 2.7 Does sqlite3 in this version of python support a delete with a limit? >>> cur.execute("delete from pwds where Account='xMe' limit 1") Traceback (most recent call last): File "", line 1, in sqlite3.OperationalError: near "limit": syntax error >>> >>> cur.execute("delete from pwds where Account='xMe' limit=1") Traceback (most recent call last): File "", line 1, in sqlite3.OperationalError: near "limit": syntax error >>> It seems not, but it may be me messing up the syntax so I thought I would check. Thanks, Jim From eryksun at gmail.com Fri Feb 22 04:41:32 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 21 Feb 2013 22:41:32 -0500 Subject: [Tutor] sqlite3 does it support limit in a delete clause? In-Reply-To: References: Message-ID: On Thu, Feb 21, 2013 at 8:47 PM, Jim Byrnes wrote: > ubuntu 12.04 python 2.7 > > Does sqlite3 in this version of python support a delete with a limit? It's enabled via the compilation option SQLITE_ENABLE_UPDATE_DELETE_LIMIT: http://www.sqlite.org/compile.html/#enable_update_delete_limit This is not enabled for Windows Python 2.7/3.3. However, I'm surprised it's disabled in Ubuntu since Debian's Python 2.7.3 has it. I checked this with a temp database in memory and also verified via the diagnostic functions (themselves optional): http://www.sqlite.org/c3ref/compileoption_get.html >>> from ctypes import * >>> import _sqlite3 >>> lib = CDLL(_sqlite3.__file__) >>> lib.sqlite3_compileoption_used( ... "ENABLE_UPDATE_DELETE_LIMIT") 1 >>> lib.sqlite3_compileoption_get.restype = c_char_p >>> i = 0 >>> while True: ... opt = lib.sqlite3_compileoption_get(i) ... if not opt: break ... print opt ... i += 1 ... CURDIR ENABLE_COLUMN_METADATA ENABLE_FTS3 ENABLE_RTREE ENABLE_UNLOCK_NOTIFY ENABLE_UPDATE_DELETE_LIMIT MAX_SCHEMA_RETRY=25 OMIT_LOOKASIDE SECURE_DELETE SOUNDEX TEMP_STORE=1 THREADSAFE=1 From eryksun at gmail.com Fri Feb 22 05:26:52 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 21 Feb 2013 23:26:52 -0500 Subject: [Tutor] sqlite3 does it support limit in a delete clause? In-Reply-To: References: Message-ID: On Thu, Feb 21, 2013 at 10:41 PM, eryksun wrote: > >>> from ctypes import * > >>> import _sqlite3 > >>> lib = CDLL(_sqlite3.__file__) > > >>> lib.sqlite3_compileoption_used( > ... "ENABLE_UPDATE_DELETE_LIMIT") > 1 A simpler way using a SQL function: http://www.sqlite.org/lang_corefunc.html#sqlite_compileoption_used Windows, Python 2.7.3: >>> cur.execute(''' ... select sqlite_compileoption_used( ... 'ENABLE_UPDATE_DELETE_LIMIT')''').fetchone() (0,) Debian, Python 2.7.3: >>> cur.execute(''' ... select sqlite_compileoption_used( ... 'ENABLE_UPDATE_DELETE_LIMIT')''').fetchone() (1,) From eryksun at gmail.com Fri Feb 22 06:10:52 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 22 Feb 2013 00:10:52 -0500 Subject: [Tutor] sqlite3 does it support limit in a delete clause? In-Reply-To: References: Message-ID: On Thu, Feb 21, 2013 at 8:47 PM, Jim Byrnes wrote: > >>>> cur.execute("delete from pwds where Account='xMe' limit 1") If you need a alternate way to limit the delete, try the following, for which the limit is on a select query: cur.execute(''' delete from pwds where rowid in ( select rowid from pwds where Account='xMe' limit 1) ''') From eryksun at gmail.com Fri Feb 22 10:33:10 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 22 Feb 2013 04:33:10 -0500 Subject: [Tutor] sqlite3 does it support limit in a delete clause? In-Reply-To: References: Message-ID: On Thu, Feb 21, 2013 at 10:41 PM, eryksun wrote: > However, I'm surprised it's disabled in Ubuntu since Debian's > Python 2.7.3 has it. I took a moment to look at the changelogs. The option to use LIMIT with DELETE was added in SQLite 3.6.4 (Oct 2008): http://www.sqlite.org/changes.html#version_3_6_4 * Add option support for LIMIT and ORDER BY clauses on DELETE and UPDATE statements. Only works if SQLite is compiled with SQLITE_ENABLE_UPDATE_DELETE_LIMIT. Windows Python 2.7.3 ships with SQLite version 3.6.21 (Dec 2009). Windows Python 3.3 uses version 3.7.12 (May 2012), but it isn't compiled with the above option. Ubuntu 12.04 uses version 3.7.9 (Nov 2011) of the libsqlite3-0 package. However, it wasn't compiled with the needed option until package version 3.7.9-3 (Jan 2012): http://changelogs.ubuntu.com/changelogs/pool/main/s/sqlite3/sqlite3_3.7.13-1/changelog * Enable LIMIT support for UPDATE and DELETE commands (closes: #649169). Ubuntu 12.10 (quantal) uses version 3.7.13 (Jun 2012), the same version I have on Debian Wheezy. http://packages.debian.org/changelogs/pool/main/s/sqlite3/sqlite3_3.7.13-1/changelog From jf_byrnes at comcast.net Fri Feb 22 15:57:48 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 22 Feb 2013 08:57:48 -0600 Subject: [Tutor] sqlite3 does it support limit in a delete clause? In-Reply-To: References: Message-ID: On 02/21/2013 11:10 PM, eryksun wrote: > On Thu, Feb 21, 2013 at 8:47 PM, Jim Byrnes wrote: >> >>>>> cur.execute("delete from pwds where Account='xMe' limit 1") > > If you need a alternate way to limit the delete, try the following, > for which the limit is on a select query: > > cur.execute(''' > delete from pwds where rowid in ( > select rowid from pwds where Account='xMe' limit 1) > ''') Thanks for all the info. I ran your tests and my version of sqlite3 is indeed not compiled to use LIMIT. After I sent the email I was wondering about using rowid. Thanks for confirming it with an example. Regards, Jim From jf_byrnes at comcast.net Fri Feb 22 22:26:39 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 22 Feb 2013 15:26:39 -0600 Subject: [Tutor] How to break long lines? Message-ID: I am cleaning up my code and have a number of sqlite3 execute statements that extend far past 80 characters. From my reading implicit line joining with (), [] or {} seems to be the preferred method, but cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE', cat) gives this error: jfb at jims1204:~/MyProgs/passwords\$ python passwords.py File "passwords.py", line 50 cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account ^ SyntaxError: EOL while scanning string literal Using a \ seems to be out of favor but it works in this case. cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account\ COLLATE NOCASE', cat) # no error. What am I not understanding about implicit line joining? Thanks, Jim From msirenef at lightbird.net Fri Feb 22 22:51:19 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 22 Feb 2013 16:51:19 -0500 Subject: [Tutor] How to break long lines? In-Reply-To: References: Message-ID: <5127E857.5080608@lightbird.net> On 02/22/2013 04:26 PM, Jim Byrnes wrote: > I am cleaning up my code and have a number of sqlite3 execute statements that extend far past 80 characters. > > From my reading implicit line joining with (), [] or {} seems to be the preferred method, but > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > COLLATE NOCASE', cat) > > gives this error: > > jfb at jims1204:~/MyProgs/passwords\$ python passwords.py > File "passwords.py", line 50 > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > ^ > SyntaxError: EOL while scanning string literal > > Using a \ seems to be out of favor but it works in this case. > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account\ > COLLATE NOCASE', cat) > # no error. > > What am I not understanding about implicit line joining? > > Thanks, Jim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > There are a few ways: "abc \ xyz" ("abc " \ "xyz") ("abc " "xyz") The last ones work because two string literals next to each other are combined: 'abc' 'xyz' == 'abcxyz' -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ The press, the machine, the railway, the telegraph are premises whose thousand-year conclusion no one has yet dared to draw. Friedrich Nietzsche From malaclypse2 at gmail.com Fri Feb 22 22:59:00 2013 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 22 Feb 2013 16:59:00 -0500 Subject: [Tutor] How to break long lines? In-Reply-To: References: Message-ID: On Fri, Feb 22, 2013 at 4:26 PM, Jim Byrnes wrote: > I am cleaning up my code and have a number of sqlite3 execute statements > that extend far past 80 characters. > > From my reading implicit line joining with (), [] or {} seems to be the > preferred method, but > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > COLLATE NOCASE', cat) > > gives this error: > > jfb at jims1204:~/MyProgs/passwords\$ python passwords.py > File "passwords.py", line 50 > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > ^ > SyntaxError: EOL while scanning string literal Single quoted strings aren't allowed to have line breaks in them. If you have two string literals separated only by whitespace, though, they get joined together, so you could do this: cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account' 'COLLATE NOCASE', cat) You can also use triple quoted strings instead, which is my preference. Triple quoted strings are allowed to have line breaks, and the whitespace doesn't matter in your SQL query. So I'd do something like this: cur.execute ('''select account from pwds where category = ? order by account collate nocase''', cat) You can break the query up over however many lines it needs to be readable, of course. -- Jerry From ramit.prasad at jpmorgan.com Fri Feb 22 22:54:47 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 22 Feb 2013 21:54:47 +0000 Subject: [Tutor] How to break long lines? In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474181B84D8@SCACMX008.exchad.jpmchase.net> Jim Byrnes wrote: > I am cleaning up my code and have a number of sqlite3 execute statements > that extend far past 80 characters. > > From my reading implicit line joining with (), [] or {} seems to be the > preferred method, but > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > COLLATE NOCASE', cat) > > gives this error: > > jfb at jims1204:~/MyProgs/passwords\$ python passwords.py > File "passwords.py", line 50 > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > ^ > SyntaxError: EOL while scanning string literal > > Using a \ seems to be out of favor but it works in this case. > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account\ > COLLATE NOCASE', cat) > # no error. > > What am I not understanding about implicit line joining? The problem is the line break. Single delimited (quote or double quote) strings can only stay on one line (unless using the \ hack). You can easily solve this problem in your case by using triple delimited strings. cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', cat) ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From jf_byrnes at comcast.net Fri Feb 22 23:54:59 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 22 Feb 2013 16:54:59 -0600 Subject: [Tutor] How to break long lines? In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474181B84D8@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474181B84D8@SCACMX008.exchad.jpmchase.net> Message-ID: On 02/22/2013 03:54 PM, Prasad, Ramit wrote: > Jim Byrnes wrote: >> I am cleaning up my code and have a number of sqlite3 execute statements >> that extend far past 80 characters. >> >> From my reading implicit line joining with (), [] or {} seems to be the >> preferred method, but >> >> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account >> COLLATE NOCASE', cat) >> >> gives this error: >> >> jfb at jims1204:~/MyProgs/passwords\$ python passwords.py >> File "passwords.py", line 50 >> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account >> ^ >> SyntaxError: EOL while scanning string literal >> >> Using a \ seems to be out of favor but it works in this case. >> >> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account\ >> COLLATE NOCASE', cat) >> # no error. >> >> What am I not understanding about implicit line joining? > > The problem is the line break. Single delimited (quote or double quote) strings > can only stay on one line (unless using the \ hack). You can easily solve this > problem in your case by using triple delimited strings. > > cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account > COLLATE NOCASE''', cat) > > > ~Ramit > So it was the quotes that tripped me up. The triple quoted ones worked great. Thanks, Jim From jf_byrnes at comcast.net Fri Feb 22 23:57:49 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 22 Feb 2013 16:57:49 -0600 Subject: [Tutor] How to break long lines? In-Reply-To: References: Message-ID: On 02/22/2013 03:59 PM, Jerry Hill wrote: > On Fri, Feb 22, 2013 at 4:26 PM, Jim Byrnes wrote: >> I am cleaning up my code and have a number of sqlite3 execute statements >> that extend far past 80 characters. >> >> From my reading implicit line joining with (), [] or {} seems to be the >> preferred method, but >> >> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account >> COLLATE NOCASE', cat) >> >> gives this error: >> >> jfb at jims1204:~/MyProgs/passwords\$ python passwords.py >> File "passwords.py", line 50 >> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account >> ^ >> SyntaxError: EOL while scanning string literal > > Single quoted strings aren't allowed to have line breaks in them. If > you have two string literals separated only by whitespace, though, > they get joined together, so you could do this: > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account' > 'COLLATE NOCASE', cat) > > You can also use triple quoted strings instead, which is my > preference. Triple quoted strings are allowed to have line breaks, > and the whitespace doesn't matter in your SQL query. So I'd do > something like this: > > cur.execute ('''select account > from pwds > where category = ? > order by account > collate nocase''', cat) > > You can break the query up over however many lines it needs to be > readable, of course. > Thanks, the triple quoted method worked great. I guess I always think of them in terms of docstrings or comments not in this way. Regards, Jim From steve at pearwood.info Sat Feb 23 00:46:28 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Feb 2013 10:46:28 +1100 Subject: [Tutor] How to break long lines? In-Reply-To: References: Message-ID: <51280354.5000909@pearwood.info> On 23/02/13 08:26, Jim Byrnes wrote: > I am cleaning up my code and have a number of sqlite3 execute statements > that extend far past 80 characters. > > From my reading implicit line joining with (), [] or {} seems to be the > preferred method, but > > cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY Account > COLLATE NOCASE', cat) > > gives this error: [...] > SyntaxError: EOL while scanning string literal Single quote strings are limited to a single line, regardless of any brackets (round, square or curly) around them. In this case, the round brackets simply allow the arguments to cur.execute() to extend over multiple lines, but each argument still has to obey the syntax rules. You can't expect this to work: func(12345 67890) # ten digit number just because of the parentheses. Neither do single-quote strings suddenly gain the power to extend past the end of line. But what you can do is use a line continuation \ as you have seen. Or you can use a little-known feature of Python, implicit string concatenation. The Python compiler will automatically concatenate strings at compile-time: s = "spam " 'ham ' 'eggs' is a more-verbose way of writing: s = "spam ham eggs" Now obviously this example here is useless, but when combined with parentheses, you get a powerful way of writing long strings: cur.execute('SELECT Account FROM pwds' ' WHERE Category=?' ' ORDER BY Account' ' COLLATE NOCASE', cat) which I think is really nice to read. The best part is, because these are string literals, the language promises to concatenate them at compile-time, not runtime. If implicit concatenation is too magical for you, you can use explicit concatenation: cur.execute('SELECT Account FROM pwds' + ' WHERE Category=?' + ' ORDER BY Account' + ' COLLATE NOCASE', cat) At worst, the string concatenation + operator will apply at runtime, which for a short string like this is not a big deal. But in practice, I would expect Python's "keyhole optimizer" to see that it is only string literals being concatenated, and perform constant-folding at compile-time. (Note: constant-folding is not a promise of the language. Not all Python versions or implementations will do this.) A fourth option is to use triple-quoted strings: cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY Account COLLATE NOCASE''', cat) but this relies on your SQL database being happy to receive commands with embedded newlines, which it may not be. -- Steven From neubyr at gmail.com Sat Feb 23 00:50:06 2013 From: neubyr at gmail.com (neubyr) Date: Fri, 22 Feb 2013 17:50:06 -0600 Subject: [Tutor] object attribute validation Message-ID: I would like to validate data attributes before the object is instantiated or any changes thereafter. For example, following is a simple Person class with name and age attributes. I would like to validate whether age is an integer before it is added/changed in the object's dictionary. I have taken a simple integer validation example, but it could be something like DateField validation or X509 certificate validation as well. Following is my example code: class Person(object): def __init__(self,name,age): self.name = name self.age = age def get_age(self): return self._age def set_age(self,val): try: int(val) self._age = val except ValueError: raise Exception('Invalid value for age') def del_age(self): del self._age age = property(get_age,set_age,del_age) a = Person('John',6) b = Person('Johny','Six') Is this a good approach? Any suggestions for improving the code or alternative approaches would be helpful. -- thanks, neubyr -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Sat Feb 23 02:22:21 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 22 Feb 2013 19:22:21 -0600 Subject: [Tutor] How to break long lines? In-Reply-To: <51280354.5000909@pearwood.info> References: <51280354.5000909@pearwood.info> Message-ID: On 02/22/2013 05:46 PM, Steven D'Aprano wrote: > On 23/02/13 08:26, Jim Byrnes wrote: > >> I am cleaning up my code and have a number of sqlite3 execute >> statements that extend far past 80 characters. >> >> From my reading implicit line joining with (), [] or {} seems to be >> the preferred method, but >> >> cur.execute('SELECT Account FROM pwds WHERE Category=? ORDER BY >> Account COLLATE NOCASE', cat) >> >> gives this error: > [...] >> SyntaxError: EOL while scanning string literal > > > Single quote strings are limited to a single line, regardless of any > brackets (round, square or curly) around them. In this case, the > round brackets simply allow the arguments to cur.execute() to extend > over multiple lines, but each argument still has to obey the syntax > rules. > > You can't expect this to work: > > func(12345 67890) # ten digit number > > just because of the parentheses. Neither do single-quote strings > suddenly gain the power to extend past the end of line. > > > But what you can do is use a line continuation \ as you have seen. Or > you can use a little-known feature of Python, implicit string > concatenation. The Python compiler will automatically concatenate > strings at compile-time: > > s = "spam " 'ham ' 'eggs' > > is a more-verbose way of writing: > > s = "spam ham eggs" > > Now obviously this example here is useless, but when combined with > parentheses, you get a powerful way of writing long strings: > > > cur.execute('SELECT Account FROM pwds' ' WHERE Category=?' ' ORDER BY > Account' ' COLLATE NOCASE', cat) > > > which I think is really nice to read. The best part is, because > these are string literals, the language promises to concatenate them > at compile-time, not runtime. > > If implicit concatenation is too magical for you, you can use > explicit concatenation: > > cur.execute('SELECT Account FROM pwds' + ' WHERE Category=?' + ' > ORDER BY Account' + ' COLLATE NOCASE', cat) > > At worst, the string concatenation + operator will apply at runtime, > which for a short string like this is not a big deal. But in > practice, I would expect Python's "keyhole optimizer" to see that it > is only string literals being concatenated, and perform > constant-folding at compile-time. > > (Note: constant-folding is not a promise of the language. Not all > Python versions or implementations will do this.) > > > A fourth option is to use triple-quoted strings: > > cur.execute('''SELECT Account FROM pwds WHERE Category=? ORDER BY > Account COLLATE NOCASE''', cat) > > > but this relies on your SQL database being happy to receive commands > with embedded newlines, which it may not be. Thanks for giving me so many options to use in the future. When reading I completely blew by the single quote on a single line part. The db is sqlite3 and it seems happy with ''' strings. Thanks, Jim From davea at davea.name Sat Feb 23 03:03:00 2013 From: davea at davea.name (Dave Angel) Date: Fri, 22 Feb 2013 21:03:00 -0500 Subject: [Tutor] How to break long lines? In-Reply-To: References: <51280354.5000909@pearwood.info> Message-ID: <51282354.3030602@davea.name> On 02/22/2013 08:22 PM, Jim Byrnes wrote: > >> >> > > Thanks for giving me so many options to use in the future. When reading > I completely blew by the single quote on a single line part. The db is > sqlite3 and it seems happy with ''' strings. > FWIW, there is absolutely no difference between a string object created with single quotes, one created with triple-quotes, or one created by calling some function, or by evaluating some expression. sqlite3 could not possibly tell the difference, even if it wanted. -- DaveA From rohit_medi at hotmail.com Sat Feb 23 03:11:19 2013 From: rohit_medi at hotmail.com (Rohit Mediratta) Date: Fri, 22 Feb 2013 18:11:19 -0800 Subject: [Tutor] Trying to avoid using eval.. Message-ID: Hi All, I want to reload my Module after I fix bugs and want to instantiate an object of a class contained in this module. Heres the pseudo code of what I want to do: def rerun(testBlock) : op = testBlock.split('.') module = op[0] ; className = op[1] reload(module) # testBlock is a string, so it needs evaluation! newObject = testBlock() rerun('ModuleName.className') Obviously, line 4 and line 6 dont work today. I want to know if there is any smart way to achieve this. In my previous life (Tcl), I could use 'eval' or 'set' to achieve this. thanks, Rohit -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Sat Feb 23 03:26:54 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 23 Feb 2013 03:26:54 +0100 Subject: [Tutor] object attribute validation In-Reply-To: References: Message-ID: > I would like to validate data attributes before the object is instantiated > or any changes thereafter. For example, following is a simple Person class > with name and age attributes. [snip] Following is my > example code: > class Person(object): > def __init__(self,name,age): > self.name = name > self.age = age You need a try/except, or some other form of validation here, otherwise: >>> b = Person("Johnny", "Six") >>> b.get_age() 'Six' > Is this a good approach? Any suggestions for improving the code or > alternative approaches would be helpful. I can't help you with that question, since I'm still (!) wrapping my head around objects and haven't really gotten around to looking at data validation and when/how you should do it. I would probably use try/except for the __init__ and the setter. -- best regards, Robert S. From msirenef at lightbird.net Sat Feb 23 03:28:23 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 22 Feb 2013 21:28:23 -0500 Subject: [Tutor] Trying to avoid using eval.. In-Reply-To: References: Message-ID: <51282947.3090208@lightbird.net> On 02/22/2013 09:11 PM, Rohit Mediratta wrote: > Hi All, > I want to reload my Module after I fix bugs and want to instantiate an object of a class contained in this module. > > Heres the pseudo code of what I want to do: > > def rerun(testBlock) : > op = testBlock.split('.') > module = op[0] ; className = op[1] > reload(module) > # testBlock is a string, so it needs evaluation! > newObject = testBlock() > > rerun('ModuleName.className') > > > Obviously, line 4 and line 6 dont work today. > I want to know if there is any smart way to achieve this. > In my previous life (Tcl), I could use 'eval' or 'set' to achieve this. > > > thanks, > Rohit > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor You can do: module = __import__(module) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ "The condition of man is already close to satiety and arrogance, and there is danger of destruction of everything in existence." - a Brahmin to Onesicritus, 327 BC, reported in Strabo's Geography From davea at davea.name Sat Feb 23 03:35:13 2013 From: davea at davea.name (Dave Angel) Date: Fri, 22 Feb 2013 21:35:13 -0500 Subject: [Tutor] object attribute validation In-Reply-To: References: Message-ID: <51282AE1.4080608@davea.name> On 02/22/2013 09:26 PM, Robert Sjoblom wrote: >> I would like to validate data attributes before the object is instantiated >> or any changes thereafter. For example, following is a simple Person class >> with name and age attributes. [snip] Following is my >> example code: > >> class Person(object): >> def __init__(self,name,age): >> self.name = name >> self.age = age > You forgot to include the rest of the class as the OP defined it. Therefore your conclusion is entirely wrong. > You need a try/except, or some other form of validation here, otherwise: > >>>> b = Person("Johnny", "Six") >>>> b.get_age() > 'Six' > >> Is this a good approach? Any suggestions for improving the code or >> alternative approaches would be helpful. > > I can't help you with that question, since I'm still (!) wrapping my > head around objects and haven't really gotten around to looking at > data validation and when/how you should do it. I would probably use > try/except for the __init__ and the setter. > You only need it for the setter, and it's there. The setter is called by the initializer, through the call to property. Look up that mechanism. -- DaveA From dfjennings at gmail.com Sat Feb 23 03:40:26 2013 From: dfjennings at gmail.com (Don Jennings) Date: Fri, 22 Feb 2013 21:40:26 -0500 Subject: [Tutor] Tutor Digest, Vol 108, Issue 75 In-Reply-To: References: Message-ID: On Feb 22, 2013, at 9:12 PM, tutor-request at python.org wrote: > Message: 5 > Date: Fri, 22 Feb 2013 21:03:00 -0500 > From: Dave Angel > To: tutor at python.org > Subject: Re: [Tutor] How to break long lines? > Message-ID: <51282354.3030602 at davea.name> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 02/22/2013 08:22 PM, Jim Byrnes wrote: >> >>> >>> >> >> Thanks for giving me so many options to use in the future. When reading >> I completely blew by the single quote on a single line part. The db is >> sqlite3 and it seems happy with ''' strings. >> > > FWIW, there is absolutely no difference between a string object created > with single quotes, one created with triple-quotes, or one created by > calling some function, or by evaluating some expression. I beg to differ as it's bitten me on more than one occasion. As Steve pointed out, the triple quoted option embeds newlines. Maybe you mean something different than what I take your statement to mean? Take care, Don From eryksun at gmail.com Sat Feb 23 04:02:16 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 22 Feb 2013 22:02:16 -0500 Subject: [Tutor] How to break long lines? In-Reply-To: <51280354.5000909@pearwood.info> References: <51280354.5000909@pearwood.info> Message-ID: On Fri, Feb 22, 2013 at 6:46 PM, Steven D'Aprano wrote: > At worst, the string concatenation + operator will apply at runtime, > which for a short string like this is not a big deal. But in practice, > I would expect Python's "keyhole optimizer" to see that it is only > string literals being concatenated, and perform constant-folding at > compile-time. > > (Note: constant-folding is not a promise of the language. Not all > Python versions or implementations will do this.) http://en.wikipedia.org/wiki/Peephole_optimization A bit of trivia. The peephole optimizer (PyCode_Optimize) in CPython 3.3 was redesigned to use a stack, which allows folding even complex expressions involving constants: 3.3: >>> dis.dis(lambda: ('a'*2 + 'b'*2) * 2) 1 0 LOAD_CONST 7 ('aabbaabb') 3 RETURN_VALUE 3.2.3: >>> dis.dis(lambda: ('a'*2 + 'b'*2) * 2) 1 0 LOAD_CONST 4 ('aa') 3 LOAD_CONST 5 ('bb') 6 BINARY_ADD 7 LOAD_CONST 2 (2) 10 BINARY_MULTIPLY 11 RETURN_VALUE From steve at pearwood.info Sat Feb 23 05:24:37 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Feb 2013 15:24:37 +1100 Subject: [Tutor] Trying to avoid using eval.. In-Reply-To: References: Message-ID: <51284485.9090204@pearwood.info> On 23/02/13 13:11, Rohit Mediratta wrote: > > Hi All, > I want to reload my Module after I fix bugs and want to instantiate an object of a class contained in this module. > > Heres the pseudo code of what I want to do: > > def rerun(testBlock) : > op = testBlock.split('.') > module = op[0] ; className = op[1] > reload(module) > # testBlock is a string, so it needs evaluation! > newObject = testBlock() > > rerun('ModuleName.className') > > > Obviously, line 4 and line 6 dont work today. > I want to know if there is any smart way to achieve this. > In my previous life (Tcl), I could use 'eval' or 'set' to achieve this. Untested: def rerun(testBlock): modulename, classname = testBlock.split('.') module = __import__(modulename) reload(module) classobj = getattr(module, classname) return classobj() -- Steven From steve at pearwood.info Sat Feb 23 05:31:49 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Feb 2013 15:31:49 +1100 Subject: [Tutor] object attribute validation In-Reply-To: References: Message-ID: <51284635.20702@pearwood.info> On 23/02/13 10:50, neubyr wrote: > I would like to validate data attributes before the object is instantiated > or any changes thereafter. For example, following is a simple Person class > with name and age attributes. I would like to validate whether age is an > integer before it is added/changed in the object's dictionary. I have taken > a simple integer validation example, but it could be something like > DateField validation or X509 certificate validation as well. Following is > my example code: > > > class Person(object): > def __init__(self,name,age): > self.name = name > self.age = age > > def get_age(self): > return self._age > > def set_age(self,val): > try: > int(val) > self._age = val > except ValueError: > raise Exception('Invalid value for age') The setter is unnecessarily complicated. Just let the ValueError, or TypeError, or any other error, propagate: def set_age(self,val): self._age = int(val) This will allow the user to pass ages as strings, which I assume you want because that's what your code above does. instance.age = "6" will set the age to the int 6. If all you want to accept are ints, and nothing else: def set_age(self,val): if isinstance(val, int): self._age = val else: raise TypeError('expected an int, but got %r' % val) > def del_age(self): > del self._age > > age = property(get_age,set_age,del_age) In general, you would leave out the property deleter. I find that in general if you're validating attributes, you want them to be present and valid, so deleting should be an error. -- Steven From eryksun at gmail.com Sat Feb 23 05:35:54 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 22 Feb 2013 23:35:54 -0500 Subject: [Tutor] Trying to avoid using eval.. In-Reply-To: References: Message-ID: On Fri, Feb 22, 2013 at 9:11 PM, Rohit Mediratta wrote: > Heres the pseudo code of what I want to do: > > def rerun(testBlock) : > op = testBlock.split('.') > module = op[0] ; className = op[1] > reload(module) > # testBlock is a string, so it needs evaluation! > newObject = testBlock() > > rerun('ModuleName.className') You can use __import__, and extend it to handle packages: try: reload except NameError: from imp import reload # 3.x def rerun(clsPath, *args): modPath, clsName = clsPath.rsplit('.', 1) mod = __import__(modPath, fromlist='not empty') reload(mod) cls = getattr(mod, clsName) return cls(*args) The fromlist option only cares whether or not the sequence is empty. If it's not empty you get the leaf (e.g. 'xml.etree.ElementTree' => ElementTree). If it's empty you get the base package (e.g. 'xml.etree.ElementTree' => xml). From davea at davea.name Sat Feb 23 06:43:29 2013 From: davea at davea.name (Dave Angel) Date: Sat, 23 Feb 2013 00:43:29 -0500 Subject: [Tutor] How to break long lines? In-Reply-To: References: Message-ID: <51285701.9060807@davea.name> On 02/22/2013 09:40 PM, Don Jennings wrote: > > On Feb 22, 2013, at 9:12 PM, tutor-request at python.org wrote: > >> Message: 5 >> Date: Fri, 22 Feb 2013 21:03:00 -0500 >> From: Dave Angel >> >>> >> Did you read the beginning of that digest? It said to make sure and rename the subect line. Tutor Digest isn't much of a title. In the future, please reply to the individual message, which you can probably find as an attachment to the digest. Not only will that give you the correct subject line, but it won't break threading either. >> FWIW, there is absolutely no difference between a string object created >> with single quotes, one created with triple-quotes, or one created by >> calling some function, or by evaluating some expression. > > I beg to differ as it's bitten me on more than one occasion. As Steve pointed out, the triple quoted option embeds newlines. Maybe you mean something different than what I take your statement to mean? > > The triple-quoting did not add newlines, the user of them did, probably along with extra spaces. And all the other methods of creating a string object could have newlines as well. No difference. Certainly if one does not consider the contents of the string, then one should expect surprises. If you run a triple-quoted string over more than a single line, you're deliberately and explicitly adding newlines. If you call readline(), the string object you get back is likely to have a newline in it. But not necessarily. A programmer that doesn't consider that is setting up for a surprise. If you have a \n in a string, you're probably going to get a newline. Even if you did something like: name = "c:\my\new\directory" So if you don't consider that, you are likely to get a surprise. Life is full of surprises; it's important to know what your literals represent. -- DaveA From jitu.icfai at gmail.com Sat Feb 23 07:14:31 2013 From: jitu.icfai at gmail.com (jitendra gupta) Date: Sat, 23 Feb 2013 11:44:31 +0530 Subject: [Tutor] Unit test case Message-ID: Hi, I am working one tool, which will do compile/run the workspace (that code is written on c/c++). on that my requirment is i need to compile subfolder also, i have wrote code for that also. My problem is , i am unable to write the Unit test case for that. Since my method (called run_subfolder) is not retrurning any thing (this will create one command line argument in that i am adding subfolder condition and passing to the another class which will do actual thing) . For this method i need to write unit test case. Since i dont have to workspace also , so that i can test this case . Please advise on this. what i need to do. this is possible or not, if not why. Some forum suggested use mox. but i dont have more idea on this . in mox how i will get thet output of the function Thanks Jitendra Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Feb 23 09:43:54 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Feb 2013 19:43:54 +1100 Subject: [Tutor] How to break long lines? In-Reply-To: <51282354.3030602@davea.name> References: <51280354.5000909@pearwood.info> <51282354.3030602@davea.name> Message-ID: <5128814A.70204@pearwood.info> On 23/02/13 13:03, Dave Angel wrote: > On 02/22/2013 08:22 PM, Jim Byrnes wrote: >> >>> >>> >> >> Thanks for giving me so many options to use in the future. When reading >> I completely blew by the single quote on a single line part. The db is >> sqlite3 and it seems happy with ''' strings. >> > > FWIW, there is absolutely no difference between a string object created with single quotes, one created with triple-quotes, or one created by calling some function, or by evaluating some expression. sqlite3 could not possibly tell the difference, even if it wanted. This is true. A triple-quoted string on a single line is a single line of text: s = """Hello world""" But in general, it is fair to expect that most triple-quoted strings will contain at least one newline, and single-quoted strings generally won't. It might be that some databases dislikes receiving SQL queries containing newlines. In any case, it bears repeating that strings are strings in Python, whatever delimiters you use. The only difference between single-quoted, triple-quoted, and raw strings, is the parsing rules applied at compile-time, not the object you get at the end. -- Steven From __peter__ at web.de Sat Feb 23 09:45:39 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 23 Feb 2013 09:45:39 +0100 Subject: [Tutor] Trying to avoid using eval.. References: Message-ID: Rohit Mediratta wrote: > I want to reload my Module after I fix bugs and want to instantiate an > object of a class contained in this module. Just a warning about reload(), as your question was already answered: Reloading modules may seem convenient at first, but can lead to strange errors as existing objects are not updated: >>> import module >>> obj = module.SomeClass() >>> reload(module) >>> isinstance(obj, module.SomeClass) False Personally I avoid reload() (and importing the main script which leads to similar problems). From alan.gauld at btinternet.com Sat Feb 23 10:32:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Feb 2013 09:32:59 +0000 Subject: [Tutor] Unit test case In-Reply-To: References: Message-ID: On 23/02/13 06:14, jitendra gupta wrote: > I am working one tool, which will do compile/run the workspace (that > code is written on c/c++). on that my requirment is i need to compile > subfolder also, i have wrote code for that also. Just to clarify. You are writing a tool in Python that will compile and run C/C++ code? I assume that the actual compilation is being done by some other tool? You are not writing a C compiler in Python? Is that right so far? > My problem is , i am unable to write the Unit test case for that. I'm not sure which bit you can't write the unit test for. Can you be more specific? Also what unit test framework are you using? And while we are at it which OS and which Python version? And finally which C/C++ tools are you using to do the compilation? make? VisualStudio? XCode? gcc? > Since my method (called run_subfolder) is not retrurning any thing > (this will create one command line argument in that i am adding > subfolder condition and passing to the another class which will do > actual thing) . Nope, you lost me there. What is creating a command line argument? Which command line? Where is the other class? Is it defined inside run_subfolder? > For this method i need to write unit test case. Since i > dont have to workspace also , so that i can test this case . Please Sorry, what do you mean by Workspace in this context? > advise on this. what i need to do. this is possible or not, if not why. Sorry, I don't understand enough of what you are trying to do to comment. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mcooganj at gmail.com Sat Feb 23 22:56:58 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Sun, 24 Feb 2013 08:56:58 +1100 Subject: [Tutor] getting and using information dict objects Message-ID: Hi, I am trying to make a move from excel to python. My main need is economic data -- to do economic analysis. I have found the FRED package, and appear to have connected to the St Louis Fed's FRED and downloaded some data, but i'm not sure what to do with the objects that are returned. _____ > import fred > fred.key(fredKey) (i guessed that i should not provide my own FRED API key) > gnp = fred.series('GNPCA') i can see that the object returned is a dict > type(gnp) but i cannot see how to access the observations, or use them in any way. After a bit of fiddling about, i managed to find another method, which i think also returns a dictionary of values and meta-data: gnpObvs = fred.observations('GNPCA') however I cannot figure out how to get the observation values out and use them. I may be thinking in the wrong framework -- i guess i'm expecting something that is an intuitive as an excel table. The end game for me is making plots of variables, combining them, and doing regressions -- i cannot see how i might take what i'm getting from these FRED / Python dicts to actual data analysis. Could someone please help me take these first steps? thanks + best regards matt From fomcl at yahoo.com Sat Feb 23 23:12:04 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 23 Feb 2013 14:12:04 -0800 (PST) Subject: [Tutor] getting and using information dict objects In-Reply-To: References: Message-ID: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> > I am trying to make a move from excel to python. My main need is > economic data -- to do economic analysis. If you say Python and Excel the first thing that comes to mind is the xlrd package > The end game for me is making plots of variables, combining them, and > doing regressions -- i cannot see how i might take what i'm getting > from these FRED / Python dicts to actual data analysis. > > Could someone please help me take these first steps? I'm not familiar with the Fred package. Pandas (http://pandas.pydata.org/) seems to be perfect for what you're doing. It's an R-like layer on top of numpy. It can be used to read Excel and many other formats and it works well with matplotlib. It's a cool tool to manipulate/massage/munge data, then analyze it (though R has still more, often ueber-exotic, stats). Its origin lies in the analysis of... economic data. Best used with IPython. From msirenef at lightbird.net Sat Feb 23 23:28:19 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 23 Feb 2013 17:28:19 -0500 Subject: [Tutor] getting and using information dict objects In-Reply-To: References: Message-ID: <51294283.4090702@lightbird.net> On 02/23/2013 04:56 PM, Matthew Johnson wrote: > Hi, > > I am trying to make a move from excel to python. My main need is > economic data -- to do economic analysis. > > I have found the FRED package, and appear to have connected to the St > Louis Fed's FRED and downloaded some data, but i'm not sure what to do > with the objects that are returned. > > _____ > >> import fred >> fred.key(fredKey) > (i guessed that i should not provide my own FRED API key) > >> gnp = fred.series('GNPCA') > i can see that the object returned is a dict > >> type(gnp) > > > but i cannot see how to access the observations, or use them in any way. > > After a bit of fiddling about, i managed to find another method, which > i think also returns a dictionary of values and meta-data: > > gnpObvs = fred.observations('GNPCA') > > however I cannot figure out how to get the observation values out and > use them. > > I may be thinking in the wrong framework -- i guess i'm expecting > something that is an intuitive as an excel table. > > The end game for me is making plots of variables, combining them, and > doing regressions -- i cannot see how i might take what i'm getting > from these FRED / Python dicts to actual data analysis. > > Could someone please help me take these first steps? > > thanks + best regards > > matt > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Basic use of dictionaries is: d = dict(x=1, y=2) for key, val in d.items(): print(key, val) print d['x'] print d['y'] -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From alan.gauld at btinternet.com Sat Feb 23 23:44:49 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Feb 2013 22:44:49 +0000 Subject: [Tutor] getting and using information dict objects In-Reply-To: References: Message-ID: On 23/02/13 21:56, Matthew Johnson wrote: > I am trying to make a move from excel to python. My main need is > economic data -- to do economic analysis. Any particular reason for moving to Python? I know this is a Python list and we are all Python fans but, frankly, it sounds like your needs might be better met with R. There are Python bindings for R but, honestly, I think raw R might suit what you want better. You can read Excel data into a data frame and then slice and dice it any which way you want. The right tool for the job... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mcooganj at gmail.com Sat Feb 23 23:51:52 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Sun, 24 Feb 2013 09:51:52 +1100 Subject: [Tutor] getting and using information dict objects In-Reply-To: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <-1508751986444041054@unknownmsgid> I can see i was being unclear: i wish to replace my analysis in excel with analysis in python. I am fairly sure i am querying the FRED API, but i am unsure how to _access and use_ the dict objects that it is returning. For example, how would i just print out values? Thanks for your help On 24/02/2013, at 9:12 AM, Albert-Jan Roskam wrote: > > >> I am trying to make a move from excel to python. My main need is > >> economic data -- to do economic analysis. > > If you say Python and Excel the first thing that comes to mind is the xlrd package > > > >> The end game for me is making plots of variables, combining them, and >> doing regressions -- i cannot see how i might take what i'm getting >> from these FRED / Python dicts to actual data analysis. >> >> Could someone please help me take these first steps? > > I'm not familiar with the Fred package. Pandas (http://pandas.pydata.org/) seems to be perfect for what you're doing. It's an R-like layer on top of numpy. It can be used to read Excel and many other formats and it works well with matplotlib. It's a cool tool to manipulate/massage/munge data, then analyze it (though R has still more, often ueber-exotic, stats). Its origin lies in the analysis of... economic data. Best used with IPython. > From robert.sjoblom at gmail.com Sun Feb 24 00:40:58 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sun, 24 Feb 2013 00:40:58 +0100 Subject: [Tutor] getting and using information dict objects In-Reply-To: <-1508751986444041054@unknownmsgid> References: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> <-1508751986444041054@unknownmsgid> Message-ID: > I am fairly sure i am querying the FRED API, but i am unsure how to > _access and use_ the dict objects that it is returning. For example, > how would i just print out values? If it's a dict object, the standard dictionary behavior and methods should work. I've not looked closely at the FRED API, but something like (untested): for key in dictionary: print(key, dictionary[key]) could possibly get you started. -- best regards, Robert S. From mcooganj at gmail.com Sun Feb 24 00:51:12 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Sun, 24 Feb 2013 10:51:12 +1100 Subject: [Tutor] getting and using information dict objects In-Reply-To: References: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> <-1508751986444041054@unknownmsgid> Message-ID: <1403569224316556901@unknownmsgid> Thanks very much; hopefully that's the boost i need to get rolling. Best regards matt On 24/02/2013, at 10:40 AM, Robert Sjoblom wrote: >> I am fairly sure i am querying the FRED API, but i am unsure how to >> _access and use_ the dict objects that it is returning. For example, >> how would i just print out values? > > If it's a dict object, the standard dictionary behavior and methods > should work. I've not looked closely at the FRED API, but something > like (untested): > for key in dictionary: > print(key, dictionary[key]) > > could possibly get you started. > > -- > best regards, > Robert S. From mcooganj at gmail.com Sun Feb 24 03:40:42 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Sun, 24 Feb 2013 13:40:42 +1100 Subject: [Tutor] getting and using information dict objects In-Reply-To: <1403569224316556901@unknownmsgid> References: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> <-1508751986444041054@unknownmsgid> <1403569224316556901@unknownmsgid> Message-ID: For the sake of those who finds this thread -- the date / value pairs can be printed by the following: import fred fred.key(fredKey) gnpObvs = fred.observations('GNPCA') for i in range(1, len(gnpObvs['observations']['observation'])): print gnpObvs['observations']['observation'][i]['date'], gnpObvs['observations']['observation'][i]['value'] mj On 24 February 2013 10:51, Matthew Johnson wrote: > Thanks very much; hopefully that's the boost i need to get rolling. > > Best regards > > matt > > On 24/02/2013, at 10:40 AM, Robert Sjoblom wrote: > >>> I am fairly sure i am querying the FRED API, but i am unsure how to >>> _access and use_ the dict objects that it is returning. For example, >>> how would i just print out values? >> >> If it's a dict object, the standard dictionary behavior and methods >> should work. I've not looked closely at the FRED API, but something >> like (untested): >> for key in dictionary: >> print(key, dictionary[key]) >> >> could possibly get you started. >> >> -- >> best regards, >> Robert S. From msirenef at lightbird.net Sun Feb 24 03:55:58 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 23 Feb 2013 21:55:58 -0500 Subject: [Tutor] getting and using information dict objects In-Reply-To: References: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> <-1508751986444041054@unknownmsgid> <1403569224316556901@unknownmsgid> Message-ID: <5129813E.3010306@lightbird.net> On 02/23/2013 09:40 PM, Matthew Johnson wrote: > For the sake of those who finds this thread -- the date / value pairs > can be printed by the following: > > import fred > > fred.key(fredKey) > > gnpObvs = fred.observations('GNPCA') > > for i in range(1, len(gnpObvs['observations']['observation'])): > print gnpObvs['observations']['observation'][i]['date'], > gnpObvs['observations']['observation'][i]['value'] > > mj > You can do this in a simpler way (in python 2.x): observation = gnpObvs["observation"]["observation"] for obsdict in observation.values()[1:]: print obsdict["date"] if you need the 'i' counter, you can do: for i, obsdict in enumerate(observation.values())[1:]: print obsdict["date"] HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Do whatever you will, but first be such as are able to will. Friedrich Nietzsche From davea at davea.name Sun Feb 24 04:04:06 2013 From: davea at davea.name (Dave Angel) Date: Sat, 23 Feb 2013 22:04:06 -0500 Subject: [Tutor] getting and using information dict objects In-Reply-To: References: <1361657524.42276.YahooMailNeo@web163805.mail.gq1.yahoo.com> <-1508751986444041054@unknownmsgid> <1403569224316556901@unknownmsgid> Message-ID: <51298326.9040805@davea.name> On 02/23/2013 09:40 PM, Matthew Johnson wrote: > For the sake of those who finds this thread -- the date / value pairs > can be printed by the following: > > import fred > > fred.key(fredKey) > > gnpObvs = fred.observations('GNPCA') > > for i in range(1, len(gnpObvs['observations']['observation'])): > print gnpObvs['observations']['observation'][i]['date'], > gnpObvs['observations']['observation'][i]['value'] > > mj > So it's returning a dict of dicts of lists of dicts? Perhaps this loop would read better (untested): for item in gnpObvs['observations']['observation']: print item['date'], item['value'] -- DaveA From sudo.nohup at gmail.com Sun Feb 24 11:56:49 2013 From: sudo.nohup at gmail.com (Sudo Nohup) Date: Sun, 24 Feb 2013 18:56:49 +0800 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: Dear all, I want to change the value of a char in a string for Python. However, It seems that "=" does not work. Could you help me? Thanks! str = "abcd" result = [char = 'a' for char in str if char == 'c'] OR: str = 'abcd' for char in str: if char == 'a': char = 'c' OR: str = 'abcd' for i in range(len(str)): if str[i] == 'a': str[i] = 'c' ( Traceback (most recent call last): File "", line 3, in TypeError: 'str' object does not support item assignment ) James -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudo.nohup at gmail.com Sun Feb 24 12:42:16 2013 From: sudo.nohup at gmail.com (Sudo Nohup) Date: Sun, 24 Feb 2013 19:42:16 +0800 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: Actually, I would like to substitute all the chars in a string with its ascii adding 2, for cracking the naive "Caesar cipher". So, there is a list of chars to be replaced. If I use "replace" function, I have to replace them one by one. Thanks all the same. On Sun, Feb 24, 2013 at 7:32 PM, Marco Mistroni wrote: > You can use replace instead? > On 24 Feb 2013 10:59, "Sudo Nohup" wrote: > >> Dear all, >> >> I want to change the value of a char in a string for Python. However, It >> seems that "=" does not work. >> >> Could you help me? Thanks! >> >> str = "abcd" >> result = [char = 'a' for char in str if char == 'c'] >> >> >> OR: >> >> str = 'abcd' >> for char in str: >> if char == 'a': >> char = 'c' >> >> >> OR: >> >> str = 'abcd' >> for i in range(len(str)): >> if str[i] == 'a': >> str[i] = 'c' >> >> ( >> Traceback (most recent call last): >> File "", line 3, in >> TypeError: 'str' object does not support item assignment >> ) >> >> >> James >> >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Sun Feb 24 12:47:15 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Sun, 24 Feb 2013 17:17:15 +0530 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: On Feb 24, 2013 4:27 PM, "Sudo Nohup" wrote: > > Dear all, > > I want to change the value of a char in a string for Python. However, It seems that "=" does not work. > > Could you help me? Thanks! > > str = "abcd" > result = [char = 'a' for char in str if char == 'c'] > > > OR: > > str = 'abcd' > for char in str: > if char == 'a': > char = 'c' > > > OR: > > str = 'abcd' > for i in range(len(str)): > if str[i] == 'a': > str[i] = 'c' > > ( > Traceback (most recent call last): > File "", line 3, in > TypeError: 'str' object does not support item assignment > ) Look up string replace function. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudo.nohup at gmail.com Sun Feb 24 12:57:42 2013 From: sudo.nohup at gmail.com (Sudo Nohup) Date: Sun, 24 Feb 2013 19:57:42 +0800 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: Thanks for your help. I just found a webpage used for me: http://stackoverflow.com/questions/10017147/python-replace-characters-in-string That page provides some other solutions. Thanks! On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai wrote: > On Feb 24, 2013 4:27 PM, "Sudo Nohup" wrote: > > > > Dear all, > > > > I want to change the value of a char in a string for Python. However, It > seems that "=" does not work. > > > > Could you help me? Thanks! > > > > str = "abcd" > > result = [char = 'a' for char in str if char == 'c'] > > > > > > OR: > > > > str = 'abcd' > > for char in str: > > if char == 'a': > > char = 'c' > > > > > > OR: > > > > str = 'abcd' > > for i in range(len(str)): > > if str[i] == 'a': > > str[i] = 'c' > > > > ( > > Traceback (most recent call last): > > File "", line 3, in > > TypeError: 'str' object does not support item assignment > > ) > > Look up string replace function. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Feb 24 13:32:54 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Feb 2013 23:32:54 +1100 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: <512A0876.1080005@pearwood.info> On 24/02/13 21:56, Sudo Nohup wrote: > Dear all, > > I want to change the value of a char in a string for Python. However, It > seems that "=" does not work. Strings are immutable, which means that you cannot modify them in place. You can only create a new string with the characters you want. If you want to change one letter, the simplest way is with string slicing: s = "Hello world!" t = s[:6] + "W" + s[7:] print t => prints "Hello World!" If you want to change many letters, the best way is to create a new list of the characters, and then join them: s = "Hello" chars = [chr(ord(c) + 13) for c in s] t = ''.join(chars) print t => prints 'Uryy|' Best still is to use the string methods, if you can, such as str.upper(), str.replace(), etc. http://docs.python.org/2/tutorial/introduction.html#strings http://docs.python.org/2/library/stdtypes.html#string-methods -- Steven From steve at pearwood.info Sun Feb 24 13:35:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Feb 2013 23:35:17 +1100 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: <512A0905.8080603@pearwood.info> On 24/02/13 22:42, Sudo Nohup wrote: > Actually, I would like to substitute all the chars in a string with its > ascii adding 2, for cracking the naive "Caesar cipher". A shameless plug: https://pypi.python.org/pypi/obfuscate -- Steven From davea at davea.name Sun Feb 24 13:40:31 2013 From: davea at davea.name (Dave Angel) Date: Sun, 24 Feb 2013 07:40:31 -0500 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: Message-ID: <512A0A3F.2030503@davea.name> Both your later remarks are top-posted, ruining the sequence of who posted what. On 02/24/2013 06:57 AM, Sudo Nohup wrote: > Thanks for your help. > > I just found a webpage used for me: > http://stackoverflow.com/questions/10017147/python-replace-characters-in-string > > That page provides some other solutions. Thanks! > > On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai wrote: > >> On Feb 24, 2013 4:27 PM, "Sudo Nohup" wrote: >>> >>> Dear all, >>> >>> I want to change the value of a char in a string for Python. However, It >> seems that "=" does not work. assignment works fine, when it's really assignment. But it doesn't work inside an expression, and you cannot change an immutable object in place. >>> >>> Could you help me? Thanks! >>> >>> str = "abcd" >>> result = [char = 'a' for char in str if char == 'c'] In a list comprehension, the if expression is used to skip items from the sequence. So the above form, modified, might be used to remove selected characters from the string. By the way, since 'str' is a builtin, it's a bad practice to take it over for your own use. For example, what if you subsequently needed to convert an int to a string? >>> >>> >>> OR: >>> >>> str = 'abcd' >>> for char in str: >>> if char == 'a': >>> char = 'c' You create a new object, and bind it to char, but then you don't do anything with it. >>> >>> >>> OR: >>> >>> str = 'abcd' >>> for i in range(len(str)): >>> if str[i] == 'a': >>> str[i] = 'c' >>> >>> ( >>> Traceback (most recent call last): >>> File "", line 3, in >>> TypeError: 'str' object does not support item assignment >>> ) A string object is immutable, so that you cannot use assignment to replace portions of it. >> >> Look up string replace function. >> > That of course is the simplest answer to the problem as originally given. (Here is where your amendment to the problem should have been given, rather than top-posting it.) But you now say you're planning to replace all the characters in the string, according to a formula. What yo should have specified in the first place is what version of Python you're using. I'll assume 2.7 This amended problem would lend itself nicely to translate(), and the link you posted does mention that. But there are several other approaches, similar to the ones you already tried, and sometimes one of them is more interesting or useful. For example, a list comprehension very close to what you tried would work fine (untested): temp = [ chr( ord(char) + 2 ) for char in mystring] result = "".join(temp) Likewise a loop: result = [] for char in mystring: char = chr ( ord(char) + 2 result.append(char) result = "".join(result) -- DaveA From sudo.nohup at gmail.com Sun Feb 24 14:26:03 2013 From: sudo.nohup at gmail.com (Sudo Nohup) Date: Sun, 24 Feb 2013 21:26:03 +0800 Subject: [Tutor] How to change the char in string for Python In-Reply-To: <512A0A3F.2030503@davea.name> References: <512A0A3F.2030503@davea.name> Message-ID: Thanks very much!! I learnt a lot from you kind reply. Not only is it about the question itself, but also about how to ask a question in a mailing list.(Sorry that it is the first time for me to ask questions in a mailing list). The question comes from a riddle of the PythonChallenge website( http://www.pythonchallenge.com/pc/def/map.html). Now I write the code as the following, mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." temp = [ chr ( (ord(char)-ord('a')+2)%26 +ord('a')) if (ord(char)>=ord('a') and ord(char)<=ord('z')) else char for char in mystring ] result = "".join(temp) print result OR mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." result = [] for char in mystring: if(ord(char)>=ord('a') and ord(char)<=ord('z')): char = chr ( (ord(char)-ord('a')+2)%26 +ord('a')) result.append(char) result = "".join(result) print result Thanks, James On Sun, Feb 24, 2013 at 8:40 PM, Dave Angel wrote: > Both your later remarks are top-posted, ruining the sequence of who posted > what. > > > On 02/24/2013 06:57 AM, Sudo Nohup wrote: > >> Thanks for your help. >> >> I just found a webpage used for me: >> http://stackoverflow.com/**questions/10017147/python-** >> replace-characters-in-string >> >> That page provides some other solutions. Thanks! >> >> On Sun, Feb 24, 2013 at 7:47 PM, Asokan Pichai >> **wrote: >> >> On Feb 24, 2013 4:27 PM, "Sudo Nohup" wrote: >>> >>>> >>>> Dear all, >>>> >>>> I want to change the value of a char in a string for Python. However, It >>>> >>> seems that "=" does not work. >>> >> > assignment works fine, when it's really assignment. But it doesn't work > inside an expression, and you cannot change an immutable object in place. > > > >>>> Could you help me? Thanks! >>>> >>>> str = "abcd" >>>> result = [char = 'a' for char in str if char == 'c'] >>>> >>> > In a list comprehension, the if expression is used to skip items from the > sequence. So the above form, modified, might be used to remove selected > characters from the string. > > By the way, since 'str' is a builtin, it's a bad practice to take it over > for your own use. For example, what if you subsequently needed to convert > an int to a string? > > > >>>> >>>> OR: >>>> >>>> str = 'abcd' >>>> for char in str: >>>> if char == 'a': >>>> char = 'c' >>>> >>> > You create a new object, and bind it to char, but then you don't do > anything with it. > > > >>>> >>>> OR: >>>> >>>> str = 'abcd' >>>> for i in range(len(str)): >>>> if str[i] == 'a': >>>> str[i] = 'c' >>>> >>>> ( >>>> Traceback (most recent call last): >>>> File "", line 3, in >>>> TypeError: 'str' object does not support item assignment >>>> ) >>>> >>> > A string object is immutable, so that you cannot use assignment to replace > portions of it. > > > >>> Look up string replace function. >>> >>> >> > That of course is the simplest answer to the problem as originally given. > > (Here is where your amendment to the problem should have been given, > rather than top-posting it.) > > But you now say you're planning to replace all the characters in the > string, according to a formula. > > What yo should have specified in the first place is what version of Python > you're using. I'll assume 2.7 > > This amended problem would lend itself nicely to translate(), and the link > you posted does mention that. > > But there are several other approaches, similar to the ones you already > tried, and sometimes one of them is more interesting or useful. > > For example, a list comprehension very close to what you tried would work > fine (untested): > > temp = [ chr( ord(char) + 2 ) for char in mystring] > result = "".join(temp) > > Likewise a loop: > > result = [] > for char in mystring: > char = chr ( ord(char) + 2 > result.append(char) > result = "".join(result) > > > -- > DaveA > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joskerc at gmail.com Sun Feb 24 15:12:23 2013 From: joskerc at gmail.com (Jos Kerc) Date: Sun, 24 Feb 2013 15:12:23 +0100 Subject: [Tutor] How to change the char in string for Python In-Reply-To: References: <512A0A3F.2030503@davea.name> Message-ID: On Sun, Feb 24, 2013 at 2:26 PM, Sudo Nohup wrote: > Thanks very much!! > > I learnt a lot from you kind reply. Not only is it about the question > itself, but also about how to ask a question in a mailing list.(Sorry that > it is the first time for me to ask questions in a mailing list). > > The question comes from a riddle of the PythonChallenge website( > http://www.pythonchallenge.com/pc/def/map.html). > > Now I write the code as the following, > > mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq > ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm > jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." > temp = [ chr ( (ord(char)-ord('a')+2)%26 +ord('a')) if > (ord(char)>=ord('a') and ord(char)<=ord('z')) else char for char in > mystring ] > result = "".join(temp) > print result > > OR > > mystring = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq > ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm > jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." > result = [] > for char in mystring: > if(ord(char)>=ord('a') and ord(char)<=ord('z')): > char = chr ( (ord(char)-ord('a')+2)%26 +ord('a')) > result.append(char) > result = "".join(result) > print result > > Thanks, > James > > > > Hi James, for this riddle, look for the translate() method. Have fun nwith the challenges. Jos -------------- next part -------------- An HTML attachment was scrubbed... URL: From neubyr at gmail.com Sun Feb 24 22:35:52 2013 From: neubyr at gmail.com (neubyr) Date: Sun, 24 Feb 2013 15:35:52 -0600 Subject: [Tutor] object attribute validation In-Reply-To: <51284635.20702@pearwood.info> References: <51284635.20702@pearwood.info> Message-ID: On Fri, Feb 22, 2013 at 10:31 PM, Steven D'Aprano wrote: > On 23/02/13 10:50, neubyr wrote: > >> I would like to validate data attributes before the object is instantiated >> or any changes thereafter. For example, following is a simple Person class >> with name and age attributes. I would like to validate whether age is an >> integer before it is added/changed in the object's dictionary. I have >> taken >> a simple integer validation example, but it could be something like >> DateField validation or X509 certificate validation as well. Following is >> my example code: >> >> >> class Person(object): >> def __init__(self,name,age): >> self.name = name >> self.age = age >> >> def get_age(self): >> return self._age >> >> def set_age(self,val): >> try: >> int(val) >> self._age = val >> except ValueError: >> raise Exception('Invalid value for age') >> > > The setter is unnecessarily complicated. Just let the ValueError, or > TypeError, or any other error, propagate: > > def set_age(self,val): > self._age = int(val) > > > This will allow the user to pass ages as strings, which I assume you want > because that's what your code above does. instance.age = "6" will set the > age to the int 6. If all you want to accept are ints, and nothing else: > > > def set_age(self,val): > if isinstance(val, int): > self._age = val > else: > raise TypeError('expected an int, but got %r' % val) > > > > > def del_age(self): >> del self._age >> >> age = property(get_age,set_age,del_**age) >> > > > In general, you would leave out the property deleter. I find that in > general if you're validating attributes, you want them to be present and > valid, so deleting should be an error. > > > -- > Steven > > Thank you for your comments Steven. Yes, I think I should remove property deleter in this case. I would like to use this Person class in another class. For example, if Person class is 'model' in a small MVC-style web application, then where should I place my validation. A view form will be passing parameters to a controller which will create and write Person objects/models. Should the validation be in place at all three levels? I am inclined towards adding integer validation in views, but I am not sure where should I add it in a controller class. Also, it's easy to add integer validation in view form (javascript), but what if I have a more complex format - X509 certificate or some other file-type related validation? Is it OK to validate them only in property setter methods? -- N -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Mon Feb 25 18:44:41 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 25 Feb 2013 17:44:41 +0000 Subject: [Tutor] object attribute validation In-Reply-To: References: <51284635.20702@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF474181BE406@SCACMX008.exchad.jpmchase.net> neubyr wrote: > Thank you for your comments Steven. > > Yes, I think I should remove property deleter in this case. > > I would like to use this Person class in another class. For example, if Person class is 'model' in a > small MVC-style web application, then where should I place my validation. A view form will be passing > parameters to a controller which will create and write Person objects/models. Should the validation be > in place at all three levels? > > I am inclined towards adding integer validation in views, but I am not sure where should I add it in a > controller class. Also, it's easy to add integer validation in view form (javascript), but what if I > have a more complex format - X509 certificate or ?some other file-type related validation? Is it OK to > validate them only in property setter methods? > Where I would place validation depends a bit on the project. As I see it there are two types of validation, simple and complex. Simple validation is something like "is this an int?" or "did they fill in all parameters?" and should be done in the form(view). Complex validation is more of a logical/business validation like "is using a blowhole a valid operation for Animal type Giraffe?" This can be done where you do an action (e.g. creating Person class) or in the class/module itself (controller). If you instantiate Person objects from various different places in code (assuming no code duplication) then I would either create a validation function or add it to the class, but if you only have one place where Person objects are created I would add the validation there with comments on validation rules or reference links. I tend to favor validation functions where I can give all parameters and it can return either bool, or an appropriate error message. My use case is where objects do not usually need to change once created (i.e. I have all input in advance). If I thought the objects would change frequently, then adding the validation to the setter makes sense. You can also combine the two ideas by adding the validation to the setters and having a wrapper validation function that creates a Person object and then sets the params (returning either the new object or error message). ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From emailkgnow at gmail.com Tue Feb 26 14:02:44 2013 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 26 Feb 2013 16:02:44 +0300 Subject: [Tutor] There's a Programmer in Me Message-ID: Hi All, I'm not a programmer by profession, but I want to learn python. I've got lots of Ideas that want to realize, but I always run into these stupid hiccups where I follow the tutorials and something stupid (known/unkown) is causing things not to work ... frustration ensues... After more than 2 years (on and off) I've got the basics down and have written some scripts, but I want some place online where a live person can tutor me to the next level. Any good suggestions? As always, many thanks for your great advice. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Feb 26 14:54:49 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 26 Feb 2013 13:54:49 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: Message-ID: On 26/02/2013 13:02, Khalid Al-Ghamdi wrote: > Hi All, > > I'm not a programmer by profession, but I want to learn python. I've got > lots of Ideas that want to realize, but I always run into these > stupid hiccups where I follow the tutorials and something stupid > (known/unkown) is causing things not to work ... frustration ensues... > > After more than 2 years (on and off) I've got the basics down and > have written some scripts, but I want some place online where a live > person can tutor me to the next level. Any good suggestions? > > As always, many thanks for your great advice. > http://pythonmentors.com/ -- Cheers. Mark Lawrence From mail at timgolden.me.uk Tue Feb 26 14:57:37 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 26 Feb 2013 13:57:37 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: Message-ID: <512CBF51.90609@timgolden.me.uk> On 26/02/2013 13:54, Mark Lawrence wrote: > On 26/02/2013 13:02, Khalid Al-Ghamdi wrote: >> Hi All, >> >> I'm not a programmer by profession, but I want to learn python. I've got >> lots of Ideas that want to realize, but I always run into these >> stupid hiccups where I follow the tutorials and something stupid >> (known/unkown) is causing things not to work ... frustration ensues... >> >> After more than 2 years (on and off) I've got the basics down and >> have written some scripts, but I want some place online where a live >> person can tutor me to the next level. Any good suggestions? >> >> As always, many thanks for your great advice. >> > > http://pythonmentors.com/ > Umm. No. Sorry, Mark, but that site and the core-mentorship list it advertises are intended for progammers who want to be helped in the development *of* Python, not development *in* Python. Ie, otherwise experienced programmers who are unfamiliar with the Python codebase. TJG From fomcl at yahoo.com Tue Feb 26 15:08:37 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 26 Feb 2013 06:08:37 -0800 (PST) Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: Message-ID: <1361887717.25344.YahooMailNeo@web163801.mail.gq1.yahoo.com> >After more than 2 years (on and off)?I've got the basics down?and have?written some scripts, but I want some place online where a live person can tutor me to the next level. Any good suggestions? I'd say Python Tutor?is what you're looking for! And there are many other awesome sources of info, for example StackOverflow. It also helps to invest in a few really good books. I like the one by Mark Summerfield, and the next one on my list is the one by Dough Helmann. From breamoreboy at yahoo.co.uk Tue Feb 26 15:19:43 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 26 Feb 2013 14:19:43 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: <512CBF51.90609@timgolden.me.uk> References: <512CBF51.90609@timgolden.me.uk> Message-ID: On 26/02/2013 13:57, Tim Golden wrote: > On 26/02/2013 13:54, Mark Lawrence wrote: >> On 26/02/2013 13:02, Khalid Al-Ghamdi wrote: >>> Hi All, >>> >>> I'm not a programmer by profession, but I want to learn python. I've got >>> lots of Ideas that want to realize, but I always run into these >>> stupid hiccups where I follow the tutorials and something stupid >>> (known/unkown) is causing things not to work ... frustration ensues... >>> >>> After more than 2 years (on and off) I've got the basics down and >>> have written some scripts, but I want some place online where a live >>> person can tutor me to the next level. Any good suggestions? >>> >>> As always, many thanks for your great advice. >>> >> >> http://pythonmentors.com/ >> > > Umm. No. Sorry, Mark, but that site and the core-mentorship list it > advertises are intended for progammers who want to be helped in the > development *of* Python, not development *in* Python. Ie, otherwise > experienced programmers who are unfamiliar with the Python codebase. > > TJG > Umm. No. Sorry, Tim, but nowhere does the OP state that he wants to develop in Python, hence "The mission of the Python Core Mentor Program is to provide an open and welcoming place to connect students, programmers ? and anyone interested in contributing to the Python Core development." seems to me an excellent fit for "some place online where a live person can tutor me to the next level". -- Cheers. Mark Lawrence From jacklittlemc at yahoo.com Tue Feb 26 15:23:56 2013 From: jacklittlemc at yahoo.com (Jack Little) Date: Tue, 26 Feb 2013 06:23:56 -0800 Subject: [Tutor] Second follow up Message-ID: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> How would I go from one def statement to another? I am developing a text based rpg. Sent from my iPod From emailkgnow at gmail.com Tue Feb 26 15:45:14 2013 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Tue, 26 Feb 2013 17:45:14 +0300 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: <512CBF51.90609@timgolden.me.uk> Message-ID: Hi all and thanks for your suggestions, I was thinking of something like a virtual classroom where I can get live mentoring and answers to my inquiries in a one on one or small group setting. Thanks On Tuesday, February 26, 2013, Mark Lawrence wrote: > On 26/02/2013 13:57, Tim Golden wrote: > >> On 26/02/2013 13:54, Mark Lawrence wrote: >> >>> On 26/02/2013 13:02, Khalid Al-Ghamdi wrote: >>> >>>> Hi All, >>>> >>>> I'm not a programmer by profession, but I want to learn python. I've got >>>> lots of Ideas that want to realize, but I always run into these >>>> stupid hiccups where I follow the tutorials and something stupid >>>> (known/unkown) is causing things not to work ... frustration ensues... >>>> >>>> After more than 2 years (on and off) I've got the basics down and >>>> have written some scripts, but I want some place online where a live >>>> person can tutor me to the next level. Any good suggestions? >>>> >>>> As always, many thanks for your great advice. >>>> >>>> >>> http://pythonmentors.com/ >>> >>> >> Umm. No. Sorry, Mark, but that site and the core-mentorship list it >> advertises are intended for progammers who want to be helped in the >> development *of* Python, not development *in* Python. Ie, otherwise >> experienced programmers who are unfamiliar with the Python codebase. >> >> TJG >> >> > Umm. No. Sorry, Tim, but nowhere does the OP state that he wants to > develop in Python, hence "The mission of the Python Core Mentor Program is > to provide an open and welcoming place to connect students, programmers ? > and anyone interested in contributing to the Python Core development." > seems to me an excellent fit for "some place online where a live person can > tutor me to the next level". > > -- > Cheers. > > Mark Lawrence > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Tue Feb 26 15:55:47 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 26 Feb 2013 15:55:47 +0100 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: <512CBF51.90609@timgolden.me.uk> Message-ID: >> Umm. No. Sorry, Mark, but that site and the core-mentorship list it >> advertises are intended for progammers who want to be helped in the >> development *of* Python, not development *in* Python. Ie, otherwise >> experienced programmers who are unfamiliar with the Python codebase. >> >> TJG >> > > Umm. No. Sorry, Tim, but nowhere does the OP state that he wants to develop in Python, I'll just quote the OP then: " I'm not a programmer by profession, but I want to learn python". That seems pretty clear-cut to me. In addition, the Python Core development is definitely not a place for beginners. Sorry if this reply is all messed up, responding on my phone. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 26 15:57:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2013 14:57:01 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: Message-ID: On 26/02/13 13:02, Khalid Al-Ghamdi wrote: > have written some scripts, but I want some place online where a live > person can tutor me to the next level. Any good suggestions? Well so far as I know there are no dead people on this mailing list.... It's what we are here for. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Tue Feb 26 15:57:47 2013 From: davea at davea.name (Dave Angel) Date: Tue, 26 Feb 2013 09:57:47 -0500 Subject: [Tutor] Second follow up In-Reply-To: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> References: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> Message-ID: <512CCD6B.3090108@davea.name> On 02/26/2013 09:23 AM, Jack Little wrote: > How would I go from one def statement to another? I am developing a text based rpg. > > Sent from my iPod > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > For your next thread, please try to pick a subject line that has something to do with what you're asking, or what you're trying to learn about. A def statement defines a function (or method). Once it's defined, the compiler goes on to the next line, and if that's a def statement, it defines that function. So all you need is a text editor. Just understand that code that will call those functions from the top-level needs to be *after* the definition is complete. Code that calls functions from inside a function does not need to be in any particular order. If this isn't what you want, then try composing a ten-line sample, tell us what environment you're running it in, and what you hoped for, and what it did instead. On the other hand, perhaps you're asking how to make indirect calls to functions. A function object can be stored in a 'variable', simply by assigning it without using parentheses. You can then later call that function by naming the object, and following the object with the parentheses. Simple example follows; def func1(name): print "function1, running with", name def func2(name): print "function2, running with", name funclist = [] funclist.append(func1) funclist.append(func2) funclist.append(func1) funclist[1]("Sam") will call func2, and pass it "Sam" as an argument. Normally, if you're doing this type of thing, you'd be using methods, not functions, but I'm not going to introduce classes unless you're already familiar with them. -- DaveA From alan.gauld at btinternet.com Tue Feb 26 16:00:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Feb 2013 15:00:44 +0000 Subject: [Tutor] Second follow up In-Reply-To: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> References: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> Message-ID: On 26/02/13 14:23, Jack Little wrote: > How would I go from one def statement to another? Type it in. Based on your message that's all I can suggest. Can you explain what you mean? What do you have in mind by a def statement? def foo(): print 'foo' def bar(): print 'bar' Those are two "def statements". You can add as many more as you like? But I suspect that's not really what you mean? > I am developing a text based rpg. I don't see whether/how that makes any difference to anything. Telling us which OS and Python version you are using and what programming tools might help though. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From vytasd2013 at gmail.com Tue Feb 26 16:07:25 2013 From: vytasd2013 at gmail.com (Vytas D.) Date: Tue, 26 Feb 2013 15:07:25 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: Message-ID: Hi, Have you considered O'Reilly Python courses. You have to pay (and it's quite expensive), but you have a tutor to answer questions. The courses are good (tried myself :) ). Vytas -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Feb 26 16:12:58 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 26 Feb 2013 15:12:58 +0000 Subject: [Tutor] Second follow up In-Reply-To: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> References: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> Message-ID: On 26/02/2013 14:23, Jack Little wrote: > How would I go from one def statement to another? I am developing a text based rpg. > > Sent from my iPod > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > I'd like to see your project when it's finished as a text based rocket propelled grenade seems very interesting, or are we talking cross purposes owing to a major lack of data? -- Cheers. Mark Lawrence From steve at pearwood.info Tue Feb 26 17:01:39 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Feb 2013 03:01:39 +1100 Subject: [Tutor] Second follow up In-Reply-To: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> References: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> Message-ID: <512CDC63.3090104@pearwood.info> On 27/02/13 01:23, Jack Little wrote: > How would I go from one def statement to another? I am developing a text based rpg. def first_function(): # write your code here, indented by FOUR spaces or ONE tab def second_function(): # NO INDENT # write your code here, indented by FOUR spaces or ONE tab Does that help? -- Steven From steve at pearwood.info Tue Feb 26 17:11:56 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Feb 2013 03:11:56 +1100 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: <512CBF51.90609@timgolden.me.uk> Message-ID: <512CDECC.4050608@pearwood.info> On 27/02/13 01:19, Mark Lawrence wrote: > On 26/02/2013 13:57, Tim Golden wrote: >> On 26/02/2013 13:54, Mark Lawrence wrote: >>> On 26/02/2013 13:02, Khalid Al-Ghamdi wrote: >>>> Hi All, >>>> >>>> I'm not a programmer by profession, but I want to LEARN PYTHON. [emphasis added] [...] >>> http://pythonmentors.com/ >> >> Umm. No. Sorry, Mark, but that site and the core-mentorship list it >> advertises are intended for progammers who want to be helped in the >> development *of* Python, not development *in* Python. Ie, otherwise >> experienced programmers who are unfamiliar with the Python codebase. >> >> TJG >> > > Umm. No. Sorry, Tim, but nowhere does the OP state that he wants to develop in Python, hence "The mission of the Python Core Mentor Program is to provide an open and welcoming place to connect students, programmers ? and anyone interested in contributing to the Python Core development." seems to me an excellent fit for "some place online where a live person can tutor me to the next level". Mark, the OP states explicitly that he wants to learn Python. I suppose that he *might* intend to learn the language without actually writing any code, but when people say that they want to learn a programming language, it's normally because they intend to, you know, program. As in develop code. Using the language he intends to learn. Which is Python. The programming language, not the snake. For the avoidance of doubt. :-P Python-mentors is completely inappropriate for a beginner who doesn't know the language. The core developers are too busy to be hand-holding a newbie who doesn't know any Python, and somebody who doesn't know any Python can't triage bugs, write documentation or tests, or write Python code for the standard library. -- Steven From steve at pearwood.info Tue Feb 26 17:13:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 27 Feb 2013 03:13:38 +1100 Subject: [Tutor] Second follow up In-Reply-To: References: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> Message-ID: <512CDF32.90909@pearwood.info> On 27/02/13 02:12, Mark Lawrence wrote: > On 26/02/2013 14:23, Jack Little wrote: >> How would I go from one def statement to another? I am developing a text based rpg. > > I'd like to see your project when it's finished as a text based rocket propelled grenade seems very interesting, or are we talking cross purposes owing to a major lack of data? RPG: Role Playing Game. -- Steven From breamoreboy at yahoo.co.uk Tue Feb 26 17:52:29 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 26 Feb 2013 16:52:29 +0000 Subject: [Tutor] Second follow up In-Reply-To: <512CDC63.3090104@pearwood.info> References: <76176498-7E66-4179-87A2-DA87BF796ABA@yahoo.com> <512CDC63.3090104@pearwood.info> Message-ID: On 26/02/2013 16:01, Steven D'Aprano wrote: > On 27/02/13 01:23, Jack Little wrote: >> How would I go from one def statement to another? I am developing a >> text based rpg. > > > def first_function(): > # write your code here, indented by FOUR spaces or ONE tab > > > def second_function(): # NO INDENT > # write your code here, indented by FOUR spaces or ONE tab > > > Does that help? > > Get thee behind me Satan/Steven, tabs indeed :) -- Cheers. Mark Lawrence From fomcl at yahoo.com Tue Feb 26 22:00:59 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 26 Feb 2013 13:00:59 -0800 (PST) Subject: [Tutor] There's a Programmer in Me In-Reply-To: <512CDECC.4050608@pearwood.info> References: <512CBF51.90609@timgolden.me.uk> <512CDECC.4050608@pearwood.info> Message-ID: <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> ? > The core developers are too busy to be hand-holding a newbie who > doesn't know any Python, Well, in a way they *can*: I find it very inspiring to read the source code of Python (the .py files), though I don't do this as often as I should. What I like about R: if I do 'print(func)' (or fix(func)), it prints the source code of the function. It would be cool if Python had something similar. Instead Python prints the not-so-informative From hugo.yoshi at gmail.com Tue Feb 26 23:31:23 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 26 Feb 2013 22:31:23 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> References: <512CBF51.90609@timgolden.me.uk> <512CDECC.4050608@pearwood.info> <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: On Tue, Feb 26, 2013 at 9:00 PM, Albert-Jan Roskam wrote: > > > The core developers are too busy to be hand-holding a newbie who > > doesn't know any Python, > > Well, in a way they *can*: I find it very inspiring to read the source > code of Python (the .py files), though I don't do this as often as I should. > > What I like about R: if I do 'print(func)' (or fix(func)), it prints the > source code of the function. It would be cool if Python had something > similar. Instead Python prints the not-so-informative 0xa82fae4> > > I don't think you'd want the generic 'print' to do this (though repr() might be a good candidate). In any case, IPython can do it with %psource: http://ipython.org/ipython-doc/rel-0.10.2/html/interactive/tutorial.html#explore-your-objects -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Feb 27 01:49:21 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Feb 2013 19:49:21 -0500 Subject: [Tutor] There's a Programmer in Me In-Reply-To: <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> References: <512CBF51.90609@timgolden.me.uk> <512CDECC.4050608@pearwood.info> <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: On Tue, Feb 26, 2013 at 4:00 PM, Albert-Jan Roskam wrote: > > What I like about R: if I do 'print(func)' (or fix(func)), it prints the > source code of the function. It would be cool if Python had something > similar. Instead Python prints the not-so-informative > You can use inspect.getsource(obj) if obj is a module, class, method, function, traceback, frame, or code that has a source file (e.g. __file__, co_filename) and is defined normally (e.g. class, def): >>> import inspect >>> def printsrc(obj): print inspect.getsource(obj) >>> import antigravity >>> printsrc(antigravity) import webbrowser webbrowser.open("http://xkcd.com/353/") From eryksun at gmail.com Wed Feb 27 02:09:11 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Feb 2013 20:09:11 -0500 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: <512CBF51.90609@timgolden.me.uk> <512CDECC.4050608@pearwood.info> <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: On Tue, Feb 26, 2013 at 7:49 PM, eryksun wrote: > > You can use inspect.getsource(obj) if obj is a module, class, method, > function, traceback, frame, or code that has a source file (e.g. > __file__, co_filename) and is defined normally (e.g. class, def): > > >>> import inspect > >>> def printsrc(obj): print inspect.getsource(obj) You ca also use a pager (uses "less" if available; "more" on Windows): >>> import inspect, pydoc >>> def showsrc(obj): pydoc.getpager()(inspect.getsource(obj)) ... >>> showsrc(inspect) From fomcl at yahoo.com Wed Feb 27 10:10:07 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 27 Feb 2013 01:10:07 -0800 (PST) Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: <512CBF51.90609@timgolden.me.uk> <512CDECC.4050608@pearwood.info> <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> Message-ID: <1361956207.69349.YahooMailNeo@web163806.mail.gq1.yahoo.com> > On Tue, Feb 26, 2013 at 4:00 PM, Albert-Jan Roskam > wrote: >> >> What I like about R: if I do 'print(func)' (or fix(func)), it > prints the >> source code of the function. It would be cool if Python had something >> similar. Instead Python prints the not-so-informative >> > > You can use inspect.getsource(obj) if obj is a module, class, method, > function, traceback, frame, or code that has a source file (e.g. > __file__, co_filename) and is defined normally (e.g. class, def): > > ? ? >>> import inspect > ? ? >>> def printsrc(obj): print inspect.getsource(obj) > > ? ? >>> import antigravity > ? ? >>> printsrc(antigravity) > > ? ? import webbrowser > > ? ? webbrowser.open(http://xkcd.com/353/) Ahh, thank you! I like the %psource magic word, but until I get IPython installed in the office I'll use inspect.getsource. import inspect, soul print inspect.getsource(soul.getsoul) import webbrowser webbrowser.open(http://xkcd.com/413/)? ;-)) From femibanjo at hotmail.com Wed Feb 27 12:19:43 2013 From: femibanjo at hotmail.com (Femi Banjo) Date: Wed, 27 Feb 2013 11:19:43 +0000 Subject: [Tutor] There's a Programmer in Me In-Reply-To: <1361956207.69349.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: , <512CBF51.90609@timgolden.me.uk>, <512CDECC.4050608@pearwood.info>, <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com>, , <1361956207.69349.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: coursera, udacity & edx all have decent Python courses for beginners and very good support on forums etc and they're all free > Date: Wed, 27 Feb 2013 01:10:07 -0800 > From: fomcl at yahoo.com > To: eryksun at gmail.com > CC: tutor at python.org > Subject: Re: [Tutor] There's a Programmer in Me > > > > > On Tue, Feb 26, 2013 at 4:00 PM, Albert-Jan Roskam > > wrote: > >> > >> What I like about R: if I do 'print(func)' (or fix(func)), it > > prints the > >> source code of the function. It would be cool if Python had something > >> similar. Instead Python prints the not-so-informative > >> > > > > You can use inspect.getsource(obj) if obj is a module, class, method, > > function, traceback, frame, or code that has a source file (e.g. > > __file__, co_filename) and is defined normally (e.g. class, def): > > > > >>> import inspect > > >>> def printsrc(obj): print inspect.getsource(obj) > > > > >>> import antigravity > > >>> printsrc(antigravity) > > > > import webbrowser > > > > webbrowser.open(http://xkcd.com/353/) > > Ahh, thank you! I like the %psource magic word, but until I get IPython installed in the office I'll use inspect.getsource. > import inspect, soul > print inspect.getsource(soul.getsoul) > import webbrowser > webbrowser.open(http://xkcd.com/413/) ;-)) > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Wed Feb 27 18:08:21 2013 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Wed, 27 Feb 2013 20:08:21 +0300 Subject: [Tutor] There's a Programmer in Me In-Reply-To: References: <512CBF51.90609@timgolden.me.uk> <512CDECC.4050608@pearwood.info> <1361912459.95429.YahooMailNeo@web163802.mail.gq1.yahoo.com> <1361956207.69349.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: Thanks everyone. On Wednesday, February 27, 2013, Femi Banjo wrote: > coursera, udacity & edx all have decent Python courses for beginners and > very good support on forums etc and they're all free > > > Date: Wed, 27 Feb 2013 01:10:07 -0800 > > From: fomcl at yahoo.com > > To: eryksun at gmail.com > > CC: tutor at python.org > > Subject: Re: [Tutor] There's a Programmer in Me > > > > > > > > > On Tue, Feb 26, 2013 at 4:00 PM, Albert-Jan Roskam > > > > > wrote: > > >> > > >> What I like about R: if I do 'print(func)' (or fix(func)), it > > > prints the > > >> source code of the function. It would be cool if Python had something > > >> similar. Instead Python prints the not-so-informative > > >> > > > > > > You can use inspect.getsource(obj) if obj is a module, class, method, > > > function, traceback, frame, or code that has a source file (e.g. > > > __file__, co_filename) and is defined normally (e.g. class, def): > > > > > > >>> import inspect > > > >>> def printsrc(obj): print inspect.getsource(obj) > > > > > > >>> import antigravity > > > >>> printsrc(antigravity) > > > > > > import webbrowser > > > > > > webbrowser.open(http://xkcd.com/353/) > > > > Ahh, thank you! I like the %psource magic word, but until I get IPython > installed in the office I'll use inspect.getsource. > > import inspect, soul > > print inspect.getsource(soul.getsoul) > > import webbrowser > > webbrowser.open(http://xkcd.com/413/) ;-)) > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org 'Tutor at python.org');> > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From doanviettrung at gmail.com Thu Feb 28 03:27:46 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Thu, 28 Feb 2013 13:27:46 +1100 Subject: [Tutor] timeit: 10million x 1 Vs 1million x 10 Message-ID: Dear tutors My function below simply populates a large dict. When measured by timeit populating 10 million items once, versus populating 1 million items ten times, the times are noticeably different: --- import timeit N = 10000000 # This constant's value is either 10 million or 1 million testDict = {} def writeDict(N): for i in xrange(N): testDict[i] = [i, [i + 1, i + 2], i + 3] print timeit.Timer('f(N)', 'from __main__ import N, writeDict as f').timeit(1) # the 'number' parameter is either 1 or 10 --- Result from 3 runs of 10 million x 1 time: 12.7655465891, 13.1248426525, 12.1611512459 Result from 3 runs of 1 million x 10 times: 14.3727692498, 14.3825673988, 14.4390314636 I ran Python 2.7 on Pycharm on Windows 7. My guess is that this discrepancy is a result of either how some sort of overhead in timeit, or of Python having to allocate memory space for a dict 10 times. What do you think, and how to find out for sure? Second (for me, this question is more important), how to improve performance? (I tried a tuple rather than a list for the dict values, it was slightly faster, but I need dict items to be mutable) Thanks Trung Doan -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 28 09:18:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 28 Feb 2013 08:18:07 +0000 Subject: [Tutor] timeit: 10million x 1 Vs 1million x 10 In-Reply-To: References: Message-ID: On 28/02/13 02:27, DoanVietTrungAtGmail wrote: > --- > import timeit > > N = 10000000 # This constant's value is either 10 million or 1 million > testDict = {} > def writeDict(N): > for i in xrange(N): > testDict[i] = [i, [i + 1, i + 2], i + 3] > print timeit.Timer('f(N)', 'from __main__ import N, writeDict as > f').timeit(1) # the 'number' parameter is either 1 or 10 > > --- > > My guess is that this discrepancy is a result of either how some sort of > overhead in timeit, or of Python having to allocate memory space for a > dict 10 times. What do you think, and how to find out for sure? There are several extra overheads including calling the function multiple times and deleting the structures you created each time. > Second (for me, this question is more important), how to improve > performance? In this specific case the best improvement is not to create the dict at all. Since the values are all derived from the key all you need is to store the keys and calculate the values when needed. But I suspect the real world use case is not that simple... You could try moving N and the dict inside the function - local variables are usually slightly faster than globals. You could also try using a generator for the dict. I've no idea how much faster/slower that would be, with all things performance related testing is the only sure way. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Thu Feb 28 11:36:50 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 28 Feb 2013 21:36:50 +1100 Subject: [Tutor] timeit: 10million x 1 Vs 1million x 10 In-Reply-To: References: Message-ID: <512F3342.5030909@pearwood.info> On 28/02/13 13:27, DoanVietTrungAtGmail wrote: > Dear tutors > > My function below simply populates a large dict. When measured by timeit > populating 10 million items once, versus populating 1 million items ten > times, the times are noticeably different: I cannot replicate your results. When I try it, I get more or less the same result each time: py> for count, N in ((1, 10000000), (10, 1000000)): ... t = timeit.Timer('f(N)', 'from __main__ import N, writeDict as f') ... print min(t.repeat(number=count)) ... 7.2105910778 7.17914915085 The difference is insignificant. However, I did notice that when I ran your code, memory consumption went to 80% on my computer, and the load average exceeded 4. I suggest that perhaps the results you are seeing have something to do with your operating system's response to memory usage, or some other external factor. [...] > My guess is that this discrepancy is a result of either how some sort of > overhead in timeit, or of Python having to allocate memory space for a dict > 10 times. What do you think, and how to find out for sure? Whatever the answer is, it is neither of the above. Firstly, while timeit does have some overhead, it is very small. After all, timeit is designed for timing tiny sub-microsecond code snippets. You can get an idea of timeit's overhead like this: py> from timeit import Timer py> t1 = Timer("x = 2") py> t2 = Timer("x = 1;x = 2") py> min(t1.repeat()) 0.048729896545410156 py> min(t2.repeat()) 0.06900882720947266 If timeit had no overhead at all, t2 should take twice as long as t1 since it has two instructions rather than one. But it doesn't, so we can calculate the (approximate) overhead with a bit of maths: overhead + t = 0.0486 overhead + 2t = 0.0690 Solving this gives me an overhead of 0.0282s, which is per the one million loops that timeit does by default. So as you can see, it's quite small: about 30 nanoseconds on my computer per loop. Even if it was a million times greater, it wouldn't be enough to explain the results you see. As for your other suggestion, about the memory space allocation, it is also unlikely to be correct. You are using the same dict on every test! On the first run, Python has to reallocate memory to make the dict big enough for 10 million entries. After that, the dict is already resized and never gets any bigger. > Second (for me, this question is more important), how to improve > performance? (I tried a tuple rather than a list for the dict values, it > was slightly faster, but I need dict items to be mutable) Firstly, are you sure you need to improve performance? Secondly, performance of what? Have you profiled your application to see which parts are slow, or are you just guessing? As it stands, I cannot advise you how to speed your application up, because I don't know what it does or what bits are slow. But I doubt very much that the slow part is storing a small list inside a dict. -- Steven