From josep.m.fontana at gmail.com Mon Nov 1 13:48:43 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Mon, 1 Nov 2010 13:48:43 +0100 Subject: [Tutor] Problems with partial string matching In-Reply-To: <4CC48E9B.6080302@ieee.org> References: <4CC48E9B.6080302@ieee.org> Message-ID: Thanks a lot Dave and Joel, > You call re.sub(), but don't do anything with the result. > > Where do you call os.rename() ? Yes, indeed, as you suggested what was missing was the use of os.rename() to apply the substitution to the actual file names. I incorporated that and I changed the loop that I had produced in my first version because it wasn't doing what it was supposed to do. Doing that definitely gets me closer to my goal but I'm encountering a strange problem. Well, strange to me, that is. I'm sure that more experienced programmers like the people who hang out in this list will immediately see what is going on. First, here's the code: ------------------------------ import os, sys, glob, re #What follows creates a dictionary with the form {'name':'year'} out of a csv file called FileNameYear.txt which has a string of the form 'A-01,1374' on each line. The substring before the comma is the code for the text that appears at the beginning of the name of the file containing the given text and the substring after the comma indicates the year in which the text was written. fileNameYear = open(r'/Volumes/DATA/Documents/workspace/MyCorpus/CORPUS_TEXT_LATIN_1/FileNameYear.txt', "U").readlines() name_year = {} for line in fileNameYear: #File objects have built-in iteration name, year = line.strip().split(',') name_year[name] = year #effectively creates the dictionary by creating keys with the element 'name' returned by the loop and assigning them values corresponding to the element 'year' --> !d[key] = value" means Set d[key] to value. os.getcwd() os.chdir('/Volumes/DATA/Documents/workspace/MyCorpus/CORPUS_TEXT_LATIN_1') file_names = glob.glob('*.txt') for name in name_year: for name_of_file in file_names: if name_of_file.startswith(name): os.rename(name_of_file, re.sub('__', '__' + year, name_of_file)) --------------- What this produces is a change in the names of the files which is not exactly the desired result. The new names of the files have the following structure: 'A-01-name1__1499.txt' , 'A-02-name2__1499.txt', 'A-05-name3__1499.txt', ... 'I-01-name14__1499.txt', ...Z-30-name1344__1499.txt' That is, only the year '1499' of the many possible years has been added in the substitution. I can understand that I've done something wrong in the loop and the iteration over the values of the dictionary (i.e. the strings representing the years) is not working properly. What I don't understand is why precisely '1499' is the string that is obtained in all the cases. I've been trying to figure out how the loop proceeds and this doesn't make sense to me because the year '1499' appears as the value for dictionary item number 34. Because of the order of the dictionary entries and the way I've designed the loop (which I admit might not be the most efficient way to process these data), the first match would correspond to a file that starts with the initial code 'I-02'. The dictionary value for this key is '1399', not '1499'. '1499' is not even the value that would correspond to key 'A-01' which is the first file in the directory according to the alphabetical order ('A-02', the second file in the directory does correspond to value '1499', though). So besides being able to explain why '1499' is the string that winds up added to the file name, my question is, how do I set up the loop so that the string representing the appropriate year is added to each file name? Thanks a lot in advance for your help (since it usually takes me a while to answer). Josep M. > On 2:59 PM, Josep M. Fontana wrote: >> >> Hi, >> >> As I said in another message with the heading "Using contents of a >> document to change file names", I'm trying to learn Python "by doing" >> and I was working on a little project where I had to change the names >> >> I run this and I don't get any errors. The names of the files in the >> directory, however, are not changed. What am I doing wrong? >> >> As always, your help is greatly appreciated. >> >> >> Josep M. >> > You call re.sub(), but don't do anything with the result. > > Where do you call os.rename() ? > > DaveA > > From davea at ieee.org Mon Nov 1 14:38:03 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 01 Nov 2010 09:38:03 -0400 Subject: [Tutor] Problems with partial string matching In-Reply-To: References: <4CC48E9B.6080302@ieee.org> Message-ID: <4CCEC2BB.1080801@ieee.org> On 11/1/2010 8:48 AM, Josep M. Fontana wrote: > Thanks a lot Dave and Joel, > > >> You call re.sub(), but don't do anything with the result. >> >> Where do you call os.rename() ? > > Yes, indeed, as you suggested what was missing was the use of > os.rename() to apply the substitution to the actual file names. I > incorporated that and I changed the loop that I had produced in my > first version because it wasn't doing what it was supposed to do. > > Doing that definitely gets me closer to my goal but I'm encountering a > strange problem. Well, strange to me, that is. I'm sure that more > experienced programmers like the people who hang out in this list will > immediately see what is going on. First, here's the code: > > ------------------------------ > import os, sys, glob, re > #What follows creates a dictionary with the form {'name':'year'} out > of a csv file called FileNameYear.txt which has a string of the form > 'A-01,1374' on each line. The substring before the comma is the code > for the text that appears at the beginning of the name of the file > containing the given text and the substring after the comma indicates > the year in which the text was written. > fileNameYear = open(r'/Volumes/DATA/Documents/workspace/MyCorpus/CORPUS_TEXT_LATIN_1/FileNameYear.txt', > "U").readlines() > name_year = {} > for line in fileNameYear: #File objects have built-in iteration > name, year = line.strip().split(',') > name_year[name] = year #effectively creates the dictionary by > creating keys with the element 'name' returned by the loop and > assigning them values corresponding to the element 'year' --> !d[key] > = value" means Set d[key] to value. > os.getcwd() > os.chdir('/Volumes/DATA/Documents/workspace/MyCorpus/CORPUS_TEXT_LATIN_1') > file_names = glob.glob('*.txt') > for name in name_year: > for name_of_file in file_names: > if name_of_file.startswith(name): > os.rename(name_of_file, re.sub('__', '__' + year, name_of_file)) > --------------- > > What this produces is a change in the names of the files which is not > exactly the desired result. The new names of the files have the > following structure: > > 'A-01-name1__1499.txt' , 'A-02-name2__1499.txt', > 'A-05-name3__1499.txt', ... 'I-01-name14__1499.txt', > ...Z-30-name1344__1499.txt' > > That is, only the year '1499' of the many possible years has been > added in the substitution. I can understand that I've done something > wrong in the loop and the iteration over the values of the dictionary > (i.e. the strings representing the years) is not working properly. > What I don't understand is why precisely '1499' is the string that is > obtained in all the cases. > > I've been trying to figure out how the loop proceeds and this doesn't > make sense to me because the year '1499' appears as the value for > dictionary item number 34. Because of the order of the dictionary > entries and the way I've designed the loop (which I admit might not be > the most efficient way to process these data), the first match would > correspond to a file that starts with the initial code 'I-02'. The > dictionary value for this key is '1399', not '1499'. '1499' is not > even the value that would correspond to key 'A-01' which is the first > file in the directory according to the alphabetical order ('A-02', the > second file in the directory does correspond to value '1499', though). > > So besides being able to explain why '1499' is the string that winds > up added to the file name, my question is, how do I set up the loop so > that the string representing the appropriate year is added to each > file name? > > Thanks a lot in advance for your help (since it usually takes me a > while to answer). > > Josep M. > (You top-posted, so I had to remove the out-of-order earlier portion.) I've not tried to run the code, but I think I can see the problem. Since you never assign 'year' inside the loop(s), it's always the same. And it's whatever the last value it had in the earlier loop. The simplest cure would be to fix the outer loop for name, year in name_year.items(): Alternatively, and maybe easier to read: for name in name_year: year = name_year[name] HTH DaveA From samueldechamplain at gmail.com Mon Nov 1 18:01:16 2010 From: samueldechamplain at gmail.com (Samuel de Champlain) Date: Mon, 1 Nov 2010 13:01:16 -0400 Subject: [Tutor] scope, visibility? Message-ID: I am learning python. To practice, I am coding a hangman application in pyGTK. Here are my imports: import pygtk pygtk.require('2.0') import gtk import random Here is my main class: class PenduGTK: Inside the class is a method with a bit of code: def masque(chaine,liInd=0): i = 0 lenght = len(chaine) The offending line is the one with len(chaine) Here are the error messages: penduGTK.py Traceback (most recent call last): File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback self.lblMot.set_text(self.masque(self.motChoisi)) File "/home/xxx/bin/penduGTK.py", line 44, in masque lenght = len(chaine) AttributeError: PenduGTK instance has no attribute '__len__' I would think it has to do with namespaces, scopes and visibility. But how do I refer to built-in functions from inside a class? -------------- next part -------------- An HTML attachment was scrubbed... URL: From josep.m.fontana at gmail.com Mon Nov 1 18:53:32 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Mon, 1 Nov 2010 18:53:32 +0100 Subject: [Tutor] Problems with partial string matching In-Reply-To: <4CCEC2BB.1080801@ieee.org> References: <4CC48E9B.6080302@ieee.org> <4CCEC2BB.1080801@ieee.org> Message-ID: Hi Dave, On Mon, Nov 1, 2010 at 2:38 PM, Dave Angel wrote: > (You top-posted, so I had to remove the out-of-order earlier portion.) > > I've not tried to run the code, but I think I can see the problem. Since > you never assign 'year' inside the loop(s), it's always the same. And it's > whatever the last value it had in the earlier loop. > > The simplest cure would be to fix the outer loop > > for name, year in name_year.items(): > > Alternatively, and maybe easier to read: > > for name in name_year: > year = name_year[name] Sorry about the top-posting. Sometimes it seems that a little top-posting might make things easier (I hate to have to go through long quotes) but you are totally right, netiquette is netiquette. I'm still puzzled as to why that particular value was the one picked up but what's important is that you provided the solution for the problem in the loop. Now it works perfectly. Thank you very much! Josep M. From davea at ieee.org Mon Nov 1 18:59:05 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 01 Nov 2010 13:59:05 -0400 Subject: [Tutor] Problems with partial string matching In-Reply-To: References: <4CC48E9B.6080302@ieee.org> <4CCEC2BB.1080801@ieee.org> Message-ID: <4CCEFFE9.2030706@ieee.org> On 11/1/2010 1:53 PM, Josep M. Fontana wrote: > Hi Dave, > > On Mon, Nov 1, 2010 at 2:38 PM, Dave Angel wrote: > >> (You top-posted, so I had to remove the out-of-order earlier portion.) >> >> I've not tried to run the code, but I think I can see the problem. Since >> you never assign 'year' inside the loop(s), it's always the same. And it's >> whatever the last value it had in the earlier loop. >> >> The simplest cure would be to fix the outer loop >> >> for name, year in name_year.items(): >> >> Alternatively, and maybe easier to read: >> >> for name in name_year: >> year = name_year[name] > Sorry about the top-posting. Sometimes it seems that a little > top-posting might make things easier (I hate to have to go through > long quotes) but you are totally right, netiquette is netiquette. > > I'm still puzzled as to why that particular value was the one picked > up but what's important is that you provided the solution for the > problem in the loop. Now it works perfectly. Thank you very much! > > Josep M. > The only time year is bound is in the previous loop, as I said. It's the line that goes: name, year = line.strip..... So year is whatever it was the last time through that loop. DaveA From davea at ieee.org Mon Nov 1 19:14:33 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 01 Nov 2010 14:14:33 -0400 Subject: [Tutor] scope, visibility? In-Reply-To: References: Message-ID: <4CCF0389.10702@ieee.org> On 2:59 PM, Samuel de Champlain wrote: > I am learning python. To practice, I am coding a hangman application in > pyGTK. > Here are my imports: > > import pygtk > pygtk.require('2.0') > import gtk > import random > > Here is my main class: > > class PenduGTK: > > Inside the class is a method with a bit of code: > > def masque(chaine,liInd=0): > > i = 0 > lenght = len(chaine) > > The offending line is the one with len(chaine) > > Here are the error messages: > > penduGTK.py > Traceback (most recent call last): > File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback > self.lblMot.set_text(self.masque(self.motChoisi)) > File "/home/xxx/bin/penduGTK.py", line 44, in masque > lenght = len(chaine) > AttributeError: PenduGTK instance has no attribute '__len__' > > I would think it has to do with namespaces, scopes and visibility. But how > do I refer to built-in functions from inside a class? > You're correctly referring to the built-in function len(). But that function assumes that the object it gets as an argument has a __len__() method. List, string, tuple all do. But perhaps PenduGTK does not. You don't show us the whole class. Your real problem is probably that you're missing self as the first argument. So where you think chaine is a string, it's actually an instance. DaveA From evert.rol at gmail.com Mon Nov 1 19:15:49 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 1 Nov 2010 19:15:49 +0100 Subject: [Tutor] scope, visibility? In-Reply-To: References: Message-ID: <054046EC-CC0E-48B4-A85E-083FCE7EE5AB@gmail.com> > Here is my main class: > > class PenduGTK: > > Inside the class is a method with a bit of code: > > def masque(chaine,liInd=0): > > i = 0 > lenght = len(chaine) > > The offending line is the one with len(chaine) > > Here are the error messages: > > penduGTK.py > Traceback (most recent call last): > File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback > self.lblMot.set_text(self.masque(self.motChoisi)) > File "/home/xxx/bin/penduGTK.py", line 44, in masque > lenght = len(chaine) > AttributeError: PenduGTK instance has no attribute '__len__' A method takes as its first argument a reference to the class. That is, in 'def some_method(blah1, blah2, blah3)', blah1 would be a reference to the class in which some_method is defined. If you look at the error message, you see Python complains that the PenduGTK instance has no __len__ attribute, meaning 'chaine' is a PenduGTK instance: it's the first argument in the method, taking a reference to the class. See eg http://diveintopython.org/object_oriented_framework/defining_classes.html (also, carefully read the error and think what it could mean: it has a lot of hints to solve your problem). Thus, define a method with an extra (first) argument. This is usually called self: def masque(self, chaine, liInd=0): Last note on a totally different thing, because this confused me a bit: preferably avoid avoid the lowercase L, lowercase i and uppercase I next to each other. It's very hard to read. See eg http://www.python.org/dev/peps/pep-0008/ (section 'Names to Avoid'). To me, it initially read something like iiind=0. Which is ok, as long as I don't have to work with the code. But it may also bite you some day. > I would think it has to do with namespaces, scopes and visibility. But how do I refer to built-in functions from inside a class? Just as you did above: len(chaine). But since that wasn't your problem, I guess this answer is rather meaningless. Cheers, Evert From josep.m.fontana at gmail.com Mon Nov 1 20:38:06 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Mon, 1 Nov 2010 20:38:06 +0100 Subject: [Tutor] Problems with partial string matching In-Reply-To: <4CCEFFE9.2030706@ieee.org> References: <4CC48E9B.6080302@ieee.org> <4CCEC2BB.1080801@ieee.org> <4CCEFFE9.2030706@ieee.org> Message-ID: > The only time year is bound is in the previous loop, as I said. ?It's the > line that goes: > ? ? name, year = line.strip..... > > So year is whatever it was the last time through that loop. OK, this makes sense. Indeed that is the value in the last entry for the dictionary. Thanks a lot again. Josep M. From g.nius.ck at gmail.com Mon Nov 1 21:01:39 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 16:01:39 -0400 Subject: [Tutor] Complete Shutdown Message-ID: <4CCF1CA3.3050305@gmail.com> Dear Tutors, How do I completely shutdown a computer without administrative rights using a simple python script. Sincerely, Me, Myself, and I From g.nius.ck at gmail.com Mon Nov 1 21:05:57 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 16:05:57 -0400 Subject: [Tutor] rights Message-ID: <4CCF1DA5.2020904@gmail.com> Dear Tutors, How do you give a script right to read a folder? From vince at vinces.ca Mon Nov 1 21:10:43 2010 From: vince at vinces.ca (Vince Spicer) Date: Mon, 1 Nov 2010 14:10:43 -0600 Subject: [Tutor] rights In-Reply-To: <4CCF1DA5.2020904@gmail.com> References: <4CCF1DA5.2020904@gmail.com> Message-ID: On Mon, Nov 1, 2010 at 2:05 PM, Chris King wrote: > Dear Tutors, > How do you give a script right to read a folder? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Which Operation System? In linux the user that is running the script must be have read access chmod +r folder -- Vince Spicer -- Sent from Ubuntu -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 1 22:20:42 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Nov 2010 21:20:42 -0000 Subject: [Tutor] Complete Shutdown References: <4CCF1CA3.3050305@gmail.com> Message-ID: "Chris King" wrote > How do I completely shutdown a computer without administrative > rights using a simple python script. If you have such a computer get rid of it, it fails the most basic test of a secure operating system. No program that runs upon it could ever be relied upon! The whole concept is evil. Administrator rights are required for good reason and are a protection against bad things happening to your data and programs. Work with it not against it and be grateful it's there. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Nov 1 22:21:47 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 1 Nov 2010 21:21:47 -0000 Subject: [Tutor] rights References: <4CCF1DA5.2020904@gmail.com> Message-ID: "Chris King" wrote > How do you give a script right to read a folder? You give the user account executing the script rights to read the folder. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Mon Nov 1 22:41:56 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 17:41:56 -0400 Subject: [Tutor] pythonpath Message-ID: <4CCF3424.8010407@gmail.com> Dear Tutors, When I try to import a module, how can I make it look in certain directories for them easily. Sincerely, Chris From vince at vinces.ca Mon Nov 1 22:47:47 2010 From: vince at vinces.ca (Vince Spicer) Date: Mon, 1 Nov 2010 15:47:47 -0600 Subject: [Tutor] pythonpath In-Reply-To: <4CCF3424.8010407@gmail.com> References: <4CCF3424.8010407@gmail.com> Message-ID: On Mon, Nov 1, 2010 at 3:41 PM, Chris King wrote: > Dear Tutors, > When I try to import a module, how can I make it look in certain > directories for them easily. > Sincerely, > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hello Chris You can manage you path from within your script, import sys sys.path.append("/home/user/lib") Or in bash you can edit your $PYTHONPATH env variable echo $PYTHONPATH -- Vince Spicer -- Sent from Ubuntu -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Mon Nov 1 22:48:40 2010 From: karim.liateni at free.fr (Karim) Date: Mon, 01 Nov 2010 22:48:40 +0100 Subject: [Tutor] pythonpath In-Reply-To: <4CCF3424.8010407@gmail.com> References: <4CCF3424.8010407@gmail.com> Message-ID: <4CCF35B8.6040200@free.fr> On 11/01/2010 10:41 PM, Chris King wrote: > Dear Tutors, > When I try to import a module, how can I make it look in certain > directories for them easily. > Sincerely, > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hello, PYTHONPATH environment variable set to /path/to/you/libs. Regards Karim From g.nius.ck at gmail.com Mon Nov 1 22:57:29 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 17:57:29 -0400 Subject: [Tutor] pythonpath In-Reply-To: References: <4CCF3424.8010407@gmail.com> Message-ID: <4CCF37C9.9030306@gmail.com> On 11/1/2010 5:47 PM, Vince Spicer wrote: > > > On Mon, Nov 1, 2010 at 3:41 PM, Chris King @gmail.com > wrote: > > Dear Tutors, > When I try to import a module, how can I make it look in > certain directories for them easily. > Sincerely, > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > Hello Chris > > You can manage you path from within your script, > > import sys > sys.path.append("/home/user/lib") > > Or in bash you can edit your $PYTHONPATH env variable > echo $PYTHONPATH > > > -- > Vince Spicer > > > -- > Sent from Ubuntu > it didn't work -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Nov 1 22:58:41 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 17:58:41 -0400 Subject: [Tutor] pythonpath In-Reply-To: References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> Message-ID: <4CCF3811.2030803@gmail.com> On 11/1/2010 5:57 PM, Vince Spicer wrote: > > > On Mon, Nov 1, 2010 at 3:54 PM, Chris King @gmail.com > wrote: > > On 11/1/2010 5:47 PM, Vince Spicer wrote: >> >> >> On Mon, Nov 1, 2010 at 3:41 PM, Chris King > @gmail.com > wrote: >> >> Dear Tutors, >> When I try to import a module, how can I make it look in >> certain directories for them easily. >> Sincerely, >> Chris >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> Hello Chris >> >> You can manage you path from within your script, >> >> import sys >> sys.path.append("/home/user/lib") >> >> Or in bash you can edit your $PYTHONPATH env variable >> echo $PYTHONPATH >> >> >> -- >> Vince Spicer >> >> >> -- >> Sent from Ubuntu >> > So doing it in cmd windows will permanently change it? > > > > the first way with work for Window, the second is for Linux or posix > systems > > Sorry I can't help with PYTHONPATH on windows. > > -- > Vince Spicer > > > -- > Sent from Ubuntu > I want a permanent change. -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Nov 1 23:00:17 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 18:00:17 -0400 Subject: [Tutor] Complete Shutdown In-Reply-To: References: <4CCF1CA3.3050305@gmail.com> Message-ID: <4CCF3871.8080006@gmail.com> On 11/1/2010 5:20 PM, Alan Gauld wrote: > > "Chris King" wrote > >> How do I completely shutdown a computer without administrative >> rights using a simple python script. > > If you have such a computer get rid of it, it fails the most basic test > of a secure operating system. No program that runs upon it could > ever be relied upon! > > The whole concept is evil. > > Administrator rights are required for good reason and are a protection > against bad things happening to your data and programs. Work with > it not against it and be grateful it's there. > > I restarted the whole system with a script. Why couldn't I shut it down? From vince at vinces.ca Mon Nov 1 23:00:38 2010 From: vince at vinces.ca (Vince Spicer) Date: Mon, 1 Nov 2010 16:00:38 -0600 Subject: [Tutor] pythonpath In-Reply-To: <4CCF3811.2030803@gmail.com> References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> <4CCF3811.2030803@gmail.com> Message-ID: On Mon, Nov 1, 2010 at 3:58 PM, Chris King wrote: > On 11/1/2010 5:57 PM, Vince Spicer wrote: > > > > On Mon, Nov 1, 2010 at 3:54 PM, Chris King wrote: > >> On 11/1/2010 5:47 PM, Vince Spicer wrote: >> >> >> >> On Mon, Nov 1, 2010 at 3:41 PM, Chris King wrote: >> >>> Dear Tutors, >>> When I try to import a module, how can I make it look in certain >>> directories for them easily. >>> Sincerely, >>> Chris >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> Hello Chris >> >> You can manage you path from within your script, >> >> import sys >> sys.path.append("/home/user/lib") >> >> Or in bash you can edit your $PYTHONPATH env variable >> echo $PYTHONPATH >> >> >> -- >> Vince Spicer >> >> >> -- >> Sent from Ubuntu >> >> So doing it in cmd windows will permanently change it? >> > > > the first way with work for Window, the second is for Linux or posix > systems > > Sorry I can't help with PYTHONPATH on windows. > > -- > Vince Spicer > > > -- > Sent from Ubuntu > > I want a permanent change. > There is probably a Windows alternative to env variables and PYTHONPATH, Google may help. -- Vince Spicer -- Sent from Ubuntu -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Mon Nov 1 23:03:30 2010 From: washakie at gmail.com (John) Date: Mon, 1 Nov 2010 23:03:30 +0100 Subject: [Tutor] pythonpath In-Reply-To: <4CCF3811.2030803@gmail.com> References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> <4CCF3811.2030803@gmail.com> Message-ID: Chris, I haven't worked on windows in ages, but I think you can set a PYTHONPATH variable if you right click on My Computer and maybe the advanced tab, there is a place to set ENVIRONMENT VARIABLES. Create a new one called PYTHONPATH pointing to your directory. -john On Mon, Nov 1, 2010 at 10:58 PM, Chris King wrote: > On 11/1/2010 5:57 PM, Vince Spicer wrote: > > On Mon, Nov 1, 2010 at 3:54 PM, Chris King wrote: >> >> On 11/1/2010 5:47 PM, Vince Spicer wrote: >> >> On Mon, Nov 1, 2010 at 3:41 PM, Chris King wrote: >>> >>> ?Dear Tutors, >>> ? ?When I try to import a module, how can I make it look in certain >>> directories for them easily. >>> Sincerely, >>> ? ?Chris >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> Hello Chris >> You can manage you path from within your script, >> import sys >> sys.path.append("/home/user/lib") >> >> Or in bash you can edit your ?$PYTHONPATH env variable >> echo $PYTHONPATH >> >> -- >> Vince Spicer >> >> -- >> Sent from Ubuntu >> >> So doing it in cmd windows will permanently change it? > > > the first way with work for Window, ?the second is for Linux or posix > systems > Sorry I can't help with PYTHONPATH on windows. > > -- > Vince Spicer > > -- > Sent from Ubuntu > > I want a permanent change. > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From vince at vinces.ca Mon Nov 1 23:03:48 2010 From: vince at vinces.ca (Vince Spicer) Date: Mon, 1 Nov 2010 16:03:48 -0600 Subject: [Tutor] pythonpath In-Reply-To: References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> <4CCF3811.2030803@gmail.com> Message-ID: On Mon, Nov 1, 2010 at 4:00 PM, Vince Spicer wrote: > > > On Mon, Nov 1, 2010 at 3:58 PM, Chris King wrote: > >> On 11/1/2010 5:57 PM, Vince Spicer wrote: >> >> >> >> On Mon, Nov 1, 2010 at 3:54 PM, Chris King wrote: >> >>> On 11/1/2010 5:47 PM, Vince Spicer wrote: >>> >>> >>> >>> On Mon, Nov 1, 2010 at 3:41 PM, Chris King wrote: >>> >>>> Dear Tutors, >>>> When I try to import a module, how can I make it look in certain >>>> directories for them easily. >>>> Sincerely, >>>> Chris >>>> _______________________________________________ >>>> Tutor maillist - Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>> >>> Hello Chris >>> >>> You can manage you path from within your script, >>> >>> import sys >>> sys.path.append("/home/user/lib") >>> >>> Or in bash you can edit your $PYTHONPATH env variable >>> echo $PYTHONPATH >>> >>> >>> -- >>> Vince Spicer >>> >>> >>> -- >>> Sent from Ubuntu >>> >>> So doing it in cmd windows will permanently change it? >>> >> >> >> the first way with work for Window, the second is for Linux or posix >> systems >> >> Sorry I can't help with PYTHONPATH on windows. >> >> -- >> Vince Spicer >> >> >> -- >> Sent from Ubuntu >> >> I want a permanent change. >> > > There is probably a Windows alternative to env variables and PYTHONPATH, > Google may help. > > > -- > Vince Spicer > > -- > Sent from Ubuntu > > Sorry I don't know any developers that run Windows anymore, if you find the solution please post it back here. Thanks. -- Vince Spicer -- Sent from Ubuntu -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Nov 1 23:04:11 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 1 Nov 2010 22:04:11 +0000 Subject: [Tutor] pythonpath In-Reply-To: <4CCF37C9.9030306@gmail.com> References: <4CCF3424.8010407@gmail.com> <4CCF37C9.9030306@gmail.com> Message-ID: On 1 November 2010 21:57, Chris King wrote: > On 11/1/2010 5:47 PM, Vince Spicer wrote: > it didn't work > > Then you've done something wrong. Post the code, and/or the error message, if any. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Nov 1 23:04:37 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 18:04:37 -0400 Subject: [Tutor] rights In-Reply-To: References: <4CCF1DA5.2020904@gmail.com> Message-ID: <4CCF3975.7070901@gmail.com> On 11/1/2010 5:21 PM, Alan Gauld wrote: > > "Chris King" wrote >> How do you give a script right to read a folder? > > You give the user account executing the script rights to read the folder. > > HTH, > It was a folder on my desktop, which I can always read, right, and destroy. I ran it on that user. From wprins at gmail.com Mon Nov 1 23:13:32 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 1 Nov 2010 22:13:32 +0000 Subject: [Tutor] pythonpath In-Reply-To: <4CCF3811.2030803@gmail.com> References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> <4CCF3811.2030803@gmail.com> Message-ID: On 1 November 2010 21:58, Chris King wrote: > the first way with work for Window, the second is for Linux or posix > systems > > Sorry I can't help with PYTHONPATH on windows. > > To set a PYTHONPATH in Windows, click "Start", right click "My computer", click "Properties", click "Advanced" tab/section, click "Environment variables" button. See if you can find an entry in either the User variables or the System variables sections named "PYTHONPATH". If not, add a new entry to "User variables" by clicking "New", and entering the name "PYTHONPATH" and whatever you want for the path. Click "OK", "OK", "OK" and you should be back to the desktop. Open the Python shell, and enter: >>> import sys >>> print sys.path ['C:\\Python26\\Lib\\idlelib', 'C:\\Python26\\lib\\site-packages\\pip-0.8.1-py2.6.egg', 'C:\\Test', 'C:\\Python26\\python26.zip', 'C:\\Python26\\DLLs', 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', 'C:\\Python26\\lib\\site-packages'] As you can see have an entry "C:\\Test" due to the fact that I created that as the contents of my "PYTHONPATH" variable. HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Mon Nov 1 23:15:19 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 01 Nov 2010 18:15:19 -0400 Subject: [Tutor] pythonpath In-Reply-To: References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> <4CCF3811.2030803@gmail.com> Message-ID: <4CCF3BF7.8050209@gmail.com> On 11/1/2010 6:13 PM, Walter Prins wrote: > > > On 1 November 2010 21:58, Chris King @gmail.com > wrote: > >> the first way with work for Window, the second is for Linux or >> posix systems >> >> Sorry I can't help with PYTHONPATH on windows. > > > To set a PYTHONPATH in Windows, click "Start", right click "My > computer", click "Properties", click "Advanced" tab/section, click > "Environment variables" button. See if you can find an entry in > either the User variables or the System variables sections named > "PYTHONPATH". If not, add a new entry to "User variables" by clicking > "New", and entering the name "PYTHONPATH" and whatever you want for > the path. Click "OK", "OK", "OK" and you should be back to the > desktop. Open the Python shell, and enter: > > >>> import sys > >>> print sys.path > ['C:\\Python26\\Lib\\idlelib', > 'C:\\Python26\\lib\\site-packages\\pip-0.8.1-py2.6.egg', 'C:\\Test', > 'C:\\Python26\\python26.zip', 'C:\\Python26\\DLLs', > 'C:\\Python26\\lib', 'C:\\Python26\\lib\\plat-win', > 'C:\\Python26\\lib\\lib-tk', 'C:\\Python26', > 'C:\\Python26\\lib\\site-packages'] > > As you can see have an entry "C:\\Test" due to the fact that I created > that as the contents of my "PYTHONPATH" variable. > > HTH, > > Walter > It worked! -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Mon Nov 1 23:19:14 2010 From: washakie at gmail.com (John) Date: Mon, 1 Nov 2010 23:19:14 +0100 Subject: [Tutor] pythonpath In-Reply-To: References: <4CCF3424.8010407@gmail.com> <4CCF371A.7000607@gmail.com> <4CCF3811.2030803@gmail.com> Message-ID: hehe. yeah, I had to go check my old PC that's collecting dust on how to navigate the 'happy dungeon' of windows wizards... I do prefer: export PYTHONPATH=/my/custom/dir On Mon, Nov 1, 2010 at 11:03 PM, Vince Spicer wrote: > > > On Mon, Nov 1, 2010 at 4:00 PM, Vince Spicer wrote: >> >> >> On Mon, Nov 1, 2010 at 3:58 PM, Chris King wrote: >>> >>> On 11/1/2010 5:57 PM, Vince Spicer wrote: >>> >>> On Mon, Nov 1, 2010 at 3:54 PM, Chris King wrote: >>>> >>>> On 11/1/2010 5:47 PM, Vince Spicer wrote: >>>> >>>> On Mon, Nov 1, 2010 at 3:41 PM, Chris King wrote: >>>>> >>>>> ?Dear Tutors, >>>>> ? ?When I try to import a module, how can I make it look in certain >>>>> directories for them easily. >>>>> Sincerely, >>>>> ? ?Chris >>>>> _______________________________________________ >>>>> Tutor maillist ?- ?Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> Hello Chris >>>> You can manage you path from within your script, >>>> import sys >>>> sys.path.append("/home/user/lib") >>>> >>>> Or in bash you can edit your ?$PYTHONPATH env variable >>>> echo $PYTHONPATH >>>> >>>> -- >>>> Vince Spicer >>>> >>>> -- >>>> Sent from Ubuntu >>>> >>>> So doing it in cmd windows will permanently change it? >>> >>> >>> the first way with work for Window, ?the second is for Linux or posix >>> systems >>> Sorry I can't help with PYTHONPATH on windows. >>> >>> -- >>> Vince Spicer >>> >>> -- >>> Sent from Ubuntu >>> >>> I want a permanent change. >> >> There is probably a Windows alternative to env variables and PYTHONPATH, >> Google may help. >> >> -- >> Vince Spicer >> -- >> Sent from Ubuntu > > > Sorry I don't know any developers that run Windows anymore, if you find the > solution please post it back here. > Thanks. > > > -- > Vince Spicer > > -- > Sent from Ubuntu > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From steve at pearwood.info Tue Nov 2 00:01:37 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 10:01:37 +1100 Subject: [Tutor] Complete Shutdown In-Reply-To: References: <4CCF1CA3.3050305@gmail.com> Message-ID: <4CCF46D1.7090404@pearwood.info> Alan Gauld wrote: > > "Chris King" wrote > >> How do I completely shutdown a computer without administrative >> rights using a simple python script. > > If you have such a computer get rid of it, it fails the most basic test > of a secure operating system. No program that runs upon it could > ever be relied upon! I'm not so sure about that... I think a personal computer which didn't allow ordinary, unprivileged users to safely shut it down would be worse. One shouldn't need to be root (or Administrator) to turn your own laptop or desktop off! Do we really want Aunt Tilly just flicking the power switch when she wants to turn her computer off? Of course in a multi-user system, things are more complicated, and nor do you want arbitrary programs to be able to shut down your computer. Imagine if your browser could turn your computer off. Imagine if arbitrary websites could turn your computer off. Chaos and pain everywhere! A bit like running IE 6 really :) An interesting question would be, given that you do have administrator rights to log out/reboot/shut down, how would you do so from Python? The solution will depend on the OS and possibly the window manager, but other than that, I'm completely out of ideas. -- Steven From steve at pearwood.info Tue Nov 2 00:05:23 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 10:05:23 +1100 Subject: [Tutor] pythonpath In-Reply-To: <4CCF37C9.9030306@gmail.com> References: <4CCF3424.8010407@gmail.com> <4CCF37C9.9030306@gmail.com> Message-ID: <4CCF47B3.9090409@pearwood.info> Chris King wrote: > it didn't work Define "it" and "didn't work". What did you try? What happened when you tried it? -- Steven From emile at fenx.com Tue Nov 2 00:27:20 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 01 Nov 2010 16:27:20 -0700 Subject: [Tutor] pythonpath In-Reply-To: <4CCF3424.8010407@gmail.com> References: <4CCF3424.8010407@gmail.com> Message-ID: On 11/1/2010 2:41 PM Chris King said... > Dear Tutors, > When I try to import a module, how can I make it look in certain > directories for them easily. > Sincerely, > Chris I'm not sure it's still the preferred way of setting sys.path, but site.py sets sys.path and contains info on *.pth files and other methods used. Emile From steve at pearwood.info Tue Nov 2 00:37:06 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 10:37:06 +1100 Subject: [Tutor] scope, visibility? In-Reply-To: References: Message-ID: <4CCF4F22.2080208@pearwood.info> Samuel de Champlain wrote: > Inside the class is a method with a bit of code: > > def masque(chaine,liInd=0): > i = 0 > lenght = len(chaine) As this is a method, you normally need to refer to the instance in the definition: def masque(self, chaine, liInd=0): i = 0 length = len(chaine) There are exceptions to this -- class methods and static methods -- but you should consider them for advanced use. Normally, so long as you remember to put self as the first argument to the method, you will be right. Because you left that out, Python assigned the instance to "chaine" and what you expected to be chaine to "liInd", leading to unexpected results. > Here are the error messages: > > penduGTK.py > Traceback (most recent call last): > File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback > self.lblMot.set_text(self.masque(self.motChoisi)) > File "/home/xxx/bin/penduGTK.py", line 44, in masque > lenght = len(chaine) > AttributeError: PenduGTK instance has no attribute '__len__' > > I would think it has to do with namespaces, scopes and visibility. But how > do I refer to built-in functions from inside a class? Nothing to do with any of those things. -- Steven From steve at pearwood.info Tue Nov 2 00:50:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 10:50:32 +1100 Subject: [Tutor] Complete Shutdown In-Reply-To: <4CCF3871.8080006@gmail.com> References: <4CCF1CA3.3050305@gmail.com> <4CCF3871.8080006@gmail.com> Message-ID: <4CCF5248.8010809@pearwood.info> Chris King wrote: > I restarted the whole system with a script. Why couldn't I shut it down? Probably because the script told the computer to restart rather than shut down. It will help if you tell us: * what operating system you are running * what you did to restart the computer * what you tried to shut it down * what happened when you tried. -- Steven From steve at pearwood.info Tue Nov 2 00:56:38 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 10:56:38 +1100 Subject: [Tutor] Problems with partial string matching In-Reply-To: References: <4CC48E9B.6080302@ieee.org> <4CCEC2BB.1080801@ieee.org> <4CCEFFE9.2030706@ieee.org> Message-ID: <4CCF53B6.3080007@pearwood.info> Josep M. Fontana wrote: >> The only time year is bound is in the previous loop, as I said. It's the >> line that goes: >> name, year = line.strip..... >> >> So year is whatever it was the last time through that loop. > > OK, this makes sense. Indeed that is the value in the last entry for > the dictionary. Thanks a lot again. Dictionaries don't have a "last", or "first", entry -- they're unordered collections. Think of them as a bag filled with stuff -- if you reach in and grab an item, one at a time, you will get the items in some order, but that's imposed on the bag by the sequential nature of taking one item at a time. The items themselves have no order. Iterating over a dictionary, or printing it, is like dipping into the bag for each item one at a time. Python carefully ensures that this order is consistent: dict,keys(), dict.values() and dict.items() will return the objects in the same order, so long as you don't modify the dictionary between calls. But that order is arbitrary, depends on the history of insertions and deletions, and is subject to change without notice. So if we do this: d = {} d[0] = 'a' d[-1] = 'b' d[-2] = 'c' and then print d in Python 3.1.1, we get: {0: 'a', -2: 'c', -1: 'b'} but if we add the items in a different order: d = {} d[-2] = 'c' d[0] = 'a' d[-1] = 'b' we get this instead: {0: 'a', -1: 'b', -2: 'c'}. In general, there is no relationship between the order you insert objects into a dict and the order that you will get them out. Sometimes it may match. Usually it won't. -- Steven From steve at pearwood.info Tue Nov 2 01:01:38 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 11:01:38 +1100 Subject: [Tutor] Problems with partial string matching In-Reply-To: References: <4CC48E9B.6080302@ieee.org> <4CCEC2BB.1080801@ieee.org> Message-ID: <4CCF54E2.8010707@pearwood.info> Josep M. Fontana wrote: > Sorry about the top-posting. Sometimes it seems that a little > top-posting might make things easier (I hate to have to go through > long quotes) but you are totally right, netiquette is netiquette. To all the people who say "Never top-post", I say never say never -- there are exceptions to every rule, except the rule about there always being exceptions. But 99% of the time, comments should follow the quote they are commenting on, like a conversation: > comment reply > comment reply The point you make about long quotes is also very important. Having to scroll, and scroll, and scroll, and SCROLL through pages and pages of quoted text to get to a single comment at the end is very annoying, sometimes more annoying than top-posting. I often get so fed up I'll give up and move on to the next email -- I have a *lot* of emails to wade through, many of them (like this list) are a labour of love and I don't get paid a cent for reading them, and if I have to work hard just to reach the relevant text, I will often decide that if the sender couldn't be bothered trimming his quoting, he obviously didn't think his post was worth spending an extra 2 seconds making it readable, so why should I spend any extra time reading it? Failure to trim the quoting down to the parts that are actually relevant is equally as thoughtless as needless top-posting. If the delete key on your keyboard is broken, then say so, otherwise use it. End of rant. Thank you. -- Steven From alan.gauld at btinternet.com Tue Nov 2 01:43:13 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Nov 2010 00:43:13 -0000 Subject: [Tutor] rights References: <4CCF1DA5.2020904@gmail.com> <4CCF3975.7070901@gmail.com> Message-ID: "Chris King" wrote >> You give the user account executing the script rights to read the >> folder. >> >> HTH, >> > It was a folder on my desktop, which I can always read, right, and > destroy. I ran it on that user. In that case we probably need to see: 1) What OS? 2) What does the code look like? 3) How are you running it? 4) What error messages do you get? Also, is it a folder you are trying to read or a file? They are not the same. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From galaxywatcher at gmail.com Tue Nov 2 01:37:13 2010 From: galaxywatcher at gmail.com (TGW) Date: Mon, 1 Nov 2010 20:37:13 -0400 Subject: [Tutor] Tutor Digest, Vol 81, Issue 3 In-Reply-To: References: Message-ID: rgr. On Nov 1, 2010, at 5:21 PM, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: scope, visibility? (Dave Angel) > 2. Re: scope, visibility? (Evert Rol) > 3. Re: Problems with partial string matching (Josep M. Fontana) > 4. Complete Shutdown (Chris King) > 5. rights (Chris King) > 6. Re: rights (Vince Spicer) > 7. Re: Complete Shutdown (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Mon, 01 Nov 2010 14:14:33 -0400 > From: Dave Angel > To: Samuel de Champlain > Cc: tutor at python.org > Subject: Re: [Tutor] scope, visibility? > Message-ID: <4CCF0389.10702 at ieee.org> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 2:59 PM, Samuel de Champlain wrote: >> I am learning python. To practice, I am coding a hangman application in >> pyGTK. >> Here are my imports: >> >> import pygtk >> pygtk.require('2.0') >> import gtk >> import random >> >> Here is my main class: >> >> class PenduGTK: >> >> Inside the class is a method with a bit of code: >> >> def masque(chaine,liInd=0): >> >> i = 0 >> lenght = len(chaine) >> >> The offending line is the one with len(chaine) >> >> Here are the error messages: >> >> penduGTK.py >> Traceback (most recent call last): >> File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback >> self.lblMot.set_text(self.masque(self.motChoisi)) >> File "/home/xxx/bin/penduGTK.py", line 44, in masque >> lenght = len(chaine) >> AttributeError: PenduGTK instance has no attribute '__len__' >> >> I would think it has to do with namespaces, scopes and visibility. But how >> do I refer to built-in functions from inside a class? >> > You're correctly referring to the built-in function len(). But that > function assumes that the object it gets as an argument has a __len__() > method. List, string, tuple all do. But perhaps PenduGTK does not. > You don't show us the whole class. > > Your real problem is probably that you're missing self as the first > argument. So where you think chaine is a string, it's actually an instance. > > DaveA > > > > ------------------------------ > > Message: 2 > Date: Mon, 1 Nov 2010 19:15:49 +0100 > From: Evert Rol > To: Samuel de Champlain > Cc: tutor at python.org > Subject: Re: [Tutor] scope, visibility? > Message-ID: <054046EC-CC0E-48B4-A85E-083FCE7EE5AB at gmail.com> > Content-Type: text/plain; charset=us-ascii > >> Here is my main class: >> >> class PenduGTK: >> >> Inside the class is a method with a bit of code: >> >> def masque(chaine,liInd=0): >> >> i = 0 >> lenght = len(chaine) >> >> The offending line is the one with len(chaine) >> >> Here are the error messages: >> >> penduGTK.py >> Traceback (most recent call last): >> File "/home/xxx/bin/penduGTK.py", line 23, in enter_callback >> self.lblMot.set_text(self.masque(self.motChoisi)) >> File "/home/xxx/bin/penduGTK.py", line 44, in masque >> lenght = len(chaine) >> AttributeError: PenduGTK instance has no attribute '__len__' > > A method takes as its first argument a reference to the class. That is, in 'def some_method(blah1, blah2, blah3)', blah1 would be a reference to the class in which some_method is defined. > If you look at the error message, you see Python complains that the PenduGTK instance has no __len__ attribute, meaning 'chaine' is a PenduGTK instance: it's the first argument in the method, taking a reference to the class. > See eg http://diveintopython.org/object_oriented_framework/defining_classes.html > (also, carefully read the error and think what it could mean: it has a lot of hints to solve your problem). > > Thus, define a method with an extra (first) argument. This is usually called self: > > def masque(self, chaine, liInd=0): > > > Last note on a totally different thing, because this confused me a bit: preferably avoid avoid the lowercase L, lowercase i and uppercase I next to each other. It's very hard to read. See eg http://www.python.org/dev/peps/pep-0008/ (section 'Names to Avoid'). To me, it initially read something like iiind=0. Which is ok, as long as I don't have to work with the code. But it may also bite you some day. > > >> I would think it has to do with namespaces, scopes and visibility. But how do I refer to built-in functions from inside a class? > > Just as you did above: len(chaine). > But since that wasn't your problem, I guess this answer is rather meaningless. > > Cheers, > > Evert > > > > ------------------------------ > > Message: 3 > Date: Mon, 1 Nov 2010 20:38:06 +0100 > From: "Josep M. Fontana" > To: Dave Angel > Cc: tutor at python.org > Subject: Re: [Tutor] Problems with partial string matching > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > >> The only time year is bound is in the previous loop, as I said. ?It's the >> line that goes: >> ? ? name, year = line.strip..... >> >> So year is whatever it was the last time through that loop. > > OK, this makes sense. Indeed that is the value in the last entry for > the dictionary. Thanks a lot again. > > Josep M. > > > ------------------------------ > > Message: 4 > Date: Mon, 01 Nov 2010 16:01:39 -0400 > From: Chris King > To: python mail list > Subject: [Tutor] Complete Shutdown > Message-ID: <4CCF1CA3.3050305 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Dear Tutors, > How do I completely shutdown a computer without administrative > rights using a simple python script. > Sincerely, > Me, Myself, and I > > > ------------------------------ > > Message: 5 > Date: Mon, 01 Nov 2010 16:05:57 -0400 > From: Chris King > To: python mail list > Subject: [Tutor] rights > Message-ID: <4CCF1DA5.2020904 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Dear Tutors, > How do you give a script right to read a folder? > > > ------------------------------ > > Message: 6 > Date: Mon, 1 Nov 2010 14:10:43 -0600 > From: Vince Spicer > To: Chris King > Cc: python mail list > Subject: Re: [Tutor] rights > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > On Mon, Nov 1, 2010 at 2:05 PM, Chris King wrote: > >> Dear Tutors, >> How do you give a script right to read a folder? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > Which Operation System? > > In linux the user that is running the script must be have read access > > chmod +r folder > > > -- > Vince Spicer > > -- > Sent from Ubuntu > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > ------------------------------ > > Message: 7 > Date: Mon, 1 Nov 2010 21:20:42 -0000 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Complete Shutdown > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > > "Chris King" wrote > >> How do I completely shutdown a computer without administrative >> rights using a simple python script. > > If you have such a computer get rid of it, it fails the most basic > test > of a secure operating system. No program that runs upon it could > ever be relied upon! > > The whole concept is evil. > > Administrator rights are required for good reason and are a protection > against bad things happening to your data and programs. Work with > it not against it and be grateful it's there. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 81, Issue 3 > ************************************ From alan.gauld at btinternet.com Tue Nov 2 01:49:52 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Nov 2010 00:49:52 -0000 Subject: [Tutor] Complete Shutdown References: <4CCF1CA3.3050305@gmail.com> <4CCF46D1.7090404@pearwood.info> Message-ID: "Steven D'Aprano" wrote >>> How do I completely shutdown a computer without administrative >>> rights using a simple python script. >> >> If you have such a computer get rid of it, it fails the most basic >> test > I'm not so sure about that... I think a personal computer which > didn't allow ordinary, unprivileged users to safely shut it down I agree the key is the word "safely" If the request is how tom invoke the shuitdown sequence in a controlled manner then it is more reasonable. I interpreted the request as being rto just power it doen from a random Python script. > Of course in a multi-user system, things are more complicated, and > nor do you want arbitrary programs to be able to shut down your > computer. And I tend to work in multi-user environments (even on my personal desktop) so I tend to forget that there are single user computers out there. In a single user then the user is de-facto the administrator too. So I will temper my words with the caution that it may occasionally be necessary but its rarely a good idea. > Imagine if your browser could turn your computer off. Imagine if > arbitrary websites could turn your computer off. Chaos and pain > everywhere! And that was precisdely the point I was trying to make albeit rather over zealously. > An interesting question would be, given that you do have > administrator rights to log out/reboot/shut down, how would you do > so from Python? The solution will depend on the OS and possibly the > window manager, but other than that, I'm completely out of ideas. Its usually available as a system call (certainly in *nix or windoze) but you do need the right privileges since you are effectively running another program. So if the OS doesn't allow you to shutdown you can't without changing user. If the OS allows it you can do it from Python, but how will depend on the OS! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Tue Nov 2 03:10:39 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 1 Nov 2010 21:10:39 -0500 Subject: [Tutor] unittest + tkinter Message-ID: I'm sure there's an incredibly simple way to do this, but at the moment it eludes me. I'm trying my hand at test driven development via the unittest module. Since my program is using Tkinter, my thought is that I need to create the main window. The only problem is that when I launch the main loop, further lines of code aren't executed. #simple.py import Tkinter as tk class Simple(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.mainloop() # test.py import unittest import simple class SimpleTestCase(unittest.TestCase): def testSimple(self): s = simple.Simple() print 'hi' # have to close the window before this happens unittest.main() Am I on the right track? or am I way out in left field? Any pointers/help in the right direction? Thanks, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 2 10:28:25 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Nov 2010 09:28:25 -0000 Subject: [Tutor] unittest + tkinter References: Message-ID: "Wayne Werner" wrote > I'm trying my hand at test driven development via the unittest > module. Since > my program is using Tkinter, my thought is that I need to create the > main > window. The only problem is that when I launch the main loop, > further lines > of code aren't executed. Thats a feature of event driven programs. All the action takes place inside the event loop. I don't know how you drive a GUI with unittest though so can't help solve your problem. But the behaviour is normal for any GUI. Alan G. From crallionx at gmail.com Tue Nov 2 10:29:18 2010 From: crallionx at gmail.com (Crallion) Date: Tue, 2 Nov 2010 10:29:18 +0100 Subject: [Tutor] True Random Numbers Message-ID: In an attempt to generate "true" random numbers, I found this python script- http://code.google.com/p/truerandom/ Getting to the point, I get this error when I run my program. File "/dev/python/absolute/truerandom.py", line 9, in from urllib import urlopen ImportError: cannot import name urlopen Is urllib and/or urlopen deprecated in 3.1.2 or is it something I forgot to do? Python is running on OSX 10.6, which I upgraded from the default install to 3.1.2. From timomlists at gmail.com Tue Nov 2 10:47:44 2010 From: timomlists at gmail.com (Timo) Date: Tue, 02 Nov 2010 10:47:44 +0100 Subject: [Tutor] Complete Shutdown In-Reply-To: <4CCF1CA3.3050305@gmail.com> References: <4CCF1CA3.3050305@gmail.com> Message-ID: <4CCFDE40.8020506@gmail.com> On 01-11-10 21:01, Chris King wrote: > Dear Tutors, > How do I completely shutdown a computer without administrative > rights using a simple python script. I once came across the following when playing with dbus. import dbus bus = dbus.SystemBus() bus_object = bus.get_object("org.freedesktop.Hal", "/org/freedesktop/Hal/devices/computer") bus_object.Shutdown(dbus_interface="org.freedesktop.Hal.Device.SystemPowerManagement") This will shutdown your computer immediatly. You can substitute the "Shutdown" method with "Suspend", "Hibernate" or "Reboot". Cheers, Timo > Sincerely, > Me, Myself, and I > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From cwitts at compuscan.co.za Tue Nov 2 10:59:01 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 02 Nov 2010 11:59:01 +0200 Subject: [Tutor] True Random Numbers In-Reply-To: References: Message-ID: <4CCFE0E5.9050905@compuscan.co.za> On 02/11/2010 11:29, Crallion wrote: > In an attempt to generate "true" random numbers, I found this python script- http://code.google.com/p/truerandom/ > Getting to the point, I get this error when I run my program. > > File "/dev/python/absolute/truerandom.py", line 9, in > from urllib import urlopen > ImportError: cannot import name urlopen > > Is urllib and/or urlopen deprecated in 3.1.2 or is it something I forgot to do? > Python is running on OSX 10.6, which I upgraded from the default install to 3.1.2. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > |The urllib2 module has been split across several modules in Python 3.0 named urllib.request and urllib.error so you should be doing `from urllib.request import urlopen`.| -- Kind Regards, Christian Witts From steve at pearwood.info Tue Nov 2 11:16:25 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Nov 2010 21:16:25 +1100 Subject: [Tutor] True Random Numbers In-Reply-To: References: Message-ID: <4CCFE4F9.6030806@pearwood.info> Crallion wrote: > In an attempt to generate "true" random numbers, Have you considered using your operating system's source of random numbers? random.SystemRandom and os.urandom return numbers which are cryptographically sound. They are also based on various sources of physical randomness (which is sometimes a disadvantage, as the entropy can run out and then the functions will hang waiting for more entropy to be collected). > I found this python script- http://code.google.com/p/truerandom/ > Getting to the point, I get this error when I run my program. > > File "/dev/python/absolute/truerandom.py", line 9, in > from urllib import urlopen > ImportError: cannot import name urlopen > > Is urllib and/or urlopen deprecated in 3.1.2 or is it something I forgot to do? > Python is running on OSX 10.6, which I upgraded from the default install to 3.1.2. You should never upgrade the system Python by hand, because parts of the OS are likely to expect a specific version. You should install it separately. But in this case, something is screwy, because that script is written for Python 2.x and won't run at all under Python 3.x. The fact that you managed to get as far as an ImportError is weird -- it should fail with SyntaxError during compilation. urllib still exists in Python 3.x, but it has been re-organised and urlopen is now called something else. Instead of from urllib import urlopen you need from urllib.request import urlopen See the Fine Manual for further details. -- Steven From washakie at gmail.com Tue Nov 2 13:51:13 2010 From: washakie at gmail.com (John) Date: Tue, 2 Nov 2010 13:51:13 +0100 Subject: [Tutor] mutable types Message-ID: Hello, I thought the following should end with G[1] and G[0] returning 20. Why doesn't it? In [69]: a = 10 In [70]: G = {} In [71]: G[0] = [a] In [72]: G[1] = G[0] In [73]: a = 20 In [74]: G[1] Out[74]: [10] In [75]: G[0] Out[75]: [10] ?? From knacktus at googlemail.com Tue Nov 2 14:31:01 2010 From: knacktus at googlemail.com (Knacktus) Date: Tue, 02 Nov 2010 14:31:01 +0100 Subject: [Tutor] mutable types In-Reply-To: References: Message-ID: <4CD01295.5060708@googlemail.com> Am 02.11.2010 13:51, schrieb John: > Hello, I thought the following should end with G[1] and G[0] returning > 20. Why doesn't it? > > In [69]: a = 10 "a" is a reference to an immutable object of type int with value 10. Somewhere in memory is an object of type int with value 10 stored. This object cannot be changed. "a" is just a name that references to the memory adress. > In [70]: G = {} > In [71]: G[0] = [a] now, G[0] holds a reference to a mutable object of type list with an immutable object of type int with value 10 as its content. So, your list holds as item the memory adress of an object int with value 10. Your list knows nothing about other names (like "a"), that refer to the same adress in memory. You have handed over the object to the list (or memory adress of the object), not the name "a". > In [72]: G[1] = G[0] > In [73]: a = 20 Now, you've created a *new* immutable object of type int with value 20. "a" now refers to the adress of the new integer object. "a" has forgotten everything about its former reference to the object of type int with value 10. You have *not* changed the "old" object of type int with value 10. Your list in G[0] still holds the memory adress of the first int with value 10. > In [74]: G[1] > Out[74]: [10] > In [75]: G[0] > Out[75]: [10] > > ?? Now, if you would keep a reference to the list you've handed over to the dict, you could change the content of the list, as the list is mutable. >>> a = [10] >>> G = {} >>> G[0] = a >>> G[0] [10] >>> a[0] = 20 >>> G[0] [20] Take care of some operations that return a copy of the list: >>> a = a[:] Now, "a" refernces to a new list, which has also one item of type in with value 20. But it's not the same list as originally! >>> a[0] = 30 Changing this new list ... >>> G[0] [20] does not affect the list, we stored in the dict. HTH, Jan > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Tue Nov 2 15:15:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 03 Nov 2010 01:15:54 +1100 Subject: [Tutor] mutable types In-Reply-To: References: Message-ID: <4CD01D1A.9020108@pearwood.info> John wrote: > Hello, I thought the following should end with G[1] and G[0] returning > 20. Why doesn't it? > > In [69]: a = 10 > In [70]: G = {} > In [71]: G[0] = [a] > In [72]: G[1] = G[0] > In [73]: a = 20 > In [74]: G[1] > Out[74]: [10] > In [75]: G[0] > Out[75]: [10] This doesn't actually have anything to do with the difference between mutable and immutable objects. Here's a simpler example to think about: a = 10 # the name "a" is bound to the object 10 b = a # the name "b" is bound to the same object "a" is bound to a = 20 # the name "a" is bound to the object 20 b = ???? What value would you expect b to have? The fact that you are using a mutable dictionary in your example is no different: a = 10 # the name "a" is bound to the object 10 G = {} # the name "G" is bound to an empty dictionary object G[0] = [a] # the dictionary bound to G has a mapping added, # the key 0 is mapped to a list containing the object bound to "a" The important thing here is that the list [a] doesn't, and can't, know anything about the *name* "a". All it sees is the object that a is *currently* bound to. Once that object is placed in the list, there is no connection from the name "a" to the list, or visa versa. So later on, when you re-bind "a" to 20, that does nothing to the object 10, or the list that contains 10, or the dict that contains the list. Around this time, many people start arguing about "call by value" and "call by reference" (or sometimes "pass by value" and "pass by reference"). If these terms mean nothing to you, congratulations! That's one less thing for you to care about, and you can stop reading now and go and do something productive. Arguments about calling conventions in programming languages often sink into long, unproductive flame wars. Seriously. Stop reading and go do some programming. Still here? Okay, don't say you weren't warned... If you do know the terms "call by (pass by) reference" and "call by value", and you're thinking that Python is pass-by-reference for mutable objects, no, it's not. There is no way to get this behaviour in Python, regardless of whether you use mutable or immutable objects: # this doesn't work a = 1 b = 2 swap(a, b) # call a function with by-reference parameters assert a == 2 # fails assert b == 1 # also fails Can't be done from Python. There are alternatives that work just as well, such as the idiomatic: a, b = b, a but Python has no by-reference variables or arguments. Now you're thinking that Python must be pass-by-value. If you're not, congratulations, you've just dodged a very common mistake. Python isn't pass-by-value *either*: def func(alist): del alist[:] return alist # this doesn't work either a = [1,2,3] b = func(a) # pass-by-value automatically makes a copy of a assert a == [1,2,3] and b = [] # fails Python's evaluation strategy goes by various names, my favourite being pass-by-object. Another is call-by-sharing. Unfortunately, other languages fall into the trap of thinking that there are only two strategies, call-by-value and call-by-reference, and so they use one or the other of those names for the exact same behaviour that Python exhibits. Sigh. http://en.wikipedia.org/wiki/Evaluation_strategy -- Steven From glenuk at gmail.com Tue Nov 2 20:02:15 2010 From: glenuk at gmail.com (Glen Clark) Date: Tue, 02 Nov 2010 19:02:15 +0000 Subject: [Tutor] if statement Message-ID: <1288724535.15073.0.camel@ubuntu-desktop.core> File "/home/glen/workspace/test.py", line 19 if confirmed == "y": ^ SyntaxError: invalid syntax Why does this not work??? PyDev says "Expected:else" From mehgcap at gmail.com Tue Nov 2 20:05:02 2010 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 2 Nov 2010 15:05:02 -0400 Subject: [Tutor] if statement In-Reply-To: <1288724535.15073.0.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: On 11/2/10, Glen Clark wrote: > File "/home/glen/workspace/test.py", line 19 > if confirmed == "y": > ^ > SyntaxError: invalid syntax > > Why does this not work??? PyDev says "Expected:else" It may help to see the rest of the file, or at least more of the code surrounding this statement. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From glenuk at gmail.com Tue Nov 2 20:07:18 2010 From: glenuk at gmail.com (Glen Clark) Date: Tue, 02 Nov 2010 19:07:18 +0000 Subject: [Tutor] if statement In-Reply-To: References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: <1288724838.15073.2.camel@ubuntu-desktop.core> sorry: NumItems = int(input("How many Items: ")) Entries = [] for In in range(0,NumItems): Entries.append("") for In in range(0,NumItems): Entries[In]=str(input("Enter name " + str(In+1) + ": ")) for In in range(0,NumItems): print(Entries[In]) confirmed = int(input("Are you happy with this? (y/n): ") if confirmed == "y": for In in range(0,NumItems): print(Entries[In] + ": " + str(In)) change = int(input("Which item would you like to change: ") Entries[change]=str(input("Please enter a nem name: ") else: #do nothing print(Entries) On Tue, 2010-11-02 at 15:05 -0400, Alex Hall wrote: > On 11/2/10, Glen Clark wrote: > > File "/home/glen/workspace/test.py", line 19 > > if confirmed == "y": > > ^ > > SyntaxError: invalid syntax > > > > Why does this not work??? PyDev says "Expected:else" > It may help to see the rest of the file, or at least more of the code > surrounding this statement. > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > From adam.jtm30 at gmail.com Tue Nov 2 20:07:11 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 02 Nov 2010 19:07:11 +0000 Subject: [Tutor] if statement In-Reply-To: <1288724535.15073.0.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: <4CD0615F.7020304@gmail.com> On 02/11/10 19:02, Glen Clark wrote: > File "/home/glen/workspace/test.py", line 19 > if confirmed == "y": > ^ > SyntaxError: invalid syntax > > Why does this not work??? PyDev says "Expected:else" > It's hard to tell without context. Can you send the code around it as well? From delegbede at dudupay.com Tue Nov 2 20:12:17 2010 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Tue, 2 Nov 2010 19:12:17 +0000 Subject: [Tutor] if statement In-Reply-To: <1288724535.15073.0.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: <1872742442-1288725148-cardhu_decombobulator_blackberry.rim.net-302133387-@bda2349.bisx.produk.on.blackberry> It is not always enough to send just the error. What construct do you have after the if line? Make your sample detailed to get useful responses. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Glen Clark Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Tue, 02 Nov 2010 19:02:15 To: python mail list Subject: [Tutor] if statement File "/home/glen/workspace/test.py", line 19 if confirmed == "y": ^ SyntaxError: invalid syntax Why does this not work??? PyDev says "Expected:else" _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From eire1130 at gmail.com Tue Nov 2 20:13:39 2010 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 2 Nov 2010 15:13:39 -0400 Subject: [Tutor] if statement In-Reply-To: <1288724535.15073.0.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: the syntax is: if True: do something that you want to do if the condition you are testing is True, in your case when confirmed is "y" elif True: optional: do something else when the above condition is false and this condition is True. else: do something else when the above conditions are false. You can try this, if confirmed == "y": stuff else: pass On Tue, Nov 2, 2010 at 3:02 PM, Glen Clark wrote: > File "/home/glen/workspace/test.py", line 19 > if confirmed == "y": > ^ > SyntaxError: invalid syntax > > Why does this not work??? PyDev says "Expected:else" > > _______________________________________________ > 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 glenuk at gmail.com Tue Nov 2 20:17:53 2010 From: glenuk at gmail.com (Glen Clark) Date: Tue, 02 Nov 2010 19:17:53 +0000 Subject: [Tutor] if statement In-Reply-To: References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: <1288725473.15073.4.camel@ubuntu-desktop.core> I tried that and it still does not work. On Tue, 2010-11-02 at 15:13 -0400, James Reynolds wrote: > the syntax is: > > > if True: > do something that you want to do if the condition you are testing > is True, in your case when confirmed is "y" > elif True: > optional: do something else when the above condition is false and > this condition is True. > else: > do something else when the above conditions are false. > > > You can try this, > > > if confirmed == "y": > stuff > else: > pass > > > > > On Tue, Nov 2, 2010 at 3:02 PM, Glen Clark wrote: > File "/home/glen/workspace/test.py", line 19 > if confirmed == "y": > ^ > SyntaxError: invalid syntax > > Why does this not work??? PyDev says "Expected:else" > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From adam.jtm30 at gmail.com Tue Nov 2 20:34:26 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 02 Nov 2010 19:34:26 +0000 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: <4CD067C2.9000907@gmail.com> On 02/11/10 19:07, Glen Clark wrote: > sorry: > > NumItems = int(input("How many Items: ")) > > > Entries = [] > for In in range(0,NumItems): > Entries.append("") > > > > for In in range(0,NumItems): > Entries[In]=str(input("Enter name " + str(In+1) + ": ")) > > > for In in range(0,NumItems): > print(Entries[In]) > > confirmed = int(input("Are you happy with this? (y/n): ") > > if confirmed == "y": > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = int(input("Which item would you like to change: ") > Entries[change]=str(input("Please enter a nem name: ") > else: > #do nothing > > print(Entries) > > Ok that's easier, you're missing a closing bracket at the end of the confirmed = int(input("Are you happy with this? (y/n): ") line. I think you might need at least a pass after else as well, although it should be fine to leave it out altogether once you've added the ')'. HTH, Adam. From vince at vinces.ca Tue Nov 2 20:36:47 2010 From: vince at vinces.ca (Vince Spicer) Date: Tue, 2 Nov 2010 13:36:47 -0600 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: On Tue, Nov 2, 2010 at 1:07 PM, Glen Clark wrote: > sorry: > > NumItems = int(input("How many Items: ")) > > > Entries = [] > for In in range(0,NumItems): > Entries.append("") > > > > for In in range(0,NumItems): > Entries[In]=str(input("Enter name " + str(In+1) + ": ")) > > > for In in range(0,NumItems): > print(Entries[In]) > > confirmed = int(input("Are you happy with this? (y/n): ") > > if confirmed == "y": > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = int(input("Which item would you like to change: ") > Entries[change]=str(input("Please enter a nem name: ") > else: > #do nothing > > print(Entries) > > On Tue, 2010-11-02 at 15:05 -0400, Alex Hall wrote: > > On 11/2/10, Glen Clark wrote: > > > File "/home/glen/workspace/test.py", line 19 > > > if confirmed == "y": > > > ^ > > > SyntaxError: invalid syntax > > > > > > Why does this not work??? PyDev says "Expected:else" > > It may help to see the rest of the file, or at least more of the code > > surrounding this statement. > > > > > > _______________________________________________ > > > 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 > confirmed = int(input("Are you happy with this? (y/n): ") You are missing a ) that the end of this line to close the int -- Vince Spicer -- Sent from Ubuntu -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Nov 2 20:42:21 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 2 Nov 2010 15:42:21 -0400 Subject: [Tutor] if statement In-Reply-To: <1288725473.15073.4.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288725473.15073.4.camel@ubuntu-desktop.core> Message-ID: On Tue, Nov 2, 2010 at 3:17 PM, Glen Clark wrote: > I tried that and it still does not work. > > On Tue, 2010-11-02 at 15:13 -0400, James Reynolds wrote: > > the syntax is: > > > > > > if True: > > do something that you want to do if the condition you are testing > > is True, in your case when confirmed is "y" > > elif True: > > optional: do something else when the above condition is false and > > this condition is True. > > else: > > do something else when the above conditions are false. > > > > > > You can try this, > > > > > > if confirmed == "y": > > stuff > > else: > > pass > > > > > > > > > > On Tue, Nov 2, 2010 at 3:02 PM, Glen Clark wrote: > > File "/home/glen/workspace/test.py", line 19 > > if confirmed == "y": > > ^ > > SyntaxError: invalid syntax > > > > Why does this not work??? PyDev says "Expected:else" > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > change = int(input("Which item would you like to change: ") In the line about you have mismatched parentheses. This confuses the parser _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From glenuk at gmail.com Tue Nov 2 20:44:32 2010 From: glenuk at gmail.com (Glen Clark) Date: Tue, 02 Nov 2010 19:44:32 +0000 Subject: [Tutor] if statement In-Reply-To: <1288724535.15073.0.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> Message-ID: <1288727072.15073.6.camel@ubuntu-desktop.core> Okay, Thank you very much for the help guys :) On a side note.. I didn't know you could do something like this: x = z if .... (thus why I needed the closing parenthesis) From christopher.henk at allisontransmission.com Tue Nov 2 20:36:27 2010 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Tue, 2 Nov 2010 15:36:27 -0400 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: Glen Clark wrote on 11/02/2010 03:07:18 PM: in general you should use raw_input instead of input. > confirmed = int(input("Are you happy with this? (y/n): ") > you are missing a closing parenthesis above, and converting a string (y,n) to and int > if confirmed == "y": you are comparing an int and a string here, probably not what you want (see above). > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = int(input("Which item would you like to change: ") again, you are missing a closing parenthesis above > Entries[change]=str(input("Please enter a nem name: ") again, you are missing a closing parenthesis above > else: > #do nothing you need to put pass here, you can't just have a comment in a block > > print(Entries) > Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Nov 2 20:57:15 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 2 Nov 2010 15:57:15 -0400 Subject: [Tutor] if statement In-Reply-To: <4CD067C2.9000907@gmail.com> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> <4CD067C2.9000907@gmail.com> Message-ID: On Tue, Nov 2, 2010 at 3:34 PM, Adam Bark wrote: > On 02/11/10 19:07, Glen Clark wrote: > >> sorry: >> >> NumItems = int(input("How many Items: ")) >> >> >> Entries = [] >> for In in range(0,NumItems): >> Entries.append("") >> >> >> >> for In in range(0,NumItems): >> Entries[In]=str(input("Enter name " + str(In+1) + ": ")) >> >> >> for In in range(0,NumItems): >> print(Entries[In]) >> >> confirmed = int(input("Are you happy with this? (y/n): ") >> >> if confirmed == "y": >> for In in range(0,NumItems): >> print(Entries[In] + ": " + str(In)) >> change = int(input("Which item would you like to change: ") >> Entries[change]=str(input("Please enter a nem name: ") >> else: >> #do nothing >> >> print(Entries) >> >> >> > Ok that's easier, you're missing a closing bracket at the end of the > > > confirmed = int(input("Are you happy with this? (y/n): ") > > line. > I think you might need at least a pass after else as well, although it > should be fine to leave it out altogether once you've added the ')'. > > HTH, > Adam. > > _______ > if confirmed == "y": for In in range(0,NumItems): print(Entries[In] + ": " + str(In)) change = int(input("Which item would you like to change: ") Entries[change]=str(input("Please enter a nem name: ") > else: > #do nothing > Actually, I caught two mismatched parens. In the line starting with 'change' and the following line. Fix those first > ________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Tue Nov 2 20:57:50 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 02 Nov 2010 12:57:50 -0700 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: On 11/2/2010 12:07 PM Glen Clark said... > sorry: > > NumItems = int(input("How many Items: ")) > > > Entries = [] > for In in range(0,NumItems): > Entries.append("") > > > > for In in range(0,NumItems): > Entries[In]=str(input("Enter name " + str(In+1) + ": ")) > > > for In in range(0,NumItems): > print(Entries[In]) > > confirmed = int(input("Are you happy with this? (y/n): ") The line above (which would appear to set confirmed to an int) doesn't have matching parens, which causes an error to be trapped elsewhere. Emile From alan.gauld at btinternet.com Tue Nov 2 21:08:34 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 2 Nov 2010 20:08:34 -0000 Subject: [Tutor] if statement References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: "Glen Clark" wrote > confirmed = int(input("Are you happy with this? (y/n): ") > > if confirmed == "y": count the parens. It thinks you are trying to do: confimed = int(input('ffff') if foo else bar) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From adam.jtm30 at gmail.com Tue Nov 2 21:26:28 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 02 Nov 2010 20:26:28 +0000 Subject: [Tutor] if statement In-Reply-To: References: Message-ID: <4CD073F4.3060804@gmail.com> On 02/11/10 19:36, christopher.henk at allisontransmission.com wrote: > > > Glen Clark wrote on 11/02/2010 03:07:18 PM: > > in general you should use raw_input instead of input. > > > > confirmed = int(input("Are you happy with this? (y/n): ") > > > It would appear that Glen is using python 3.x as he used the print function so input is correct. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Nov 2 22:18:17 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 02 Nov 2010 17:18:17 -0400 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: <4CD08019.7020407@gmail.com> On 11/2/2010 3:07 PM, Glen Clark wrote: > sorry: > > NumItems = int(input("How many Items: ")) > > > Entries = [] > for In in range(0,NumItems): > Entries.append("") > > > > for In in range(0,NumItems): > Entries[In]=str(input("Enter name " + str(In+1) + ": ")) > > > for In in range(0,NumItems): > print(Entries[In]) > > confirmed = int(input("Are you happy with this? (y/n): ") > In addition to the other help - do not use int here. You will get a run time error when it tries to convert y or n to an integer. If that succeeded e.g. the user entered 3), then confirmed (an integer) will NEVER be == "y" (a string). > if confirmed == "y": > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = int(input("Which item would you like to change: ") > Entries[change]=str(input("Please enter a nem name: ") > else: > #do nothing > > print(Entries) > > On Tue, 2010-11-02 at 15:05 -0400, Alex Hall wrote: >> On 11/2/10, Glen Clark wrote: >>> File "/home/glen/workspace/test.py", line 19 >>> if confirmed == "y": >>> ^ >>> SyntaxError: invalid syntax >>> >>> Why does this not work??? PyDev says "Expected:else" >> It may help to see the rest of the file, or at least more of the code >> surrounding this statement. >>> _______________________________________________ >>> 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 > -- Bob Gailer 919-636-4239 Chapel Hill NC From bermanrl at cfl.rr.com Tue Nov 2 21:00:35 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 2 Nov 2010 16:00:35 -0400 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: <000901cb7ac8$9d665b90$d83312b0$@rr.com> > -----Original Message----- > From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Glen Clark > Sent: Tuesday, November 02, 2010 3:07 PM > To: python mail list > Subject: Re: [Tutor] if statement > > sorry: > > > confirmed = int(input("Are you happy with this? (y/n): ") > > if confirmed == "y": > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = int(input("Which item would you like to change: ") > Entries[change]=str(input("Please enter a nem name: ") > else: > #do nothing Whoops. Why are you trying to make the variable "confirmed" an integer rather than a simple 'y/n' as you are asking for? Robert Berman -- I am using the free version of SPAMfighter. We are a community of 7 million users fighting spam. SPAMfighter has removed 34 of my spam emails to date. Get the free SPAMfighter here: http://www.spamfighter.com/len The Professional version does not have this message From alan.gauld at btinternet.com Wed Nov 3 01:47:33 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 3 Nov 2010 00:47:33 -0000 Subject: [Tutor] if statement References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288727072.15073.6.camel@ubuntu-desktop.core> Message-ID: "Glen Clark" wrote > On a side note.. I didn't know you could do something like this: > > x = z if .... Yes it's python's equivalent to the C style foo = testVal() ? bar : baz Also found in other languages (Java, Javascript, Perl?) Alan G. From modulok at gmail.com Wed Nov 3 13:29:39 2010 From: modulok at gmail.com (Modulok) Date: Wed, 3 Nov 2010 06:29:39 -0600 Subject: [Tutor] True Random Numbers In-Reply-To: References: Message-ID: On 11/2/10, Crallion wrote: > In an attempt to generate "true" random numbers, I found this python script- > http://code.google.com/p/truerandom/ > Getting to the point, I get this error when I run my program. > > File "/dev/python/absolute/truerandom.py", line 9, in > from urllib import urlopen > ImportError: cannot import name urlopen > > Is urllib and/or urlopen deprecated in 3.1.2 or is it something I forgot to > do? > Python is running on OSX 10.6, which I upgraded from the default install to > 3.1.2. The only 'true' source of entropy is a hardware random number generator. For cryptographic work you don't need this. All you need is a seemingly endless unpredictable sequence of bits. For this purpose, a cryptographically secure pseudo random number generator will do nicely. Furthermore, if your intent was for encryption, you shouldn't be getting your entropy over the wire for obvious reasons. (Speed and security.) With your stress on 'true' random numbers, I can only assume your intent is encryption. That said, use the operating system's random number generator. This will vary from system to system in how it is implemented, but all systems have one which is suitable for cryptographic purposes. On *NIX flavors this will be /dev/random. You can either read from this file directly to get a random stream of bits, or use the python standard library to interface with it to do things like get random numbers (as others have pointed out.) Whether reads to this, or calls which use this, will block, waiting for a suitable amount of entropy, depends on the system your code runs on. For example on FreeBSD both '/dev/random' and '/dev/urandom' are always non-blocking. FreeBSD uses a crypto secure 256-bit pseudo random number generator based on yarrow. The same is true for Mac OS X and AIX. On linux '/dev/random' will block if the entropy pool is exhausted, while '/dev/urandom' will not, but is still considered cryptographically secure. (And far better than any home brewed solution.) Also remember, 'pseudo-random' doesn't mean 'almost random,' it means deterministic *if you know the initial state*. (This is only true of some generators though, as some perturb their state with external sources of entropy on a regular basis.) On python you can get random numbers through the operating system's '/dev/urandom' (or on Windows, CryptGenRandom ): # Python example of getting secure, random numbers using the standard library: # This works in python 2.4 and greater on most systems: import random foo = random.SystemRandom() # Uses /dev/urandom or Windows CryptGenRandom # Print 10 random numbers: for i in range(10): foo.random() What are you using the random numbers for? -Modulok- From patty at cruzio.com Thu Nov 4 05:24:00 2010 From: patty at cruzio.com (patty at cruzio.com) Date: Wed, 3 Nov 2010 21:24:00 -0700 (PDT) Subject: [Tutor] Displaying picture and Text Message-ID: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> Hi - I am running Python 2.6.6 on my HP netbook with Windows 7. The default picture viewer is set to HP Photo Viewer. I am working on a part of my python program where a picture is supposed to display with a few lines of text below it. Ideally, I would like this to stay on the screen for a short period of time (2 minutes?) but I am using raw_input() for now. I imported the Image library and when I run the program below, it brings up a window (stdout or python?) with cursor flashing for a few seconds and then the HP Photo Viewer comes up with the picture, I close this window and then my text comes up in a python window. import Image fhdl = Image.open("C:\Users\StarShip\PyProgs\\bbsparkle.gif") fhdl.show() print "here is some test text test text test text" print "here is some more test text test text test text" print "here is even more of some test text test text test text" raw_input("press any key to continue") How do I get any picture to display on half a screen then my print text display below that and stay on screen for 2 or 3 minutes before I call another function that will redraw the screen anyway - it will be interactive text responses with the user. Also this is a test .gif file, I may want to just edit the source file and change this to a .jpg. I don't want to change the system defaults for this, maybe for the picture itself if that is necessary. Thanks Patty From alan.gauld at btinternet.com Thu Nov 4 09:58:10 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Nov 2010 08:58:10 -0000 Subject: [Tutor] Displaying picture and Text References: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> Message-ID: wrote > of my python program where a picture is supposed to display with a > few > lines of text below it. To do this you will need to use some kind of GUI. The simplest option is probably to use the Text widget in Tkinter which can display both Images and text. > Ideally, I would like this to stay on the screen > for a short period of time (2 minutes?) You would do that with a Timer event in Tkinter. > import Image > > fhdl = Image.open("C:\Users\StarShip\PyProgs\\bbsparkle.gif") > fhdl.show() I've never used Image but I assume the show() method just invokes the default viewer on the system. > print "here is some test text test text test text" > print "here is some more test text test text test text" > print "here is even more of some test text test text test text" print will always go to stdout, wherever that is defined to be.. > How do I get any picture to display on half a screen then my print > text > display below that and stay on screen for 2 or 3 minutes before I > call > another function that will redraw the screen anyway - it will be > interactive text responses with the user. Also this is a test .gif > file, > I may want to just edit the source file and change this to a .jpg. The Tkinter PhotoImage object can display jpg. I can't recall if it does gifs. If you want to habndle many types yoyu may need to look at using an image convertion library too. > I don't want to change the system defaults for this, maybe for the > picture > itself if that is necessary. That should not be necessary, if you tell Python the filepath it can load the specific file you select. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Thu Nov 4 10:00:51 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 04 Nov 2010 09:00:51 +0000 Subject: [Tutor] Displaying picture and Text In-Reply-To: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> References: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> Message-ID: <4CD27643.9040009@timgolden.me.uk> On 04/11/2010 04:24, patty at cruzio.com wrote: > Hi - I am running Python 2.6.6 on my HP netbook with Windows 7. The > default picture viewer is set to HP Photo Viewer. I am working on a part > of my python program where a picture is supposed to display with a few > lines of text below it. Ideally, I would like this to stay on the screen > for a short period of time (2 minutes?) but I am using raw_input() for > now. > > I imported the Image library and when I run the program below, it brings > up a window (stdout or python?) with cursor flashing for a few seconds and > then the HP Photo Viewer comes up with the picture, I close this window > and then my text comes up in a python window. The Image.show function in the PIL is simply a convenience for doing a quick-and-dirty "What does this image look like?". It hands off to the default image viewer -- as you discovered. It's not intended for use in a production program which needs to control image size, placement etc. There probably *are* image viewers which you could control from the command line to display what you want, but if you're going to need a solution involving text and images, just use one of the existing GUI toolkits: wxPython, PyQt or others (just search for "Python GUI") which let you display text, images etc. with complete control. TJG From alan.gauld at btinternet.com Thu Nov 4 10:15:14 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Nov 2010 09:15:14 -0000 Subject: [Tutor] Displaying picture and Text References: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> Message-ID: "Alan Gauld" wrote >> ...a picture is supposed to display with a few >> lines of text below it. > > To do this you will need to use some kind of GUI. > The simplest option is probably to use the Text widget in Tkinter I just had a thought. The simplest option might be to use HTML to create a simple web page and display that in a browser. However the extra features you require will probably be easier in a GUI.But its another option to consider. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Thu Nov 4 12:06:58 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 4 Nov 2010 06:06:58 -0500 Subject: [Tutor] Displaying picture and Text In-Reply-To: References: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> Message-ID: On Thu, Nov 4, 2010 at 3:58 AM, Alan Gauld wrote: > > wrote > > > of my python program where a picture is supposed to display with a few >> lines of text below it. >> > > To do this you will need to use some kind of GUI. > The simplest option is probably to use the Text widget in Tkinter > which can display both Images and text. I'll second the motion. You can probably write the most basic functions in less than 50 lines > How do I get any picture to display on half a screen then my print text >> display below that and stay on screen for 2 or 3 minutes before I call >> another function that will redraw the screen anyway - it will be >> interactive text responses with the user. Also this is a test .gif file, >> I may want to just edit the source file and change this to a .jpg. >> > > The Tkinter PhotoImage object can display jpg. I can't recall if > it does gifs. If you want to habndle many types yoyu may need to > look at using an image convertion library too. PIL (What you have installed to use the Image library) allows you to convert basically any image to a format you can use in Tkinter. There is a short example here: http://stackoverflow.com/questions/1236540/how-do-i-use-pil-with-tkinter HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From patty at cruzio.com Thu Nov 4 17:38:49 2010 From: patty at cruzio.com (Patty) Date: Thu, 4 Nov 2010 09:38:49 -0700 Subject: [Tutor] Displaying picture and Text References: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> <4CD27643.9040009@timgolden.me.uk> Message-ID: Thank you for all the replies - I think I will want to use Tkinter since it also has the timer I am looking for and I do have one book that has a big chapter on using Tkinter. If I find that I am having trouble understanding Python GUI programming. I may be able to copy some code from the book or I will use a workaround of skipping the picture part temporarily, I am sure with time it will all come together. I am liking Python programming! I pretty much consider myself a C programmer plus know several other programming and database querying languages. Patty From alan.gauld at btinternet.com Thu Nov 4 18:39:32 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 4 Nov 2010 17:39:32 -0000 Subject: [Tutor] Displaying picture and Text References: <323226b363ecad110ee82883c3c0df50.squirrel@cruziomail.cruzio.com> Message-ID: "Alan Gauld" wrote >> fhdl = Image.open("C:\Users\StarShip\PyProgs\\bbsparkle.gif") >> fhdl.show() > The Tkinter PhotoImage object can display jpg. I can't recall if > it does gifs. Sorry I got that wrong, it can display gifs but not jpgs (despite the fact that jpgs are used more often for photos than gifs!) So you will need to convert the jpg to a gif - which might lose a lot of quality! Anyone know of a way to get decent quality in a Tkinter image? Is there any support in PIL itself? Alan G. From fal at libero.it Thu Nov 4 20:02:41 2010 From: fal at libero.it (Francesco Loffredo) Date: Thu, 04 Nov 2010 20:02:41 +0100 Subject: [Tutor] if statement In-Reply-To: <1288724838.15073.2.camel@ubuntu-desktop.core> References: <1288724535.15073.0.camel@ubuntu-desktop.core> <1288724838.15073.2.camel@ubuntu-desktop.core> Message-ID: <4CD30351.8080705@libero.it> On 02/11/2010 20.07, Glen Clark wrote: > sorry: > > NumItems = int(input("How many Items: ")) > > > Entries = [] > for In in range(0,NumItems): > Entries.append("") > > > > for In in range(0,NumItems): > Entries[In]=str(input("Enter name " + str(In+1) + ": ")) > > > for In in range(0,NumItems): > print(Entries[In]) > > confirmed = int(input("Are you happy with this? (y/n): ") > > if confirmed == "y": > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = int(input("Which item would you like to change: ") > Entries[change]=str(input("Please enter a nem name: ") > else: > #do nothing > > print(Entries) > >> On 11/2/10, Glen Clark wrote: >>> File "/home/glen/workspace/test.py", line 19 >>> if confirmed == "y": >>> ^ >>> SyntaxError: invalid syntax It seems to me that when you wrote the request for confirmation you just copied and pasted part of the first line, changing the variable name to 'confirmed'. But you were expecting a string, so you should delete the leading "int(" part of that statement, what you forgot to do: confirmed = input("Are you happy with this? (y/n): ") So the problem was not in the missing ending parenthesis, but in those four characters in excess. A very similar mistake is in the request for a new name for Entries[change]: remember that input() ALWAYS returns a string. Entries[change]=input("Please enter a new name: ") Finally, as others have pointed out, you should put a pass statement after the else clause, or delete it altogether: > if confirmed == "y": > for In in range(0,NumItems): > print(Entries[In] + ": " + str(In)) > change = input("Which item would you like to change: ") > Entries[change]=input("Please enter a nem name: ") #the following two lines may be safely deleted, or must be BOTH there > else: > pass Hope that helps, Francesco -------------- next part -------------- Nessun virus nel messaggio in uscita. Controllato da AVG - www.avg.com Versione: 9.0.864 / Database dei virus: 271.1.1/3235 - Data di rilascio: 11/03/10 09:36:00 From jbiquez at icsmx.com Thu Nov 4 20:43:55 2010 From: jbiquez at icsmx.com (Jorge Biquez) Date: Thu, 04 Nov 2010 13:43:55 -0600 Subject: [Tutor] Advantages or disadvantages on Platform? Message-ID: <201011041952.oA4JqFtH096400@krusty.intranet.com.mx> Hello all. I am newbie and studying and working hard learning python. Per your advise I am on 2.7 . I have one question for you. I can work on Windows (XP) or under Ubuntu . Do you see any advantages or disadvantanges to be working in one or another ? My main goal , for now, is use Python for web applictions. Thanks in advance for your comments and advice. Jorge Biquez From glenuk at gmail.com Thu Nov 4 21:10:01 2010 From: glenuk at gmail.com (Glen Clark) Date: Thu, 4 Nov 2010 20:10:01 +0000 Subject: [Tutor] Looking for a tutor to review my code and provide constructive feedback. Message-ID: Hello, I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling "python projects for beginners". The idea was to create a script that asked the user to input a list of names and allow the user to change a name if he wanted before confirming the entries. I tried to incorporate what I had learnt from the videos, such as conditionals, error handling, functions etc... and write it how I would write code in future. Please if you are kind enougth to take the time to provide feedback I would appreciate that it is constructive :) The script is here: http://bpaste.net/show/10658/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Nov 4 21:21:55 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 4 Nov 2010 16:21:55 -0400 Subject: [Tutor] Advantages or disadvantages on Platform? In-Reply-To: <201011041952.oA4JqFtH096400@krusty.intranet.com.mx> References: <201011041952.oA4JqFtH096400@krusty.intranet.com.mx> Message-ID: <018101cb7c5d$ed69ae80$c83d0b80$@rr.com> > -----Original Message----- > From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor- > bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Jorge Biquez > Sent: Thursday, November 04, 2010 3:44 PM > To: tutor at python.org > Subject: [Tutor] Advantages or disadvantages on Platform? > > Hello all. > > I am newbie and studying and working hard learning python. Per your > advise I am on 2.7 . I have one question for you. > > I can work on Windows (XP) or under Ubuntu . > > Do you see any advantages or disadvantanges to be working in one or > another ? Do you see any reasons for not working in both environments? Robert _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- I am using the free version of SPAMfighter. We are a community of 7 million users fighting spam. SPAMfighter has removed 34 of my spam emails to date. Get the free SPAMfighter here: http://www.spamfighter.com/len The Professional version does not have this message From knacktus at googlemail.com Thu Nov 4 21:28:50 2010 From: knacktus at googlemail.com (Knacktus) Date: Thu, 04 Nov 2010 21:28:50 +0100 Subject: [Tutor] Advantages or disadvantages on Platform? In-Reply-To: <201011041952.oA4JqFtH096400@krusty.intranet.com.mx> References: <201011041952.oA4JqFtH096400@krusty.intranet.com.mx> Message-ID: <4CD31782.1000504@googlemail.com> Am 04.11.2010 20:43, schrieb Jorge Biquez: > Hello all. > > I am newbie and studying and working hard learning python. Per your > advise I am on 2.7 . I have one question for you. > > I can work on Windows (XP) or under Ubuntu . > The advantage of using Ubuntu is that you learn how to work in a Linux/Unix environment. Most servers are using Linux/Unix based operation systems. Therefore if your goal is to develop web-apps, I would go for Ubuntu. Also, once you've set up your development environment and know how to work with your shell, working on Linux is incredible fast and fun. I used to work professionally for engineering stuff on Linux/Unix before moving to Windows. Productivity on Linux for OS operations like organising your files and quickly modifing scripts is by far higher than on Windows. Another advantage is, that there're good editors well integrated. If you have the time to learn vim, go for it. After telling you all this, I have to admit that I'm currently on a Windows 7 machine and also perfectly happy. Using an IDE makes the OS less important. > Do you see any advantages or disadvantanges to be working in one or > another ? > My main goal , for now, is use Python for web applictions. > > Thanks in advance for your comments and advice. > > Jorge Biquez > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Thu Nov 4 23:33:42 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 4 Nov 2010 17:33:42 -0500 Subject: [Tutor] Looking for a tutor to review my code and provide constructive feedback. In-Reply-To: References: Message-ID: <82E8BCBE-DC0D-4C2D-B1F4-E6E6C9682732@gmail.com> Your code is not bad overall, pretty great for a beginner actually. I would say you should read guido's style guide though; some of your variable and function naming is nonstandard python. ----------------------------- Sent from a mobile device with a bad e-mail client. ----------------------------- On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: > Hello, > > I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling "python projects for beginners". > > The idea was to create a script that asked the user to input a list of names and allow the user to change a name if he wanted before confirming the entries. > > I tried to incorporate what I had learnt from the videos, such as conditionals, error handling, functions etc... and write it how I would write code in future. > > Please if you are kind enougth to take the time to provide feedback I would appreciate that it is constructive :) > > The script is here: http://bpaste.net/show/10658/ > _______________________________________________ > 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 rabidpoobear at gmail.com Thu Nov 4 23:36:12 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 4 Nov 2010 17:36:12 -0500 Subject: [Tutor] Looking for a tutor to review my code and provide constructive feedback. In-Reply-To: References: Message-ID: <3A0451A5-B9BB-4E21-9F77-04B75C21D990@gmail.com> Also for your confirm entries function, read about while loops ----------------------------- Sent from a mobile device with a bad e-mail client. ----------------------------- On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: > Hello, > > I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling "python projects for beginners". > > The idea was to create a script that asked the user to input a list of names and allow the user to change a name if he wanted before confirming the entries. > > I tried to incorporate what I had learnt from the videos, such as conditionals, error handling, functions etc... and write it how I would write code in future. > > Please if you are kind enougth to take the time to provide feedback I would appreciate that it is constructive :) > > The script is here: http://bpaste.net/show/10658/ > _______________________________________________ > 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 rabidpoobear at gmail.com Thu Nov 4 23:38:55 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 4 Nov 2010 17:38:55 -0500 Subject: [Tutor] Looking for a tutor to review my code and provide constructive feedback. In-Reply-To: References: Message-ID: Also for your confirm entries read about sentinel values for while loops. It saves you repeating the conditional in the loop body. And you might want to .lower().strip()[0] the input choice so that they can use y, Y, yes, or whatever. Remember, users suck at generating accurate and correct input so don't give them any credit you can avoid. ----------------------------- Sent from a mobile device with a bad e-mail client. ----------------------------- On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: > Hello, > > I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling "python projects for beginners". > > The idea was to create a script that asked the user to input a list of names and allow the user to change a name if he wanted before confirming the entries. > > I tried to incorporate what I had learnt from the videos, such as conditionals, error handling, functions etc... and write it how I would write code in future. > > Please if you are kind enougth to take the time to provide feedback I would appreciate that it is constructive :) > > The script is here: http://bpaste.net/show/10658/ > _______________________________________________ > 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 quasipedia at gmail.com Fri Nov 5 00:20:50 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 05 Nov 2010 00:20:50 +0100 Subject: [Tutor] argparse: how to use the returned Namespace object? Message-ID: <1288912850.30441.91.camel@jabbar> Hi, I'm writing a small command line utility using the argparse module (I am on python 2.6.6 so that's not in the standard lib, but this should not play any role in my problem, I believe). My goal is to use a class that I already wrote and cannot change for a GUI app, as a command utility, so I would like to simply have the CLI as a wrapping layer, without changing the pre-existing code. The code I want to reuse, accept all keywords arguments, so I wrote my parser in such a way that it returns keywords/values in a compatible way to my method signatures. Example: Let the signature of one of my functions be: def do_stuff(overwrite=False, verbose=False): do-some-stuff-here I wrote the parser in such a way that issuing: utilityname dostuff --overwrite --verbose I get at the end of the parsing process a variable "args" that looks like this: Namespace(command=dostuff, overwrite=True, verbose=True) Now, I tried to do the following: command = args.command del args.command command(**args) But that doesn't work because the Namespace implementation of the argparse result is an object which is not iterable. Of course if I use: args.command(overwrite=args.overwrite, verbose=args.verbose) I get the system working, but the fact is that each command calls a different function / method, each of them with a different signature. My question boils down to: how can I expand the Namespace object in order to get a list of keyword arguments? Thank you for your time, Mac. From wprins at gmail.com Fri Nov 5 01:17:01 2010 From: wprins at gmail.com (Walter Prins) Date: Fri, 5 Nov 2010 00:17:01 +0000 Subject: [Tutor] argparse: how to use the returned Namespace object? In-Reply-To: <1288912850.30441.91.camel@jabbar> References: <1288912850.30441.91.camel@jabbar> Message-ID: On 4 November 2010 23:20, Mac Ryan wrote: > My question boils down to: how can I expand the Namespace object in > order to get a list of keyword arguments? > If "ns" is your Namespace object, then use ns.__dict__, which you can directly pass to your commands, e.g. do_stuff(**ns.__dict__) I'll post a more complete answer if this isn't clear/obvious. HTH Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Fri Nov 5 01:40:59 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 05 Nov 2010 01:40:59 +0100 Subject: [Tutor] argparse: how to use the returned Namespace object? In-Reply-To: References: <1288912850.30441.91.camel@jabbar> Message-ID: <1288917659.30441.138.camel@jabbar> On Fri, 2010-11-05 at 00:17 +0000, Walter Prins wrote: > > > On 4 November 2010 23:20, Mac Ryan wrote: > My question boils down to: how can I expand the Namespace > object in > order to get a list of keyword arguments? > > If "ns" is your Namespace object, then use ns.__dict__, which you can > directly pass to your commands, e.g. > > do_stuff(**ns.__dict__) > > I'll post a more complete answer if this isn't clear/obvious. > > HTH Thank you Walter. I got it and it works! :) I have a follow-up question, though. I had previously already inspected "ns.__dict__" with the "dir()" function, but couldn't (and can not) see my parameters neither with "dir(ns.__dict__)" nor with "dir(ns.__dict__.items)". This is clearly an indication that I misunderstand what the __dict__ is and how it works. Yet if I do a dir() on an instance of an object, it does work as expected, returning all attributes of that object. Could you (on anybody else!) help me undertand what I fail to grasp? Thank you! Mac. From g.nius.ck at gmail.com Fri Nov 5 01:43:39 2010 From: g.nius.ck at gmail.com (Chris King) Date: Thu, 04 Nov 2010 20:43:39 -0400 Subject: [Tutor] Server Message-ID: <4CD3533B.1030900@gmail.com> Dear Tutors, May server and client programs aren't working. They basically simplify socket and SocketServer. Run them directly to test them. They do work locally. They don't work from one computer to the next on the same network. Please Help. Sincerely, Me, Myself, and I P.S. How to you stop a server loop and open up the port? From steve at pearwood.info Fri Nov 5 02:03:51 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 05 Nov 2010 12:03:51 +1100 Subject: [Tutor] Server In-Reply-To: <4CD3533B.1030900@gmail.com> References: <4CD3533B.1030900@gmail.com> Message-ID: <4CD357F7.1060705@pearwood.info> Chris King wrote: > Dear Tutors, > May server and client programs aren't working. They basically > simplify socket and SocketServer. Run them directly to test them. They > do work locally. They don't work from one computer to the next on the > same network. Please Help. It's probably a network issue. Consult with your network administrator. Perhaps the firewall is blocking something? > P.S. How to you stop a server loop and open up the port? What's a server loop? What firewall are you using? -- Steven From wprins at gmail.com Fri Nov 5 02:11:52 2010 From: wprins at gmail.com (Walter Prins) Date: Fri, 5 Nov 2010 01:11:52 +0000 Subject: [Tutor] argparse: how to use the returned Namespace object? In-Reply-To: <1288917659.30441.138.camel@jabbar> References: <1288912850.30441.91.camel@jabbar> <1288917659.30441.138.camel@jabbar> Message-ID: On 5 November 2010 00:40, Mac Ryan wrote: > > Thank you Walter. I got it and it works! :) > Excellent. I thought I'd mention here you can also create your own Namespace object (e.g. if you find accessing __dict__ not ideal or something you can do your own implementation, which will work as long as it's got the neccesary features.) > I had previously already inspected "ns.__dict__" with the "dir()" > function, but couldn't (and can not) see my parameters neither with > "dir(ns.__dict__)" nor with "dir(ns.__dict__.items)". This is clearly an > indication that I misunderstand what the __dict__ is and how it works. > You need to distinguish between what __dict__ *is*, and what it *contains*. dir() does introspection, it inspects what an object in Python *is*, e.g. displays all the methods and attributes of the object. It does not however know anything about what (if anything) the object might contain, in the data storage sense. A dictionary object is a specific type of container object, it has many methods but suffice it to say the data (keys and values) inside it are obviously not explicitly exposed as attribues of the dict object itself. So then, dir() on a dict object, shows you the methods and attributes of dict's, but nothing of what data might be inside the dict. Similarly when you dir() your own instance of an object with some custom attributes, then likewise, dir() on the object itself will show you the members and attribues of that object itself. Now, Python makes available a read-only, "hidden" attribute on all objects (e.g. a chiled member/object) called "__dict__", into which it encodes the actual attributes of that object, as key value pairs. So... if you dir() the object *itself*, you get information about *its* attributes, if you however dir() the dict that's part of that object, you'll get a dict's properties, not what is contained inside of the dicts. Best, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Fri Nov 5 09:32:43 2010 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 5 Nov 2010 01:32:43 -0700 Subject: [Tutor] Looking for a tutor to review my code and provideconstructive feedback. References: Message-ID: "Glen Clark" wrote in message news:AANLkTimaBbj8ae35q3aO9+XZBvtnyZbZ3WRudahmN+hf at mail.gmail.com... > Hello, > > I have completed my first python script. This is after watching a video > guide on python and is my first attempt at writing code in python. While > the > code is not very useful I got the idea for it when googling "python > projects > for beginners". > > The idea was to create a script that asked the user to input a list of > names > and allow the user to change a name if he wanted before confirming the > entries. > > I tried to incorporate what I had learnt from the videos, such as > conditionals, error handling, functions etc... and write it how I would > write code in future. > > Please if you are kind enougth to take the time to provide feedback I > would > appreciate that it is constructive :) > > The script is here: http://bpaste.net/show/10658/ Your code is very readable...more so than some experienced people ;^) A few suggestions (and assuming Python 3.X, since that's what it looks like): * "list" shadows a built-in type, and should not be used for variable names. "names" would be more appropriate. * input() return a string, so no need for str(input(...)). * range(x) is equivalent to range(0,x). * The two loops in InitiateEntries can be consolidated: for In in range(NumItems): names.append(input("Enter name {}: ".format(In+1))) Or using a list comprehension: names = [input("Enter name {}: ".format(In+1) for In in range(NumItems)] * Prefer "for name in names:" instead of using indexing, or "for idx,name in enumerate(names):" if indexes are needed. Example: for idx,name in enumerate(names): print("{}: {}".format(idx,name) * Since 1-based indexing was used elsewhere to present names to the user, the PrintEntries display code should also use idx+1. * When returning a boolean value, you can simpify: if confirmed == 'n': return True else: return False To: return confirmed == 'n' Also see PEP8 (http://www.python.org/dev/peps/pep-0008/) for Python's suggested coding standard. -Mark From alan.gauld at btinternet.com Fri Nov 5 09:30:24 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 5 Nov 2010 08:30:24 +0000 (GMT) Subject: [Tutor] Fw: rights In-Reply-To: References: <4CCF1DA5.2020904@gmail.com> <4CCF3975.7070901@gmail.com> Message-ID: <502933.33449.qm@web86707.mail.ird.yahoo.com> fowarding to group, please use reply-all when replying. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ---- > From: Chris King > To: Alan Gauld > Sent: Friday, 5 November, 2010 0:48:51 > Subject: Re: [Tutor] rights > > On 11/1/2010 8:43 PM, Alan Gauld wrote: > > > > "Chris King" wrote > > > >>> You give the user account executing the script rights to read the folder. > >>> > >>> HTH, > >>> > >> It was a folder on my desktop, which I can always read, right, and destroy. >I ran it on that user. > > > > In that case we probably need to see: > > > > 1) What OS? > > > > 2) What does the code look like? > > > > 3) How are you running it? > > > > 4) What error messages do you get? > > > > Also, is it a folder you are trying to read or a file? > > They are not the same. > > > > > I'm trying to get the raw binary of a file in linux or windows. > When I run: > > f = open('C:/Documents and Settings/family/Desktop/Tuxpaint', 'rb') > > in Windows, it raises: > > Traceback (most recent call last): > File "", line 1, in > f = open('C:/Documents and Settings/family/Desktop/Tuxpaint', 'rb') > IOError: [Errno 13] Permission denied: 'C:/Documents and >Settings/family/Desktop/Tuxpaint' > > Can you help? > From quasipedia at gmail.com Fri Nov 5 10:44:43 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 05 Nov 2010 10:44:43 +0100 Subject: [Tutor] argparse: how to use the returned Namespace object? In-Reply-To: References: <1288912850.30441.91.camel@jabbar> <1288917659.30441.138.camel@jabbar> Message-ID: <1288950283.30441.143.camel@jabbar> On Fri, 2010-11-05 at 01:11 +0000, Walter Prins wrote: > You need to distinguish between what __dict__ *is*, and what it > *contains*. dir() does introspection, it inspects what an object in > Python *is*, e.g. displays all the methods and attributes of the > object. It does not however know anything about what (if anything) > the object might contain, in the data storage sense. [...] Thank you Walter, now I got it. :) Mac. From garry.willgoose at newcastle.edu.au Fri Nov 5 12:15:26 2010 From: garry.willgoose at newcastle.edu.au (Garry Willgoose) Date: Fri, 5 Nov 2010 22:15:26 +1100 Subject: [Tutor] querying the name of a calling python file Message-ID: For a while now I have been using the command below in a python file to determine the name of the python file that I use to launch an application (i.e.IF I go 'python junk.py' I want to get 'junk.py'). The command I have use that I came across somewhere some time ago was sys.modules['__main__'].__dict__['__file__'] Now this works fine for the standard python interpretter but when I use ipython (I'm using the enthought distribution 6.1) this command returns /Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/IPython/FakeModule.py I discovered this when I was tracking down inconsistencies/errors between the matplotlib in the enthought distribution depending on whether you use python or ipython. My question is this: Is the way I'm getting the file name the recommended way or did I pick up a bit of flaky advice? I'm puzzled by the matplot lib errors (the y axes on imgshow() show problems in python but appear to 1st order to be OK in ipython) ... but I'll pursue that at the Matplotlib, enthought and ipython forums once I've been able to run a broader cross-section of my codes. ==================================================================== Prof Garry Willgoose, Australian Professorial Fellow in Environmental Engineering, Director, Centre for Climate Impact Management (C2IM), School of Engineering, The University of Newcastle, Callaghan, 2308 Australia. Centre webpage: www.c2im.org.au Phone: (International) +61 2 4921 6050 (Tues-Fri AM); +61 2 6545 9574 (Fri PM-Mon) FAX: (International) +61 2 4921 6991 (Uni); +61 2 6545 9574 (personal and Telluric) Env. Engg. Secretary: (International) +61 2 4921 6042 email: garry.willgoose at newcastle.edu.au; g.willgoose at telluricresearch.com email-for-life: garry.willgoose at alum.mit.edu personal webpage: www.telluricresearch.com/garry ==================================================================== "Do not go where the path may lead, go instead where there is no path and leave a trail" Ralph Waldo Emerson ==================================================================== From shantanoo at gmail.com Fri Nov 5 12:24:17 2010 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Fri, 5 Nov 2010 16:54:17 +0530 Subject: [Tutor] querying the name of a calling python file In-Reply-To: References: Message-ID: <44755649-16A9-47F5-8525-7BC28E27FCFA@gmail.com> On 05-Nov-2010, at 4:45 PM, Garry Willgoose wrote: > For a while now I have been using the command below in a python file to determine the name of the python file that I use to launch an application (i.e.IF I go 'python junk.py' I want to get 'junk.py'). The command I have use that I came across somewhere some time ago was > > sys.modules['__main__'].__dict__['__file__'] > > Now this works fine for the standard python interpretter but when I use ipython (I'm using the enthought distribution 6.1) this command returns > > /Library/Frameworks/Python.framework/Versions/6.1/lib/python2.6/site-packages/IPython/FakeModule.py > > I discovered this when I was tracking down inconsistencies/errors between the matplotlib in the enthought distribution depending on whether you use python or ipython. My question is this: Is the way I'm getting the file name the recommended way or did I pick up a bit of flaky advice? > > I'm puzzled by the matplot lib errors (the y axes on imgshow() show problems in python but appear to 1st order to be OK in ipython) ... but I'll pursue that at the Matplotlib, enthought and ipython forums once I've been able to run a broader cross-section of my codes. > Try the following code: === #!/usr/bin/env python import sys print sys.argv === From glenuk at gmail.com Fri Nov 5 12:31:31 2010 From: glenuk at gmail.com (Glen Clark) Date: Fri, 5 Nov 2010 11:31:31 +0000 Subject: [Tutor] Looking for a tutor to review my code and provideconstructive feedback. In-Reply-To: References: Message-ID: *#Your code is very readable...more so than some experienced people ;^)* Thank you, that is very motivating that I am at least on the right track! #A few suggestions (and assuming Python 3.X, since that's what it looks like): Yeah it is 3.1, forgot to mention that. # * "list" shadows a built-in type, and should not be used for variable names. "names" would be more appropriate. I used list as it was a list and therefore new what argument to pass. I did not even consider that this would be confusing! Thank you for pointing it out. # * input() return a string, so no need for str(input(...)). # * range(x) is equivalent to range(0,x). Thank you, I will note these for future code :) #* The two loops in InitiateEntries can be consolidated: Thank you, Seems a much better way or doing it. #* Prefer "for name in names:" instead of using indexing, or "for idx,name in enumerate(names):" if indexes are needed. Example: # * Since 1-based indexing was used elsewhere to present names to the user, the PrintEntries display code should also use idx+1 I thought that by using an index would be an easy way for the user to select which element of the list to edit. Not seem the enumerate keyword before so I will look up what that does :) . # * When returning a boolean value, you can simpify: Ah, thank you! Really useful feedback, I will note the points highlighted for my next mini-project. I feel it is important that I am writing proper code before moving onto learning modules and such. On 5 November 2010 08:32, Mark Tolonen > wrote: > > "Glen Clark" wrote in message > news:AANLkTimaBbj8ae35q3aO9+XZBvtnyZbZ3WRudahmN+hf at mail.gmail.com... > > Hello, >> >> I have completed my first python script. This is after watching a video >> guide on python and is my first attempt at writing code in python. While >> the >> code is not very useful I got the idea for it when googling "python >> projects >> for beginners". >> >> The idea was to create a script that asked the user to input a list of >> names >> and allow the user to change a name if he wanted before confirming the >> entries. >> >> I tried to incorporate what I had learnt from the videos, such as >> conditionals, error handling, functions etc... and write it how I would >> write code in future. >> >> Please if you are kind enougth to take the time to provide feedback I >> would >> appreciate that it is constructive :) >> >> The script is here: http://bpaste.net/show/10658/ >> > > Your code is very readable...more so than some experienced people ;^) > > A few suggestions (and assuming Python 3.X, since that's what it looks > like): > > * "list" shadows a built-in type, and should not be used for variable > names. "names" would be more appropriate. > * input() return a string, so no need for str(input(...)). > * range(x) is equivalent to range(0,x). > * The two loops in InitiateEntries can be consolidated: > > for In in range(NumItems): > names.append(input("Enter name {}: ".format(In+1))) > > Or using a list comprehension: > > names = [input("Enter name {}: ".format(In+1) for In in > range(NumItems)] > > * Prefer "for name in names:" instead of using indexing, or "for idx,name > in enumerate(names):" if indexes are needed. Example: > > for idx,name in enumerate(names): > print("{}: {}".format(idx,name) > > * Since 1-based indexing was used elsewhere to present names to the user, > the PrintEntries display code should also use idx+1. > * When returning a boolean value, you can simpify: > > if confirmed == 'n': > return True > else: > return False > > To: > > return confirmed == 'n' > > Also see PEP8 (http://www.python.org/dev/peps/pep-0008/) for Python's > suggested coding standard. > > -Mark > > > > _______________________________________________ > 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 glenuk at gmail.com Fri Nov 5 12:33:04 2010 From: glenuk at gmail.com (Glen Clark) Date: Fri, 5 Nov 2010 11:33:04 +0000 Subject: [Tutor] Looking for a tutor to review my code and provide constructive feedback. In-Reply-To: References: Message-ID: Thank you very much for the feedback Luke. I have taken it onboard. I especially like the .lower().strip()[0] method ^^ Regards, G On 4 November 2010 22:38, Luke Paireepinart wrote: > Also for your confirm entries read about sentinel values for while loops. > It saves you repeating the conditional in the loop body. And you might want > to .lower().strip()[0] the input choice so that they can use y, Y, yes, or > whatever. Remember, users suck at generating accurate and correct input so > don't give them any credit you can avoid. > > > ----------------------------- > Sent from a mobile device with a bad e-mail client. > ----------------------------- > > On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: > > Hello, > > I have completed my first python script. This is after watching a video > guide on python and is my first attempt at writing code in python. While the > code is not very useful I got the idea for it when googling "python projects > for beginners". > > The idea was to create a script that asked the user to input a list of > names and allow the user to change a name if he wanted before confirming the > entries. > > I tried to incorporate what I had learnt from the videos, such as > conditionals, error handling, functions etc... and write it how I would > write code in future. > > Please if you are kind enougth to take the time to provide feedback I would > appreciate that it is constructive :) > > The script is here: > http://bpaste.net/show/10658/ > > _______________________________________________ > > 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 Fri Nov 5 19:28:28 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Nov 2010 18:28:28 -0000 Subject: [Tutor] Looking for a tutor to review my code and provideconstructive feedback. References: Message-ID: "Glen Clark" wrote > Really useful feedback, I will note the points highlighted for my > next > mini-project. I feel it is important that I am writing proper code > before > moving onto learning modules and such. I wouldn't sweat over it. Modules are at the heart of Python and restricting yourself to the core language should not be necessary. Learning the modules and what they can do for you is at least as important as getting every last idiom perfect - after all, a lot of that stuff is ultimately a matter of personal style and taste. Readable code is a great target, but (re)using modules rather than writing from scratch is another way to make your code both more readable and more reliable. Regards, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Nov 5 19:34:44 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 5 Nov 2010 18:34:44 -0000 Subject: [Tutor] querying the name of a calling python file References: Message-ID: "Garry Willgoose" wrote > For a while now I have been using the command below in a python file > to determine the name of the python file that I use to launch an > application > > sys.modules['__main__'].__dict__['__file__'] The usual way to do that would be via sys.argv[0] Is there any reason why you are using the method above? Any time you find yourself using __xxx__ type names it suggests that you are getting in too deep! :-) There is usually a simpler alternative. If I see three double-underscores in one line I know I'm either delving in very deep or missing a trick... > Is the way I'm getting the file name the recommended way or did > I pick up a bit of flaky advice? There may be cases where it will work and argv[0] won't but until you prove that you need it I'd go with argv[] -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From g.nius.ck at gmail.com Fri Nov 5 20:18:27 2010 From: g.nius.ck at gmail.com (Chris King) Date: Fri, 05 Nov 2010 15:18:27 -0400 Subject: [Tutor] Server In-Reply-To: <4CD36213.3060903@aim.com> References: <4CD3533B.1030900@gmail.com> <4CD36213.3060903@aim.com> Message-ID: <4CD45883.3090502@gmail.com> On 11/4/2010 9:46 PM, Corey Richardson wrote: > > > On 11/4/2010 8:43 PM, Chris King wrote: >> Dear Tutors, >> May server and client programs aren't working. They basically >> simplify socket and SocketServer. Run them directly to test them. >> They do work locally. They don't work from one computer to the next >> on the same network. Please Help. >> >> Sincerely, >> Me, Myself, and I >> >> P.S. How to you stop a server loop and open up the port? >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > When ever I have worked on network, it's always been a firewall issue. > If you are using Windows, turn off the built-in firewall. That's what > fixed my problems. > Hope it helped, > ~Corey make sure you click reply to all, so you don't just send it to me also, it is on the same network, so the server shouldn't be a problem From patty at cruzio.com Fri Nov 5 21:30:51 2010 From: patty at cruzio.com (Patty) Date: Fri, 5 Nov 2010 13:30:51 -0700 Subject: [Tutor] Displaying picture and Text & Downloads Message-ID: I just realized I did the same thing - must have hit reply to one instead of reply to all :} I had a followup question for you all - and would like to know the answer to Alan's question about print quality - below - Patty ----- Original Message ----- From: "Patty" To: "Alan Gauld" Sent: Thursday, November 04, 2010 11:14 AM Subject: Re: [Tutor] Displaying picture and Text > Yes, I would like to know this, I want this function to be really modular > and I thought of something else. If my solution turns out to be using > Tkinter functions only then wouldn't that mean I downloaded and am > 'import'ing the Image library for nothing? > > This might mean the second addon library I download the source and > documentation for. So how are people keeping their customized system > organized? I could come up with all sorts of scenarios of losing track of > libraries, having too many you never use, and doc you never use, etc. > > Patty > > ----- Original Message ----- > From: "Alan Gauld" > To: > Sent: Thursday, November 04, 2010 10:39 AM > Subject: Re: [Tutor] Displaying picture and Text > > >> >> "Alan Gauld" wrote >>>> fhdl = Image.open("C:\Users\StarShip\PyProgs\\bbsparkle.gif") >>>> fhdl.show() >> >>> The Tkinter PhotoImage object can display jpg. I can't recall if >>> it does gifs. >> >> Sorry I got that wrong, it can display gifs but not jpgs (despite the >> fact that jpgs are used more often for photos than gifs!) So you will >> need to convert the jpg to a gif - which might lose a lot of quality! >> >> Anyone know of a way to get decent quality in a Tkinter image? >> Is there any support in PIL itself? >> >> Alan G. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > From kb1pkl at aim.com Fri Nov 5 21:55:53 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 05 Nov 2010 16:55:53 -0400 Subject: [Tutor] Server In-Reply-To: <4CD45883.3090502@gmail.com> References: <4CD3533B.1030900@gmail.com> <4CD36213.3060903@aim.com> <4CD45883.3090502@gmail.com> Message-ID: <4CD46F59.3090108@aim.com> On 11/5/2010 3:18 PM, Chris King wrote: > On 11/4/2010 9:46 PM, Corey Richardson wrote: >> >> >> On 11/4/2010 8:43 PM, Chris King wrote: >>> Dear Tutors, >>> May server and client programs aren't working. They basically >>> simplify socket and SocketServer. Run them directly to test them. >>> They do work locally. They don't work from one computer to the next >>> on the same network. Please Help. >>> >>> Sincerely, >>> Me, Myself, and I >>> >>> P.S. How to you stop a server loop and open up the port? >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> When ever I have worked on network, it's always been a firewall >> issue. If you are using Windows, turn off the built-in firewall. >> That's what fixed my problems. >> Hope it helped, >> ~Corey > make sure you click reply to all, so you don't just send it to me > also, it is on the same network, so the server shouldn't be a problem It has nothing to do with a server, it's the firewall built into Windows. From carroll at tjc.com Fri Nov 5 22:42:37 2010 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Nov 2010 14:42:37 -0700 (PDT) Subject: [Tutor] Reading the CDROM in Linux Message-ID: I have a program that traverses the directory of a CDROM using os.walk. I do most of my work on Windows, but some on (Ubuntu) Linux, and I'd like this to work in both environments. On Windows, I do something along the lines of this: startpoint="D:/" for (root, dirs, files) in os.walk(startpoint): (stuff) What would I use for startpoint in Linux? I've tried "/dev/sr0" and "/dev/sr0/"; neither work. (If I recall correctly, the for-loop just drops through; I'm not at my Linux box right now to confirm.) A number of other mount points (like /dev/cdrom, I think) are links to /dev/sr0; and don't work either. It *does* work to start at "/media/VOLUMENAME", where VOLUMENAME is the volume ID of the disc; but my program will not know that. I need to be able to do this without knowing the volume name. Any ideas? (I have a nagging suspicion the answer will be that it's not possible to do this in exactly teh same way, and that I'll need to somehow query what volume is mounted on /dev/sr0, and then use the /media/volumename approach) From alan.gauld at btinternet.com Sat Nov 6 01:10:25 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 00:10:25 -0000 Subject: [Tutor] Server References: <4CD3533B.1030900@gmail.com> <4CD36213.3060903@aim.com> <4CD45883.3090502@gmail.com> Message-ID: "Chris King" wrote >> If you are using Windows, turn off the built-in firewall. That's >> what fixed my problems. >> ~Corey > also, it is on the same network, so the server shouldn't be a > problem I think Corey means the firewall on your PC if you have one. It could be blocking outgoing traffic to uncommon port numbers or somesuch. Its worth trying if only to eliminate the possibility Alan G. From alan.gauld at btinternet.com Sat Nov 6 01:15:06 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 00:15:06 -0000 Subject: [Tutor] Reading the CDROM in Linux References: Message-ID: "Terry Carroll" wrote > On Windows, I do something along the lines of this: > > startpoint="D:/" > for (root, dirs, files) in os.walk(startpoint): > (stuff) > > What would I use for startpoint in Linux? I don't use Ubuntu so don;t know the standard anmswer there but it will depend on where the CD is mounterd. I usually mount cdroms on /dev/cdrom But I don't use a standdard distro so set up the mount myself (based on where I did itr when I had a Sun workstation!). If you have access to the Linux box can you use a file mamnager type program to see where it is mounted? Alan G. From alan.gauld at btinternet.com Sat Nov 6 01:20:37 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 00:20:37 -0000 Subject: [Tutor] Displaying picture and Text & Downloads References: Message-ID: "Patty" wrote > I had a followup question for you all - and would like to know the > answer to Alan's question about print quality - below - A Google search led me to this page which seems to offer a solution using PIL anmd a module called ImageTk: http://codeidol.com/python/python3/A-Tkinter-Tour,-Part-1/Viewing-and-Processing-Images-with-PIL/ I've never tried it so I'll be interested to hear if it works for you... Alan G., From carroll at tjc.com Sat Nov 6 01:59:19 2010 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Nov 2010 17:59:19 -0700 (PDT) Subject: [Tutor] Reading the CDROM in Linux Message-ID: Alan Gauld wrote: > I don't use Ubuntu so don;t know the standard anmswer > there but it will depend on where the CD is mounterd. > > I usually mount cdroms on /dev/cdrom That's what I figured; I now realize I didn't say so in my email, but it's mounted at /dev/sr0, which is where I came up with that mount point. tjrc at vraspberry:~$ df . . . /dev/sr0 614350 614350 0 100% /media/MP_04_074 MP_04_074 is the volume name. But in python: >>> import os >>> for (r, d, f) in os.walk("/dev/sr0"): print r, d, f ... >>> for (r, d, f) in os.walk("/dev/sr0/"): print r, d, f ... >>> for (r, d, f) in os.walk("/dev/cdrom/"): print r, d, f ... >>> for (r, d, f) in os.walk("/dev/cdrom"): print r, d, f ... >>> for (r, d, f) in os.walk("/dev/cdrom0"): print r, d, f ... >>> for (r, d, f) in os.walk("/dev/cdrom0/"): print r, d, f ... None of those work; but: >>> for (r, d, f) in os.walk("/media/MP_04_074"): print r, d, f ... /media/MP_04_074 ['directory1'] [] (etc.) What I can't figure out is how to do this if my program does not know the volume name. I won't know the colume name in advance, and in fact, I'll be processing one CDROM, replacing it and processing another, etc. From steve at pearwood.info Sat Nov 6 02:08:35 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Nov 2010 12:08:35 +1100 Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: References: Message-ID: <4CD4AA93.3000707@pearwood.info> Alan Gauld wrote: > I don't use Ubuntu so don;t know the standard anmswer there but it will > depend on where the CD is mounterd. > > I usually mount cdroms on /dev/cdrom Surely that's where you mount cdroms *from*? I can't think that using /dev/cdrom as the mount point would be a good idea! Anyway, more modern Linux systems automatically mount CDs and DVDs. By convention, /mnt/... is used for manually mounts, and /media/... for automatic mounts of media. -- Steven From petluke at gmail.com Sat Nov 6 02:12:42 2010 From: petluke at gmail.com (Luke Pettit) Date: Sat, 6 Nov 2010 12:12:42 +1100 Subject: [Tutor] Hi Message-ID: Hi everyone, I'm just about to begin to learn python and have bookmarked a number of sites to learn from http://www.alan-g.me.uk/ is the main one but after reading this ""On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: Hello, I have completed my first python script. This is after watching a video guide on python and is my first attempt at writing code in python. While the code is not very useful I got the idea for it when googling "python projects for beginners"."" I was interested in which video tutorials Glen was watching, and if anyone else could recommend some video tutorials to watch, mainly because of a mild dyslexia and preference for video tutorials. I have been learning Autodesk 3d Studio Max http://south-apac.autodesk.com/adsk/servlet/pc/index?siteID=1157326&id=15474303 for several years and learning it's scripting language Maxscript http://rosettacode.org/wiki/Category:MAXScript and since Autodesk now own all the competitors software and they all (except Max) use Python for their coding I thought it would be the way to go when learning a new language. Blender also uses Python btw. My 3d site http://lukepettit-3d.blogspot.com/ -- Luke Pettit -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Sat Nov 6 02:22:38 2010 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Nov 2010 18:22:38 -0700 (PDT) Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: <4CD4AA93.3000707@pearwood.info> References: <4CD4AA93.3000707@pearwood.info> Message-ID: On Sat, 6 Nov 2010, Steven D'Aprano wrote: > Anyway, more modern Linux systems automatically mount CDs and DVDs. By > convention, /mnt/... is used for manually mounts, and /media/... for > automatic mounts of media. I am seeing my volume in /media ; however, I won't know the volume name when my program runs. I can't use whatever shows up in /media, because there could be more than one drive. From steve at pearwood.info Sat Nov 6 02:25:28 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Nov 2010 12:25:28 +1100 Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: References: Message-ID: <4CD4AE88.3040009@pearwood.info> Terry Carroll wrote: > I have a program that traverses the directory of a CDROM using os.walk. > I do most of my work on Windows, but some on (Ubuntu) Linux, and I'd > like this to work in both environments. > > On Windows, I do something along the lines of this: > > startpoint="D:/" What if the user has two CD drives? What if they have a second hard disk mounted on D:/, and a network drive on E:/, and use F:/ or A:/ or Z:/ for the CD drive? If this program is for you, then it is fine to make assumptions about where the CD drive will be mounted, but don't make the mistake of thinking that they're not assumptions. > for (root, dirs, files) in os.walk(startpoint): > (stuff) > > What would I use for startpoint in Linux? I've tried "/dev/sr0" and > "/dev/sr0/"; neither work. (If I recall correctly, the for-loop just > drops through; I'm not at my Linux box right now to confirm.) As a general rule, don't touch anything in /dev unless you know what you're doing. /dev/sr0, and it's more user-friendly name /dev/cdrom, are devices, not folders. This is how low-level programs get access to the raw bytes being read from the device (in this case the CDROM drive) *before* it is turned into files. > A number of other mount points (like /dev/cdrom, I think) are links to > /dev/sr0; and don't work either. No, of course not. If they're links, that will mean that they are essentially nicknames or aliases. If Fred Smith doesn't respond when you talk to him, then calling him Freddy, Mr Smith, Hey you! or Frederick isn't going to work either. > It *does* work to start at "/media/VOLUMENAME", where VOLUMENAME is the > volume ID of the disc; but my program will not know that. I need to be > able to do this without knowing the volume name. Yes, this is because you need to look at the mount point. The mount point is where the CDROM disk is mounted as a file system, in other words, where you can see the files on the disk *as files*. If you want to read the raw bytes off the disk, you open /dev/cdrom as a file and read from it. On Unix and Linux systems, there are two conventions for mounting external media. One is that if you, the user, mount something by hand using the "mount" command, it gets placed in /mnt (old-school Unix sys admins had keyboards without vowels *wink*). Often people would use subdirectories under /mnt: /mnt/cdrom /mnt/floppy are the two most common ones. The other convention is that modern window/desktop managers like KDE and Gnome will automatically mount devices by name under /media. This is typically for CDs, DVDs, cameras and mobile phones with file storage, USB sticks and portable hard drives, etc. If you only have one CD drive, and no other devices mounted, you can just look at /media and walk over that without caring what the CD drive is called. In other words, just use /media as the starting point, and let os.walk discover the name of the CD under it. But if you might have an external hard drive plugged in, or a USB key, or similar, then you need to find out what the volume name of the mounted CD drive is. That's a good question and I don't have an answer right now. Let me think about it and get back to you. -- Steven From steve at pearwood.info Sat Nov 6 02:31:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Nov 2010 12:31:54 +1100 Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: <4CD4AE88.3040009@pearwood.info> References: <4CD4AE88.3040009@pearwood.info> Message-ID: <4CD4B00A.7030609@pearwood.info> Steven D'Aprano wrote: > But if you might have an external hard drive plugged in, or a USB key, > or similar, then you need to find out what the volume name of the > mounted CD drive is. That's a good question and I don't have an answer > right now. Let me think about it and get back to you. Well that was easy. You need to query the external tool volname, which should be present on just about any Linux system. Use the subprocess module to call "volname /dev/cdrom". -- Steven From wprins at gmail.com Sat Nov 6 02:44:37 2010 From: wprins at gmail.com (Walter Prins) Date: Sat, 6 Nov 2010 01:44:37 +0000 Subject: [Tutor] Looking for a tutor to review my code and provide constructive feedback. In-Reply-To: References: Message-ID: One final suggestion to add to the others: Install and use both pylint, and pychecker. That will help ensure you don't make silly errors or omissions and follow a consistent coding style that matches the generally accepted format well. PyLint: http://pypi.python.org/pypi/pylint PyChecker: http://pypi.python.org/pypi/PyChecker/0.8.12 Aside: The easiest way to install these (and many other) Python modules is using "Pip": http://pypi.python.org/pypi/pip/0.8.1 Using Pip, installing pylint is just the following command: pip install pylint Likewise for pychecker. Have a good weekend. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladynikon at gmail.com Sat Nov 6 04:20:39 2010 From: ladynikon at gmail.com (Danyelle Davis) Date: Fri, 5 Nov 2010 23:20:39 -0400 Subject: [Tutor] Programs for Newbies? Message-ID: Hi all, Any suggestions for a newbie to program while learning python? I am new to programming and python. Thanks, LN -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Sat Nov 6 04:58:27 2010 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Nov 2010 20:58:27 -0700 (PDT) Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: <4CD4AE88.3040009@pearwood.info> References: <4CD4AE88.3040009@pearwood.info> Message-ID: On Sat, 6 Nov 2010, Steven D'Aprano wrote: > Terry Carroll wrote: >> I have a program that traverses the directory of a CDROM using os.walk. I >> do most of my work on Windows, but some on (Ubuntu) Linux, and I'd like >> this to work in both environments. >> >> On Windows, I do something along the lines of this: >> >> startpoint="D:/" > > What if the user has two CD drives? What if they have a second hard disk > mounted on D:/, and a network drive on E:/, and use F:/ or A:/ or Z:/ for the > CD drive? D:/ doesn't enter into it. That's on Windows, I'm asking about Linux. I used "D:/" to show a single example of what works on Windows to explain what I am looking for on Linux. In practice, the drive specification will be coming from a config file. It would be D:? on some systems, E:/ on others or maybe both. But my question is not about Windows, which I already have covered. My question is, to put it succinctly: How can one use os.walk to walk a directory structure of a CDROM on LInux when the volume name is not known? > On Unix and Linux systems, there are two conventions for mounting external > media. One is that if you, the user, mount something by hand using the > "mount" command, it gets placed in /mnt (old-school Unix sys admins had > keyboards without vowels *wink*). Often people would use subdirectories under > /mnt: > > /mnt/cdrom > /mnt/floppy > > are the two most common ones. No such luck: tjrc at vraspberry:~$ ls -pal /mnt total 8 drwxr-xr-x 2 root root 4096 2010-04-23 03:23 ./ drwxr-xr-x 23 root root 4096 2010-10-04 10:42 ../ tjrc at vraspberry:~$ ls -pal /mnt/cdrom ls: cannot access /mnt/cdrom: No such file or directory tjrc at vraspberry:~$ ls -pal /mnt/floppy ls: cannot access /mnt/floppy: No such file or directory > The other convention is that modern window/desktop managers like KDE and > Gnome will automatically mount devices by name under /media. Yes, I mentioned this, but it requires knowing the volume name. > If you only have one CD drive, and no other devices mounted, you can > just look at /media and walk over that without caring what the CD drive > is called. In other words, just use /media as the starting point, and > let os.walk discover the name of the CD under it. But that has the same problem I already mentioned in the prior note: what if there's more than one device? The same thing you pointed out above about D:/ > Well that was easy. You need to query the external tool volname, which > should be present on just about any Linux system. > > Use the subprocess module to call "volname /dev/cdrom". Aha, this looks like it will work; I was starting to think along these lines; I was thinking of reading the output of df, but this is cleaner. From clsdaniel at gmail.com Sat Nov 6 05:03:26 2010 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Fri, 5 Nov 2010 21:03:26 -0700 Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: References: Message-ID: This is more of a Linux question, but here is some advice: All files under /dev are more or less raw representations of the devices, meaning that /dev/cdrom or /dev/sr0 files represent the CDROM devices, however this is for raw access to the device data, now really for normal use, the sistem may "mount" this device in another place (like inside the /media directory), so that a directory will represent the contents (filesystem) of the device, which is what you may want to use. In the example that you are using, you may call 'df' from python and parse the data, which more or less is presented in the following format: device, space, used space, mounted directory. What you need the the directory where the device is mounted (the last data), and then you may use walk on that, taking care that the directory is under your media directory so that you won't walk the root directory entirely (your hard disk). You may want to use os.popen or one of the many process modules to call 'df', then parse each line by spliting the spaces or tabs, then the rest is more or less what you are doing right now. Regards, Carlos Ruvalcaba On Fri, Nov 5, 2010 at 5:59 PM, Terry Carroll wrote: > Alan Gauld wrote: > >> I don't use Ubuntu so don;t know the standard anmswer >> there but it will depend on where the CD is mounterd. >> >> I usually mount cdroms on /dev/cdrom > > That's what I figured; I now realize I didn't say so in my email, but it's > mounted at /dev/sr0, which is where I came up with that mount point. > > > ?tjrc at vraspberry:~$ df > ?. . . > > ?/dev/sr0 ? ? ? ? ? ? ? 614350 ? ?614350 ? ? ? ? 0 100% /media/MP_04_074 > > > MP_04_074 is the volume name. > > But in python: > >>>> import os >>>> for (r, d, f) in os.walk("/dev/sr0"): print r, d, f > > ... >>>> >>>> for (r, d, f) in os.walk("/dev/sr0/"): print r, d, f > > ... >>>> >>>> for (r, d, f) in os.walk("/dev/cdrom/"): print r, d, f > > ... >>>> >>>> for (r, d, f) in os.walk("/dev/cdrom"): print r, d, f > > ... >>>> >>>> for (r, d, f) in os.walk("/dev/cdrom0"): print r, d, f > > ... >>>> >>>> for (r, d, f) in os.walk("/dev/cdrom0/"): print r, d, f > > ... > > > None of those work; but: > > >>>> for (r, d, f) in os.walk("/media/MP_04_074"): print r, d, f > > ... > /media/MP_04_074 ['directory1'] [] > (etc.) > > > What I can't figure out is how to do this if my program does not know the > volume name. ?I won't know the colume name in advance, and in fact, I'll be > processing one CDROM, replacing it and processing another, etc. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From ladynikon at gmail.com Sat Nov 6 05:37:24 2010 From: ladynikon at gmail.com (Danyelle Davis) Date: Sat, 6 Nov 2010 00:37:24 -0400 Subject: [Tutor] test Message-ID: im wondering if im able to mail this list. I sent an email asking for good newbie projects but never saw it post. All i got was the welcome/ info email. LN -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sat Nov 6 05:44:44 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 5 Nov 2010 23:44:44 -0500 Subject: [Tutor] test In-Reply-To: References: Message-ID: You don't get your own e-mails back. On Fri, Nov 5, 2010 at 11:37 PM, Danyelle Davis wrote: > im wondering if im able to mail this list. ?I sent an email asking for good > newbie projects but never saw it post. ?All i got was the welcome/ info > email. > LN > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From patty at cruzio.com Sat Nov 6 05:53:01 2010 From: patty at cruzio.com (Patty) Date: Fri, 5 Nov 2010 21:53:01 -0700 Subject: [Tutor] Displaying Pictures & Text Message-ID: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer> Hi Alan - I tried using ImageTk from the PIL library to display jpegs (and hopefully any picture type) instead of just gif as you suggested below. I read online that these these types of programs should be run from executables not in the interpreter but it crashes and I can't read the error. Here is the program: import Image import ImageTk fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") ImageTk.PhotoImage(fhdl) Tested in interpreter and get the following error. I included Image.show() to be sure pic could be displayed and it did come up in HP Photo Viewer just like the gif file did and I tried the PhotoImage() after I got the cursor back Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Image >>> import ImageTk >>> fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") >>> fhdl.show() >>> ImageTk.PhotoImage(fhdl) Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\PIL\ImageTk.py", line 113, in __init__ self.__photo = apply(Tkinter.PhotoImage, (), kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3285, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3226, in __init__ raise RuntimeError, 'Too early to create image' RuntimeError: Too early to create image >>> >> > "Alan Gauld" wrote in message news:ib270l$p30$1 at dough.gmane.org... > > "Patty" wrote > >> I had a followup question for you all - and would like to know the >> answer to Alan's question about print quality - below - > > > A Google search led me to this page which seems to offer a solution > using PIL anmd a module called ImageTk: > > http://codeidol.com/python/python3/A-Tkinter-Tour,-Part-1/Viewing-and-Processing-Images-with-PIL/ > > I've never tried it so I'll be interested to hear if it works for > you... > > Alan G., > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Nov 6 06:20:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Nov 2010 16:20:54 +1100 Subject: [Tutor] test In-Reply-To: References: Message-ID: <4CD4E5B6.9050200@pearwood.info> Luke Paireepinart wrote: > You don't get your own e-mails back. I do. Perhaps it's an option when you sign up? -- Steven From steve at pearwood.info Sat Nov 6 06:40:12 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Nov 2010 16:40:12 +1100 Subject: [Tutor] Programs for Newbies? In-Reply-To: References: Message-ID: <4CD4EA3C.8070706@pearwood.info> Danyelle Davis wrote: > Hi all, > > Any suggestions for a newbie to program while learning python? I am new to > programming and python. What are you interested in? Interested in maths? Write a program to generate prime numbers, or to search for amicable numbers. Look at Project Euler, although (in my opinion) the puzzles there are quite hard are require a lot of maths know-how. Write a number guessing game. Or Hangman or Battleship. Try the Python Challenge: http://www.pythonchallenge.com/ More puzzle sites here, written in other languages but you can solve them in Python if you like: http://sixrevisions.com/resources/10-puzzle-websites-to-sharpen-your-programming-skills/ Unfortunately, most of them seem to be aimed at people who aren't newbies. I think the world needs a good set of programming puzzles for beginners. Good luck! -- Steven From steve at pearwood.info Sat Nov 6 06:55:35 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Nov 2010 16:55:35 +1100 Subject: [Tutor] Programs for Newbies? In-Reply-To: References: Message-ID: <4CD4EDD7.2080202@pearwood.info> Danyelle Davis wrote: > Hi all, > > Any suggestions for a newbie to program while learning python? I am new to > programming and python. Here's a few suggestions: Write a program that asks the user to enter a word, then counts how many vowels and consonants are in the word. Write a program that asks the user for a list of numbers, separated by spaces or commas, and then calculated the average. A program that prints the time. A program that prints how many days to go until their next birthday. A program that counts how many palindrome numbers there are between two other numbers. (A palindrome number is one like 12321, or 473374.) A program that sings (well, prints) the "There were ten in the bed" song. If you don't know it, it is a children's song. You start off by holding up ten fingers, or you can use actual children. You don't have to start with ten. Then you sing: There were ten in the bed, and the little one said, Roll over! Roll over! And they all rolled over and ONE FELL OUT! There were nine in the bed, and the little one said, Roll over! Roll over! And they all rolled over and ONE FELL OUT! There were eight in the bed, and the little one said, ... Well you get the idea. Eventually you've left with only the little one left, and the song ends: There was one in a bed, and the little one said Good night! -- Steven From bouncingcats at gmail.com Sat Nov 6 07:11:59 2010 From: bouncingcats at gmail.com (David) Date: Sat, 6 Nov 2010 17:11:59 +1100 Subject: [Tutor] test In-Reply-To: <4CD4E5B6.9050200@pearwood.info> References: <4CD4E5B6.9050200@pearwood.info> Message-ID: On 6 November 2010 16:20, Steven D'Aprano wrote: > Luke Paireepinart wrote: >> >> You don't get your own e-mails back. > > I do. > > Perhaps it's an option when you sign up? For any list (like this one) hosted by mailman, the default is set by list administrator, but every user can customise this at their list config via the URL mentioned in the footer. From carroll at tjc.com Sat Nov 6 07:55:16 2010 From: carroll at tjc.com (Terry Carroll) Date: Fri, 5 Nov 2010 23:55:16 -0700 (PDT) Subject: [Tutor] Reading the CDROM in Linux In-Reply-To: References: <4CD4AE88.3040009@pearwood.info> Message-ID: On Fri, 5 Nov 2010, Terry Carroll wrote: > Aha, this looks like it will work; I was starting to think along these lines; > I was thinking of reading the output of df, but this is cleaner. Just to close this out, here's what's working for me. It will need to be prettied up, and the "/media/" parameterized, but it's my proof of concept that lets me know how to solve my problem: ######################################################### import subprocess, os def getvolid(mountpoint): p = subprocess.Popen(["volname", mountpoint], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (response, errmsg) = p.communicate() volid=response.rstrip() errmsg = errmsg.rstrip() if len(response)==0: volid=None return (volid, errmsg) # Test it things_to_try = ["/dev/sr0", # VBOXADDITIONS_3.2.6_63112 "/dev/cdrom1", # symlink to sr0 "/dev/sr1", # MP_04_074 "/dev/cdrom", # symlink to sr1 "/dev/sr2"] # no such mount point, return an error for thing in things_to_try: volid, error = getvolid(thing) print "mount point=%s; volid=%s; errormsg=%s" % (thing, volid, error) # Try the os.walk: (volid, errmsg) = getvolid("/dev/sr0") for (r, d, f) in os.walk("/media/"+volid): print (r, d, f) ######################################################### From alan.gauld at btinternet.com Sat Nov 6 10:04:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 09:04:56 -0000 Subject: [Tutor] Reading the CDROM in Linux References: <4CD4AA93.3000707@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> I usually mount cdroms on /dev/cdrom > > Surely that's where you mount cdroms *from*? I can't think that > using /dev/cdrom as the mount point would be a good idea! Oops, yes, that should be /usr/cdrom, sorry. Alan G. From alan.gauld at btinternet.com Sat Nov 6 10:11:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 09:11:43 -0000 Subject: [Tutor] Hi References: Message-ID: "Luke Pettit" wrote > I was interested in which video tutorials Glen was watching, and if > anyone > else could recommend some video tutorials to watch, I don;t know what Glen was watching but thhere are a whole bunch of videos at showmedo.com Alan G. From petluke at gmail.com Sat Nov 6 11:29:37 2010 From: petluke at gmail.com (Luke Pettit) Date: Sat, 6 Nov 2010 21:29:37 +1100 Subject: [Tutor] Hi In-Reply-To: References: Message-ID: Thanks Alan I found those about an hour ago :) On 6 November 2010 20:11, Alan Gauld wrote: > > "Luke Pettit" wrote > > > I was interested in which video tutorials Glen was watching, and if anyone >> else could recommend some video tutorials to watch, >> > > I don;t know what Glen was watching but thhere are a whole bunch of > videos at showmedo.com > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Luke Pettit -------------- next part -------------- An HTML attachment was scrubbed... URL: From seekker at yahoo.com Sat Nov 6 15:05:03 2010 From: seekker at yahoo.com (Seekker) Date: Sat, 6 Nov 2010 07:05:03 -0700 (PDT) Subject: [Tutor] Newbie Programming puzzles, etc. In-Reply-To: Message-ID: <581093.59605.qm@web32103.mail.mud.yahoo.com> Unfortunately, most of them seem to be aimed at people who aren't newbies. I think the world needs a good set of programming puzzles for beginners. It would sure be helpful to have a library of newbie type projects ... I'm teaching myself with the "think like a computer scientist' books, and thus far I've been able to follow and/or figure out the exercises ... but I'm only in chapter 03 at time moment.? I'm sure it'll get more challenging as I go.? I'm not the greatest 'problem solver' ... I've been hoping that learning a programming language would help in that area. Thanks Seekker -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Nov 6 15:16:40 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 6 Nov 2010 09:16:40 -0500 Subject: [Tutor] Displaying Pictures & Text In-Reply-To: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer> References: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer> Message-ID: On Fri, Nov 5, 2010 at 11:53 PM, Patty wrote: > Hi Alan - > > I tried using ImageTk from the PIL library to display jpegs (and hopefully > any picture type) instead of just gif as you suggested below. I read > online that these these types of programs should > be run from executables not in the interpreter but it crashes and I can't > read the error. Here is the program: > > import Image > import ImageTk > > fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") > ImageTk.PhotoImage(fhdl) > Before you convert to an ImageTk, you need to first create a toplevel window: import Image import ImageTk import Tkinter as tk root = tk.Tk() #put your code here And that should work. You'll still have to add the widgets and what-nots so you can present your image, but in order to create an image with ImageTk, you need to have a toplevel window created. That's what this is telling you Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\PIL\ImageTk.py", line 113, in __init__ self.__photo = apply(Tkinter.PhotoImage, (), kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3285, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3226, in __init__ raise RuntimeError, 'Too early to create image' RuntimeError: Too early to create image HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From glenuk at gmail.com Sat Nov 6 15:45:30 2010 From: glenuk at gmail.com (Glen Clark) Date: Sat, 06 Nov 2010 14:45:30 +0000 Subject: [Tutor] Hi In-Reply-To: References: Message-ID: <1289054730.15087.7.camel@BigPC> Luke, I used a video from Lynda.com, simply because I already had a subscription. The price was about $25 per month which I think is more expensive that showmedo. Or you could buy it for $99 (Python 3 Essential Training (DVD-ROM)). The video's were very good for me personally because he was straight to the point which kept me from getting bored. I have recently found showmedo though and they does loog very good also. It seems to have a lot of content on there. Regards, Glen On Sat, 2010-11-06 at 21:29 +1100, Luke Pettit wrote: > Thanks Alan I found those about an hour ago :) > > On 6 November 2010 20:11, Alan Gauld > wrote: > > "Luke Pettit" wrote > > > I was interested in which video tutorials Glen was > watching, and if anyone > else could recommend some video tutorials to watch, > > > I don;t know what Glen was watching but thhere are a whole > bunch of > videos at showmedo.com > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Luke Pettit > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From glenuk at gmail.com Sat Nov 6 15:48:05 2010 From: glenuk at gmail.com (Glen Clark) Date: Sat, 06 Nov 2010 14:48:05 +0000 Subject: [Tutor] Hi In-Reply-To: <1289054730.15087.7.camel@BigPC> References: <1289054730.15087.7.camel@BigPC> Message-ID: <1289054885.15087.10.camel@BigPC> Also, if you have not yet chosen an IDE I recommend eclipse with the pydev extension. Google them or if you use gnu/linux (like ubuntu) you can get it from the package manager. It is a very simple interface, with syntax highlighting, debug mode and console. On Sat, 2010-11-06 at 14:45 +0000, Glen Clark wrote: > Luke, > > I used a video from Lynda.com, simply because I already had a > subscription. The price was about $25 per month which I think is more > expensive that showmedo. Or you could buy it for $99 (Python 3 Essential > Training (DVD-ROM)). > > The video's were very good for me personally because he was straight to > the point which kept me from getting bored. > > I have recently found showmedo though and they does loog very good also. > It seems to have a lot of content on there. > > Regards, > Glen > > On Sat, 2010-11-06 at 21:29 +1100, Luke Pettit wrote: > > Thanks Alan I found those about an hour ago :) > > > > On 6 November 2010 20:11, Alan Gauld > > wrote: > > > > "Luke Pettit" wrote > > > > > > I was interested in which video tutorials Glen was > > watching, and if anyone > > else could recommend some video tutorials to watch, > > > > > > I don;t know what Glen was watching but thhere are a whole > > bunch of > > videos at showmedo.com > > > > Alan G. > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > -- > > Luke Pettit > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > From patty at cruzio.com Sat Nov 6 17:50:07 2010 From: patty at cruzio.com (Patty) Date: Sat, 6 Nov 2010 09:50:07 -0700 Subject: [Tutor] Displaying Pictures & Text References: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer> Message-ID: <68790179F57D4947B6BADC5A327A43BC@mycomputer> Thank you! I was getting confused, I thought I wouldn't need Tkinter. I thought Tkinter is yet another addon library besides PIL. Am I right or wrong? So I actually need both? And this brings me back to my _other_ question which is that as individuals go about downloading these addon libraries and their doc, how do you organize this on your computer system? I can imagine that in corporations there are guidelines for this, but I am wondering what you all do? You could end up with addon libraries, doc and Readmes all over your hard disk Patty ----- Original Message ----- From: Wayne Werner To: Patty Cc: tutor at python.org Sent: Saturday, November 06, 2010 7:16 AM Subject: Re: [Tutor] Displaying Pictures & Text On Fri, Nov 5, 2010 at 11:53 PM, Patty wrote: Hi Alan - I tried using ImageTk from the PIL library to display jpegs (and hopefully any picture type) instead of just gif as you suggested below. I read online that these these types of programs should be run from executables not in the interpreter but it crashes and I can't read the error. Here is the program: import Image import ImageTk fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") ImageTk.PhotoImage(fhdl) Before you convert to an ImageTk, you need to first create a toplevel window: import Image import ImageTk import Tkinter as tk root = tk.Tk() #put your code here And that should work. You'll still have to add the widgets and what-nots so you can present your image, but in order to create an image with ImageTk, you need to have a toplevel window created. That's what this is telling you Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\PIL\ImageTk.py", line 113, in __init__ self.__photo = apply(Tkinter.PhotoImage, (), kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3285, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3226, in __init__ raise RuntimeError, 'Too early to create image' RuntimeError: Too early to create image HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From patty at cruzio.com Sat Nov 6 17:54:32 2010 From: patty at cruzio.com (Patty) Date: Sat, 6 Nov 2010 09:54:32 -0700 Subject: [Tutor] Programs for Newbies? References: <4CD4EDD7.2080202@pearwood.info> Message-ID: <4D393BB30916461B82F75F14C956695E@mycomputer> For my first program, I liked creating a number game, simple and where the user made a choice. That was good for learning how to interact with the user. The raw_input() function. Patty ----- Original Message ----- From: "Steven D'Aprano" To: Sent: Friday, November 05, 2010 10:55 PM Subject: Re: [Tutor] Programs for Newbies? > Danyelle Davis wrote: >> Hi all, >> >> Any suggestions for a newbie to program while learning python? I am new >> to >> programming and python. > > > Here's a few suggestions: > > > Write a program that asks the user to enter a word, then counts how many > vowels and consonants are in the word. > > Write a program that asks the user for a list of numbers, separated by > spaces or commas, and then calculated the average. > > A program that prints the time. > > A program that prints how many days to go until their next birthday. > > A program that counts how many palindrome numbers there are between two > other numbers. (A palindrome number is one like 12321, or 473374.) > > A program that sings (well, prints) the "There were ten in the bed" song. > If you don't know it, it is a children's song. You start off by holding up > ten fingers, or you can use actual children. You don't have to start with > ten. Then you sing: > > There were ten in the bed, and the little one said, > Roll over! Roll over! > And they all rolled over and ONE FELL OUT! > There were nine in the bed, and the little one said, > Roll over! Roll over! > And they all rolled over and ONE FELL OUT! > There were eight in the bed, and the little one said, > ... > > Well you get the idea. Eventually you've left with only the little one > left, and the song ends: > > There was one in a bed, and the little one said > Good night! > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Sat Nov 6 18:55:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 17:55:59 -0000 Subject: [Tutor] Displaying Pictures & Text References: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer> <68790179F57D4947B6BADC5A327A43BC@mycomputer> Message-ID: "Patty" wrote > I thought I wouldn't need Tkinter. I thought Tkinter is yet > another addon library Tkinter is the standfard GUI toolkit for Python and as such comes as part of the standard library. (Although you do have to compile Python with that option enabled in some Linux distros) > So I actually need both? Yes PUIL is for transforming the graphics and creatnf the image object. Tkinter can then displaty that image object in a GUI. > And this brings me back to my _other_ question which is that > as individuals go about downloading these addon libraries and > their doc, how do you organize this on your computer system? Most common add-on libraries will install themselves in the site-packages dirtectory structure under your Python root folder So they remain fairly well organized. Some thoird party tools are kist a single python module and you have to decide where to put it yourselfd. In my case thats usually in site-packages too. This does mean that when you upgrade you have to decide which, if any, of your site-package files to migrate to the new version and which to re-download. I usually opt for the re-download route just to be safe. Alan G. From patty at cruzio.com Sat Nov 6 19:53:49 2010 From: patty at cruzio.com (Patty) Date: Sat, 6 Nov 2010 11:53:49 -0700 Subject: [Tutor] Displaying Pictures & Text References: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer><68790179F57D4947B6BADC5A327A43BC@mycomputer> Message-ID: <732014822C87404ABE6BE5CF9016F156@mycomputer> Thanks for the explanation. I will go ahead and trying using these functions in my program. Patty ----- Original Message ----- From: "Alan Gauld" To: Sent: Saturday, November 06, 2010 10:55 AM Subject: Re: [Tutor] Displaying Pictures & Text > > "Patty" wrote > >> I thought I wouldn't need Tkinter. I thought Tkinter is yet another >> addon library > > Tkinter is the standfard GUI toolkit for Python and as such comes as part > of the > standard library. (Although you do have to compile Python with that option > enabled in some Linux distros) > >> So I actually need both? > > Yes PUIL is for transforming the graphics and creatnf the image object. > Tkinter can then displaty that image object in a GUI. > >> And this brings me back to my _other_ question which is that >> as individuals go about downloading these addon libraries and >> their doc, how do you organize this on your computer system? > > Most common add-on libraries will install themselves in the > site-packages dirtectory structure under your Python root folder > So they remain fairly well organized. > > Some thoird party tools are kist a single python module and you have > to decide where to put it yourselfd. In my case thats usually in > site-packages too. > > This does mean that when you upgrade you have to decide which, > if any, of your site-package files to migrate to the new version and > which to re-download. I usually opt for the re-download route just > to be safe. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From waynejwerner at gmail.com Sat Nov 6 20:24:49 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 6 Nov 2010 14:24:49 -0500 Subject: [Tutor] Programs for Newbies? In-Reply-To: <4D393BB30916461B82F75F14C956695E@mycomputer> References: <4CD4EDD7.2080202@pearwood.info> <4D393BB30916461B82F75F14C956695E@mycomputer> Message-ID: On Sat, Nov 6, 2010 at 11:54 AM, Patty wrote: > For my first program, I liked creating a number game, simple and where the > user made a choice. That was good for learning how to interact with the > user. The raw_input() function. > > Patty > My favorite one is a simple guessing game, where the computer "thinks" of a number 1-10 (inclusive) and then the user guesses the number, with the computer responding "Too High" or "Too low!". For more variation, keeping "score" - number of guesses, # of rounds played, etc. are fun additions to the program. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 6 23:10:57 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 6 Nov 2010 22:10:57 -0000 Subject: [Tutor] Displaying Pictures & Text References: <7BD676F528B441AB87EAF4D6ACBA1A17@mycomputer><68790179F57D4947B6BADC5A327A43BC@mycomputer> <732014822C87404ABE6BE5CF9016F156@mycomputer> Message-ID: "Patty" wrote > Thanks for the explanation. I will go ahead and trying using these > functions in my program. Tkinrer is quite easy once you get the hang of it. Its also a good intro to GUI frameworks in general if you ever need to move top something more advanced. There are good tutorials for both PIL and Tkinter on the Pythonware site: http://www.pythonware.com/products/pil/index.htm http://www.pythonware.com/products/tkinter/index.htm Or you can try the intro to GUI programming in my tuitorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From trenchcoat at gmail.com Sun Nov 7 03:43:30 2010 From: trenchcoat at gmail.com (trench) Date: Sat, 6 Nov 2010 21:43:30 -0500 Subject: [Tutor] Hi In-Reply-To: References: Message-ID: I'd also point out that Google has created a very awesome Python course which is heavily dependent on video lectures by Nick Parlante. Included in the course are downloadable exercises and examples (all mentioned in the video lectures). After you review all of this quality (not to mention free) material... I think you'll fully understand what separates Google from its competitors. (By this, I simply mean that you will not see similar offerings from, say, Facebook, Apple, or MS.) http://code.google.com/edu/languages/google-python-class/index.html This is a part of Google's "Google Code University". Here's the root URL for the entire project: http://code.google.com/edu/ -- definitely worth checking out. -trench On Fri, Nov 5, 2010 at 8:12 PM, Luke Pettit wrote: > Hi everyone, > I'm just about to begin to learn python and have bookmarked a number of > sites to learn from > http://www.alan-g.me.uk/ is the main one but after reading this > > ""On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: > > Hello, > > I have completed my first python script. This is after watching a video > guide on python and is my first attempt at writing code in python. While the > code is not very useful I got the idea for it when googling "python projects > for beginners"."" > > > I was interested in which video tutorials Glen was watching, and if anyone > else could recommend some video tutorials to watch, mainly because of a mild > dyslexia and preference for video tutorials. > > I have been learning Autodesk 3d Studio Max > http://south-apac.autodesk.com/adsk/servlet/pc/index?siteID=1157326&id=15474303 for > several years and learning it's scripting language Maxscript > http://rosettacode.org/wiki/Category:MAXScript and since Autodesk now own > all the competitors software and they all (except Max) use Python for > their coding I thought it would be the way to go when learning a new > language. Blender also uses Python btw. > > My 3d site http://lukepettit-3d.blogspot.com/ > > -- > Luke Pettit > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- - t -------------- next part -------------- An HTML attachment was scrubbed... URL: From petluke at gmail.com Sun Nov 7 05:34:05 2010 From: petluke at gmail.com (Luke Pettit) Date: Sun, 7 Nov 2010 15:34:05 +1100 Subject: [Tutor] Hi In-Reply-To: References: Message-ID: Wow information overload lol Thanks everyone this is great. On 7 November 2010 13:43, trench wrote: > I'd also point out that Google has created a very awesome Python course > which is heavily dependent on video lectures by Nick Parlante. Included in > the course are downloadable exercises and examples (all mentioned in the > video lectures). After you review all of this quality (not to mention free) > material... I think you'll fully understand what separates Google from its > competitors. (By this, I simply mean that you will not see similar offerings > from, say, Facebook, Apple, or MS.) > > http://code.google.com/edu/languages/google-python-class/index.html > > This > is a part of Google's "Google Code University". Here's the root URL for the > entire project: http://code.google.com/edu/ -- definitely worth checking > out. > > -trench > > On Fri, Nov 5, 2010 at 8:12 PM, Luke Pettit wrote: > >> Hi everyone, >> I'm just about to begin to learn python and have bookmarked a number of >> sites to learn from >> http://www.alan-g.me.uk/ is the main one but after reading this >> >> ""On Nov 4, 2010, at 3:10 PM, Glen Clark wrote: >> >> Hello, >> >> I have completed my first python script. This is after watching a video >> guide on python and is my first attempt at writing code in python. While the >> code is not very useful I got the idea for it when googling "python projects >> for beginners"."" >> >> >> I was interested in which video tutorials Glen was watching, and if anyone >> else could recommend some video tutorials to watch, mainly because of a mild >> dyslexia and preference for video tutorials. >> >> I have been learning Autodesk 3d Studio Max >> http://south-apac.autodesk.com/adsk/servlet/pc/index?siteID=1157326&id=15474303 for >> several years and learning it's scripting language Maxscript >> http://rosettacode.org/wiki/Category:MAXScript and since Autodesk now own >> all the competitors software and they all (except Max) use Python for >> their coding I thought it would be the way to go when learning a new >> language. Blender also uses Python btw. >> >> My 3d site http://lukepettit-3d.blogspot.com/ >> >> -- >> Luke Pettit >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > - t > -- Luke Pettit -------------- next part -------------- An HTML attachment was scrubbed... URL: From arv2007 at gmail.com Sun Nov 7 00:56:24 2010 From: arv2007 at gmail.com (Aravind Venkatesan) Date: Sat, 6 Nov 2010 19:56:24 -0400 Subject: [Tutor] Interactive visualization in python Message-ID: Hello, This is Aravind. I am a university graduate student. I am looking for a software module or package to visualize a hierarchial tree data structure in python. Here's the problem: I have a tree(hierarchially represented) with set of nodes and edges. I would like to visualize this tree first. Then i would like to have each node a clickable object so that when a node in the tree is clicked using a mouse, i want to show some data associated with that node(probably a graph) in another popup window. What kind of packages exists in python which will help me solve this? Regards, Aravind -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 7 09:50:01 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 7 Nov 2010 08:50:01 -0000 Subject: [Tutor] Interactive visualization in python References: Message-ID: "Aravind Venkatesan" wrote > This is Aravind. I am a university graduate student. I am looking > for a > software module or package to visualize a hierarchial tree data > structure in > python. Most GUI toolkits have a tree widget like the Wiondows Explorer tree view. The Tkintrer version is included in the Tix module which extends the basic Tkinter widgets. The documentation is not fantastic but ithere should be enough to get you going. I'm pretty sure wxPython will have one too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Sun Nov 7 10:02:13 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 7 Nov 2010 03:02:13 -0600 Subject: [Tutor] Interactive visualization in python In-Reply-To: References: Message-ID: On Sun, Nov 7, 2010 at 2:50 AM, Alan Gauld wrote: > > "Aravind Venkatesan" wrote > > > This is Aravind. I am a university graduate student. I am looking for a >> software module or package to visualize a hierarchial tree data structure >> in >> python. >> > > Most GUI toolkits have a tree widget like the Wiondows Explorer tree view. > The Tkintrer version is included in the Tix module which extends the basic > Tkinter widgets. The documentation is not fantastic but ithere should be > enough to get you going. > As an alternative method using Tkinter, you can create objects on a canvas and make them clickable with relative ease. For serious graphing, matplotlib is the defacto standard. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sandipb at foss-community.com Sun Nov 7 16:50:45 2010 From: sandipb at foss-community.com (Sandip Bhattacharya) Date: Sun, 7 Nov 2010 21:20:45 +0530 Subject: [Tutor] test In-Reply-To: <4CD4E5B6.9050200@pearwood.info> References: <4CD4E5B6.9050200@pearwood.info> Message-ID: <20101107155045.GB6296@saturn.home> On Sat, Nov 06, 2010 at 04:20:54PM +1100, Steven D'Aprano wrote: > Luke Paireepinart wrote: > >You don't get your own e-mails back. > > I do. > > Perhaps it's an option when you sign up? I think it is an irritating gmail-only "feature". I use a google apps domain and face the same issue. I see that the OP also uses gmail. http://mail.google.com/support/bin/answer.py?hl=en&answer=82454 """ Finally, if you're sending mail to a mailing list that you subscribe to, those messages will only appear in 'Sent Mail.' """ - Sandip From carroll at tjc.com Sun Nov 7 20:17:24 2010 From: carroll at tjc.com (Terry Carroll) Date: Sun, 7 Nov 2010 11:17:24 -0800 (PST) Subject: [Tutor] Interactive visualization in python In-Reply-To: References: Message-ID: On Sun, 7 Nov 2010, Alan Gauld wrote: > Most GUI toolkits have a tree widget like the Wiondows Explorer tree view. > The Tkintrer version is included in the Tix module which extends the basic > Tkinter widgets. > > I'm pretty sure wxPython will have one too. I haven't used it, but wxPython's tree widget is wx.TreeCtrl doc: http://wxpython.org/docs/api/wx.TreeCtrl-class.html example: http://wiki.wxpython.org/AnotherTutorial#wx.TreeCtrl From tmantjg at gmail.com Sun Nov 7 22:59:38 2010 From: tmantjg at gmail.com (Terry Green) Date: Sun, 7 Nov 2010 14:59:38 -0700 Subject: [Tutor] trying to generate change in print output Message-ID: <093FCAFAF29C41FDA5407A572637A115@terryPC> Am stumped, when I use this code: race=int(row[2]) raceChek=1 if raceChek == race: print ('raceChek ', raceChek, 'race ', race) else: print ('raceChek ', raceChek,' no match ', 'race ', race); raceChek = race I Get this: raceChek 1 race 1 raceChek 1 race 1 raceChek 1 race 1 raceChek 1 race 1 raceChek 1 race 1 raceChek 1 race 1 raceChek 1 no match race 2 raceChek 1 no match race 2 raceChek 1 no match race 2 raceChek 1 no match race 2 raceChek 1 no match race 2 raceChek 1 no match race 2 raceChek 1 no match race 2 raceChek 1 no match race 3 raceChek 1 no match race 3 raceChek 1 no match race 3 raceChek 1 no match race 3 raceChek 1 no match race 3 Seems my test between race and raceChek doesn't work! What is wrong? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Nov 7 23:26:34 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 08 Nov 2010 09:26:34 +1100 Subject: [Tutor] trying to generate change in print output In-Reply-To: <093FCAFAF29C41FDA5407A572637A115@terryPC> References: <093FCAFAF29C41FDA5407A572637A115@terryPC> Message-ID: <4CD7279A.2070502@pearwood.info> Terry Green wrote: > Am stumped, when I use this code: > > race=int(row[2]) > raceChek=1 This causes IndentationError: unexpected indent. > if raceChek == race: print ('raceChek ', raceChek, 'race ', race) > else: print ('raceChek ', raceChek,' no match ', 'race ', race); > raceChek = race > I Get this: > > raceChek 1 race 1 > raceChek 1 race 1 > raceChek 1 race 1 [...] I don't see how. The code you show fails completely, due to the inconsistent indentation. Even if we fix the indentation, it will only print something *once*, not eighteen times. You don't show us what the variable "row" has, so we don't know what value "race" has. Presumably it equals 1, but then later on you get: > raceChek 1 no match race 2 [repeated many times] > raceChek 1 no match race 3 [repeated many times] So mysteriously race is changing value. Obviously you are not showing us the actual code you are running, but only part of the code. Would you like us to guess what code you are running? > Seems my test between race and raceChek doesn't work! What is wrong? What makes you think that the problem is the test? It seems to me that the test if raceChek == race: is so simple that it couldn't possibly be broken. The problem is probably somewhere else. But since I don't know how you are getting eighteen lines of output, I don't know what you are doing and can't tell you what it is that is wrong. -- Steven From fjulll at gmail.com Sun Nov 7 23:52:41 2010 From: fjulll at gmail.com (fjulll) Date: Sun, 7 Nov 2010 23:52:41 +0100 Subject: [Tutor] Adding cookies to cookiejar object (Python 3.01) Message-ID: I have succeded in importing a bunch of cookies from my browser to an array and now want to put them in a cookiejar object to send in a HTTP-request. I've read the documentation over and over again but can't figure out how to actually add your own cookies to the jar. Does anyone know? http://docs.python.org/release/3.0.1/library/http.cookiejar.html Thank you! Kind regards Vilhelm -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Nov 8 00:36:30 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 7 Nov 2010 15:36:30 -0800 Subject: [Tutor] List comprehension question Message-ID: def proper_divisors(n): """ Return the sum of the proper divisors of positive integer n """ return sum([x for x in range(1,n) if int(n/x) == n/x]) The list comprehension is this function is inefficient in that it computes n/x twice. I'd like to do an a = n/x and use a in "if int(a) == a", but I don't know how. Thanks, Dick Moores -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Mon Nov 8 00:53:06 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 8 Nov 2010 00:53:06 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Mon, Nov 8, 2010 at 12:36 AM, Richard D. Moores wrote: > def proper_divisors(n): > ??? """ > ??? Return the sum of the proper divisors of positive integer n > ??? """ > ??? return sum([x for x in range(1,n) if int(n/x) == n/x]) > > The list comprehension is this function is inefficient in that it computes > n/x twice. I'd like to do an? a = n/x and use a in > "if int(a) == a", but I don't know how. > You can't do that inside a list comprehension. Either get rid of the comprehension and do a regular loop, or get rid of the n/x expression. I'd suggest replacing the whole check with x % n == 0. n is a proper divisor of x if there is no remainder after division, after all. This also means you won't have to do a cast, which tend to be fairly expensive. On another note, getting rid of the list comprehension and using a generator expression will be even faster, since you won't have to build the list. Hugo From rdmoores at gmail.com Mon Nov 8 01:16:36 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 7 Nov 2010 16:16:36 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Sun, Nov 7, 2010 at 15:53, Hugo Arts wrote: > On Mon, Nov 8, 2010 at 12:36 AM, Richard D. Moores wrote: >> def proper_divisors(n): >> ??? """ >> ??? Return the sum of the proper divisors of positive integer n >> ??? """ >> ??? return sum([x for x in range(1,n) if int(n/x) == n/x]) >> >> The list comprehension is this function is inefficient in that it computes >> n/x twice. I'd like to do an? a = n/x and use a in >> "if int(a) == a", but I don't know how. >> > > You can't do that inside a list comprehension. Either get rid of the > comprehension and do a regular loop, or get rid of the n/x expression. > > I'd suggest replacing the whole check with x % n == 0. Wow! using n % x == 0 is about 3x faster than what I had before. > n is a proper > divisor of x if there is no remainder after division, after all. This > also means you won't have to do a cast, which tend to be fairly > expensive. I don't know what a cast is. Would that be the int(n/x)? Here are 2 versions, of about equal speed: def proper_divisors(n): """ Return the sum of the proper divisors of positive integer n """ return sum([x for x in range(1,n) if n % x == 0]) def proper_divisors(n): sum_ = 0 for x in range(1,n): if n % x == 0: sum_ += x return sum_ > On another note, getting rid of the list comprehension and using a > generator expression will be even faster, since you won't have to > build the list. Could you spell that out for me? Thanks, Dick From hugo.yoshi at gmail.com Mon Nov 8 01:31:16 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 8 Nov 2010 01:31:16 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Mon, Nov 8, 2010 at 1:16 AM, Richard D. Moores wrote: > On Sun, Nov 7, 2010 at 15:53, Hugo Arts wrote: >> n is a proper >> divisor of x if there is no remainder after division, after all. This >> also means you won't have to do a cast, which tend to be fairly >> expensive. > > I don't know what a cast is. Would that be the int(n/x)? > Yes. A cast or typecast means converting some data to a different type, like converting floats to integers, strings to integers, integers to strings, etc. They are fairly expensive because the representation of the data changes. > Here are 2 versions, of about equal speed: > > def proper_divisors(n): > ? ?""" > ? ?Return the sum of the proper divisors of positive integer n > ? ?""" > ? ?return sum([x for x in range(1,n) if n % x == 0]) > > def proper_divisors(n): > ? ?sum_ = 0 > ? ?for x in range(1,n): > ? ? ? ?if n % x == 0: > ? ? ? ? ? ?sum_ += x > ? ?return sum_ > >> On another note, getting rid of the list comprehension and using a >> generator expression will be even faster, since you won't have to >> build the list. > > Could you spell that out for me? here's a list comprehension >>> a = [x*2 for x in range(10)] >>> a [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] here's the equivalent generator expression: >>> a = (x*2 for x in range(10)) >>> a at 0xb7792fa4> >>> for x in a: print x 0 2 4 6 8 10 12 14 16 18 As you can see, they are constructed almost the same way, the only difference being the type of parentheses. The main difference is what comes out. A list comprehension computes all its elements and builds a list out of them, very simple. A generator expression builds a generator. When you create a generator, nothing is actually done yet. Only when you *iterate* over a generator (like I did with the for loop) does it start computing results, one by one, giving each one out as it is needed. If all you're doing with the results is iterating over them once and then throwing them away (like you do here with sum()), using a generator expression saves us some time and space, since we don't have to build a list object that we won't be needing anyway. HTH, Hugo From waynejwerner at gmail.com Mon Nov 8 01:41:48 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 7 Nov 2010 18:41:48 -0600 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Sun, Nov 7, 2010 at 6:31 PM, Hugo Arts wrote: > > here's a list comprehension > >>> a = [x*2 for x in range(10)] > >>> a > [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] > > here's the equivalent generator expression: > >>> a = (x*2 for x in range(10)) Since you're talking about generators and efficiency, it's probably a good idea to point out that range is only a generator in python 3.x. In python 2.x it creates a list. Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 8 01:52:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Nov 2010 00:52:48 -0000 Subject: [Tutor] trying to generate change in print output References: <093FCAFAF29C41FDA5407A572637A115@terryPC> Message-ID: "Terry Green" wrote > Am stumped, when I use this code: > > race=int(row[2]) > raceChek=1 > > if raceChek == race: print ('raceChek ', raceChek, 'race ', race) > else: print ('raceChek ', raceChek,' no match ', 'race ', race); > raceChek = race > I Get this: > > raceChek 1 race 1 > raceChek 1 no match race 2 > raceChek 1 no match race 3 > > Seems my test between race and raceChek doesn't work! What is > wrong? >From the segment of code you posted it loks like it works perfectly. When race is different to 1 you get the second message when it is equal to 1 tyou get the first. What did you expect? And how are you generating the repeated results? Do you have a loop somewhere or just repeatedly run the same code? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davidheiserca at gmail.com Mon Nov 8 01:59:19 2010 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Sun, 7 Nov 2010 16:59:19 -0800 Subject: [Tutor] Interactive visualization in python References: Message-ID: <58BFE9DB7A434E5EAAB9A2EA3FE4C3D8@dheiser> FYI... There is a non-Python commercial program called XMLSpy which displays a visual tree rendition of an XML schema (.xsd) file. The schema file can be created or manipulated with Python/ElementTree. Maybe it can help you in your program development. ----- Original Message ----- From: Aravind Venkatesan To: tutor at python.org Sent: Saturday, November 06, 2010 3:56 PM Subject: [Tutor] Interactive visualization in python Hello, This is Aravind. I am a university graduate student. I am looking for a software module or package to visualize a hierarchial tree data structure in python. Here's the problem: I have a tree(hierarchially represented) with set of nodes and edges. I would like to visualize this tree first. Then i would like to have each node a clickable object so that when a node in the tree is clicked using a mouse, i want to show some data associated with that node(probably a graph) in another popup window. What kind of packages exists in python which will help me solve this? Regards, Aravind ------------------------------------------------------------------------------ _______________________________________________ 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 Nov 8 02:03:36 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Nov 2010 01:03:36 -0000 Subject: [Tutor] List comprehension question References: Message-ID: "Hugo Arts" wrote > Yes. A cast or typecast means converting some data to a different > type, like converting floats to integers, strings to integers, The term cast can be misleading however since in some languages - those decended from C it means treating a piece of data as if it were another type, which is different to converting it. For example in C: char c = '7'; int x = (int)c; //this is type casting in C - it means treat c as an integer int y = atoi(c); // this is type conversion in C x and y are not the same. x is effectively ord('7') whereas y is 7. But in C only the first is referred to as a cast. Not directly relevant in a Python thread but it can cause confusion if newbies see references to casting in the C sense and think it means type conversion. Just feeling picky, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Mon Nov 8 02:15:57 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 7 Nov 2010 17:15:57 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Sun, Nov 7, 2010 at 16:41, Wayne Werner wrote: > On Sun, Nov 7, 2010 at 6:31 PM, Hugo Arts wrote: >> >> >> here's a list comprehension >> >>> a = [x*2 for x in range(10)] >> >>> a >> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >> >> here's the equivalent generator expression: >> >>> a = (x*2 for x in range(10)) >> >> ? > > Since you're talking about generators and efficiency, it's probably a good > idea to point out that range is only a generator in python 3.x. In python > 2.x it creates a list. I should have mentioned that I'm using 3.1 . So this version of my function uses a generator, range(), no? def proper_divisors(n): sum_ = 0 for x in range(1,n): if n % x == 0: sum_ += x return sum_ Dick From waynejwerner at gmail.com Mon Nov 8 02:47:51 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 7 Nov 2010 19:47:51 -0600 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Sun, Nov 7, 2010 at 7:15 PM, Richard D. Moores wrote: > On Sun, Nov 7, 2010 at 16:41, Wayne Werner wrote: > > On Sun, Nov 7, 2010 at 6:31 PM, Hugo Arts wrote: > > I should have mentioned that I'm using 3.1 . > > So this version of my function uses a generator, range(), no? > Correct. The rule of thumb for this type of thing is that if you care about the entire object/collection, you should use a listcomp (or range in 2.x), but if you only care about individual elements you should always use a generator. Your function is a perfect example of this - you only care about the individual #s from 1 up to n, not the collection of numbers as a whole, so a generator is what you should prefer. > > def proper_divisors(n): > sum_ = 0 > for x in range(1,n): > if n % x == 0: > sum_ += x > return sum_ > Generators are super powerful, and my preferred reference on the subject is here: www.dabeaz.com/*generators*/ -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Nov 8 03:12:28 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 7 Nov 2010 18:12:28 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Sun, Nov 7, 2010 at 17:47, Wayne Werner wrote: > On Sun, Nov 7, 2010 at 7:15 PM, Richard D. Moores > wrote: >> >> On Sun, Nov 7, 2010 at 16:41, Wayne Werner wrote: >> > On Sun, Nov 7, 2010 at 6:31 PM, Hugo Arts wrote: >> >> I should have mentioned that I'm using 3.1 . >> >> So this version of my function uses a generator, range(), no? > > Correct. The rule of thumb for this type of thing is that if you care about > the entire object/collection, you should use a listcomp (or range in 2.x), > but if you only care about individual elements you should always use a > generator. Your function is a perfect example of this - you only care about > the individual #s from 1 up to n, not the collection of numbers as a whole, > so a generator is what you should prefer. > >> >> def proper_divisors(n): >> ? ?sum_ = 0 >> ? ?for x in range(1,n): >> ? ? ? ?if n % x == 0: >> ? ? ? ? ? ?sum_ += x >> ? ?return sum_ > > Generators are super powerful, and my preferred reference on the subject is > here:?www.dabeaz.com/generators/ Thank you for the advice and the link. Dick From steve at pearwood.info Mon Nov 8 12:43:40 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 08 Nov 2010 22:43:40 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: <4CD7E26C.3010908@pearwood.info> Richard D. Moores wrote: > So this version of my function uses a generator, range(), no? > > def proper_divisors(n): > sum_ = 0 > for x in range(1,n): > if n % x == 0: > sum_ += x > return sum_ I'm going to be pedantic here... but to quote the Middleman, specificity is the soul of all good communication. The term "generator" in Python refers specifically to an object akin to ordinary functions. Instead of using return, they use yield: def g(n): n = 2*n yield n yield n+1 g itself is a "generator function", and the result of calling g is a "generator object". In practice, people tend to be sloppy and just refer to both the function g and the result of calling it as generators, expecting the reader to tell from context which is which. But pedantically, we can see the difference: >>> g # the function itself >>> type(g) >>> g(1) # the result of calling the function >>> type(g(1)) Generators are a special type of "iterators" -- iterators are objects which can be iterated over, like lists, strings, and many others. In this case, the generator is a special type of executable function which can be paused mid-process. If you do this: it = g(3) # say next(it) the built-in next() function starts executing the generator object. The code is executed up to the first yield statement: n = 2*n yield n and so next(it) returns 2*3 = 6. Then execution pauses, and the generator just waits. (Aside: in Python 2.x, next(it) is written it.next() instead.) The next time you call next(it), execution continues until the next yield: yield n+1 and so next(it) will now return 6+1 = 7. Finally, if you call next(it) again, execution drops off the end of the code, and the generator will raise StopIteration. Now, this seems a bit complicated, but Python can handle most of that for you. Instead of manually calling next() on the generator object, if you use it in a for-loop: for i in g(3): print(i) the for-loop will handle calling next and catching the StopIterator, and you simply see i = 6, 7. Or you can pass it to functions such as list: list(g(3)) and get pretty much the same result. (For advanced use: in newer versions of Python, generators have become even more powerful, but complex, objects called co-routines. Co-routines allow you to send data *into* the middle of the running code, as well as extract data using yield.) Python also has "generator expressions" -- this is a short-cut syntax for particularly simple generators. Generator expressions look just like list expressions, except they use round brackets instead of square: >>> (x+1 for x in (1, 2, 4) if x%2 == 0) at 0xb7a7be3c> List comprehensions run all the way to the end, producing a list. Generator expressions run lazily, only producing values one at a time as needed. So compare: sum([list comp]) vs sum(gen expr) The first case needs to find storage for the entire list first, which is potentially huge. But the second case just adds the numbers one at a time, and so never needs much memory. So, that's generators... what about range? range is also an iterator, that is, something you can iterate over, but it's not a generator: >>> type(range(20)) It is its own special type of object, like list, str, int or dict. Coming back to your function: def proper_divisors(n): sum_ = 0 for x in range(1,n): if n % x == 0: sum_ += x return sum_ we can write that much more simply: def proper_divisors(n): return sum(x for x in range(1, n) if n%x == 0) And we can speed it up a bit by realising that there's no need to go all the way up to n in the range. After all, we know that (say) 100%96 can't possibly be zero. The largest factor of n is sqrt(n): def proper_divisors(n): return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0) For large n, that will save a lot of time. -- Steven From alan.gauld at btinternet.com Mon Nov 8 17:28:07 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Nov 2010 16:28:07 -0000 Subject: [Tutor] List comprehension question References: <4CD7E26C.3010908@pearwood.info> Message-ID: "Steven D'Aprano" wrote > I'm going to be pedantic here... but to quote the Middleman, > specificity is the soul of all good communication. Be pedantic! :-) I really liked the explanation although I already sort of knew most of it. But there were a few nuggets in there I'd missed, like range() being a type all of its own. But one, slightly off-topic, question: > def proper_divisors(n): > return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0) > Why use math.sqrt() instead of just using the ** operator? return sum(x for x in range(1, int(n**0.5)) if n%x == 0) I'd have expected ** to be significantly faster than calling the function, and given this is a performance tweak...? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Mon Nov 8 17:44:44 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 08 Nov 2010 17:44:44 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: Alan Gauld, 08.11.2010 17:28: > "Steven D'Aprano" wrote >> def proper_divisors(n): >> return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0) > > Why use math.sqrt() instead of just using the ** operator? > > return sum(x for x in range(1, int(n**0.5)) if n%x == 0) > > I'd have expected ** to be significantly faster than calling the > function, and given this is a performance tweak...? Since this operation is only evaluated once in the whole runtime of the loop, I think readability beats the likely very tiny performance difference here. Stefan From stefan_ml at behnel.de Mon Nov 8 18:10:23 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 08 Nov 2010 18:10:23 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: Hugo Arts, 08.11.2010 00:53: > On Mon, Nov 8, 2010 at 12:36 AM, Richard D. Moores wrote: >> def proper_divisors(n): >> """ >> Return the sum of the proper divisors of positive integer n >> """ >> return sum([x for x in range(1,n) if int(n/x) == n/x]) >> >> The list comprehension is this function is inefficient in that it computes >> n/x twice. I'd like to do an a = n/x and use a in >> "if int(a) == a", but I don't know how. >> > > You can't do that inside a list comprehension. Either get rid of the > comprehension and do a regular loop, or get rid of the n/x expression. > > I'd suggest replacing the whole check with x % n == 0. n is a proper > divisor of x if there is no remainder after division, after all. This > also means you won't have to do a cast, which tend to be fairly > expensive. > > On another note, getting rid of the list comprehension and using a > generator expression will be even faster, since you won't have to > build the list. I gave this suggestion a try. It is true for me when run in CPython 3.2: $ python3 -m timeit -s 'from divisors import forloop' 'forloop(1000000)' 10 loops, best of 3: 161 msec per loop $ python3 -m timeit -s 'from divisors import genexp' 'genexp(1000000)' 10 loops, best of 3: 159 msec per loop $ python3 -m timeit -s 'from divisors import listcomp' 'listcomp(1000000)' 10 loops, best of 3: 171 msec per loop However, it is no longer true when I run the same thing in Cython: $ python3 -m timeit -s 'from divisors import forloop' 'forloop(1000000)' 100 loops, best of 3: 13.6 msec per loop $ python3 -m timeit -s 'from divisors import genexp' 'genexp(1000000)' 100 loops, best of 3: 13.6 msec per loop $ python3 -m timeit -s 'from divisors import listcomp' 'listcomp(1000000)' 100 loops, best of 3: 12.6 msec per loop Here, the listcomp clearly wins, i.e. return sum([x for x in range(1,n) if n%x == 0]) is actually *faster* than the inlined loop for result = sum(x for x in range(1,n) if n%x == 0) return result This totally surprised me, until I figured out what was going on here. In the case of the listcomp, the inner loop is smaller, it does not contain the adding. It only contains the division that filters out the non-divisors. Then, from time to time, it calls into the list appender to append a Python integer that actually matched the condition. But the final list is tiny, so this is done extremely rarely compared to the number of loop iterations. The tighter loop simply wins. And summing up a short list in another tight loop is just another very fast operation. Lesson learned: Sometimes, it can be worth splitting a loop in two, one with a tight filter for the values, and another one to work on the remaining values. Stefan From alan.gauld at btinternet.com Mon Nov 8 19:29:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Nov 2010 18:29:56 -0000 Subject: [Tutor] List comprehension question References: <4CD7E26C.3010908@pearwood.info> Message-ID: "Stefan Behnel" wrote >> Why use math.sqrt() instead of just using the ** operator? >> >> return sum(x for x in range(1, int(n**0.5)) if n%x == 0) >> > Since this operation is only evaluated once in the whole runtime of > the loop, I think readability beats the likely very tiny performance > difference here. Ah, I wondered if readability was the reason. I hadn't thought about it hard enough to notice the sqrt() would only be called once! :-) As to readability I personally prefer the exponentiation sign (or even pow()!) and don't think I have ever used math.sqrt() in my 12 years of Python. But I recognise that some may prefer sqrt, especially if they don't have a math background. Alan G. From alan.gauld at btinternet.com Mon Nov 8 19:34:13 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 8 Nov 2010 18:34:13 -0000 Subject: [Tutor] List comprehension question References: Message-ID: "Stefan Behnel" wrote >> On another note, getting rid of the list comprehension and using a >> generator expression will be even faster, since you won't have to >> build the list. > > I gave this suggestion a try. It is true for me when run in CPython > 3.2: > > However, it is no longer true when I run the same thing in Cython: > ... > Lesson learned: > > Sometimes, it can be worth splitting a loop in two, one with a tight > filter for the values, and another one to work on the remaining > values. And another good example of how hard it is to guess the optimal solution in performance terms. It is one area where nothing beats trial and test. And another reason why premature optimisation should be resisted! :-) Alan G. From jbiquez at icsmx.com Mon Nov 8 21:44:45 2010 From: jbiquez at icsmx.com (Jorge Biquez) Date: Mon, 08 Nov 2010 14:44:45 -0600 Subject: [Tutor] Too different 2.6 vs 2.7? Message-ID: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> Hello all. Newbie question. Are there really BIG differences between version 2.6 and 2.7? Under my ubuntu configuration I can not install version 2.7, searching the why, but the version 2.6 is maintained and installed by the ubuntu software center..... As a newby , trying to learn all the features of all the libraries. Will I miss TOO much if I stay under version 2.6? Or it will be better to stay under 2.7 (in that case under Windows XP) Thanks in advance for your comments. Jorge Biquez From karim.liateni at free.fr Mon Nov 8 22:00:59 2010 From: karim.liateni at free.fr (Karim) Date: Mon, 08 Nov 2010 22:00:59 +0100 Subject: [Tutor] Too different 2.6 vs 2.7? In-Reply-To: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> Message-ID: <4CD8650B.1090504@free.fr> Hello Jorge, I have Ubuntu 10.04 LTS and get the same issue. I installed 2.7 version manually in another place using -prefix option. It works as long as you are pointing to the correct bin (python2.7) and the local lib/ installation (PYTHONPATH) from python 2.7. Regards Karim On 11/08/2010 09:44 PM, Jorge Biquez wrote: > Hello all. > Newbie question. > > Are there really BIG differences between version 2.6 and 2.7? > > Under my ubuntu configuration I can not install version 2.7, searching > the why, but the version 2.6 is maintained and installed by the ubuntu > software center..... > > As a newby , trying to learn all the features of all the libraries. > Will I miss TOO much if I stay under version 2.6? Or it will be better > to stay under 2.7 (in that case under Windows XP) > > Thanks in advance for your comments. > > Jorge Biquez > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From emile at fenx.com Mon Nov 8 22:07:01 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 08 Nov 2010 13:07:01 -0800 Subject: [Tutor] Too different 2.6 vs 2.7? In-Reply-To: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> Message-ID: On 11/8/2010 12:44 PM Jorge Biquez said... > Hello all. > Newbie question. > > Are there really BIG differences between version 2.6 and 2.7? No, however there is quite a lot of info at http://docs.python.org/dev/whatsnew/2.7.html that details the changes, mostly 3.x features/bug-fixes back-ported to 2.7 to provide an easier upgrade path. Emile From python at bdurham.com Mon Nov 8 22:14:06 2010 From: python at bdurham.com (python at bdurham.com) Date: Mon, 08 Nov 2010 16:14:06 -0500 Subject: [Tutor] Too different 2.6 vs 2.7? In-Reply-To: <4CD8650B.1090504@free.fr> References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> <4CD8650B.1090504@free.fr> Message-ID: <1289250846.18465.1404252343@webmail.messagingengine.com> Jorge, Python 2.7 supports an updated version of the Tkinter GUI framework with support for native themes (ttk). This makes it possible to create professional looking user interfaces without having to install a separate GUI framework like wxPython or pyQt. Malcolm From steve at pearwood.info Mon Nov 8 22:41:34 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Nov 2010 08:41:34 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: <4CD86E8E.7080006@pearwood.info> Alan Gauld wrote: > > "Steven D'Aprano" wrote > >> I'm going to be pedantic here... but to quote the Middleman, >> specificity is the soul of all good communication. > > Be pedantic! :-) > I really liked the explanation although I already sort of knew most of it. > But there were a few nuggets in there I'd missed, like range() being > a type all of its own. Thank you :) > But one, slightly off-topic, question: > >> def proper_divisors(n): >> return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0) >> > > Why use math.sqrt() instead of just using the ** operator? > > return sum(x for x in range(1, int(n**0.5)) if n%x == 0) > > I'd have expected ** to be significantly faster than calling the > function, and given this is a performance tweak...? Mostly personal taste, but I would expect math.sqrt() to be more accurate than a generic exponentiation operator, although in this case the difference shouldn't matter. If your value for n is so large that you need to care about the floating point rounding errors in n**0.5, you're probably using the wrong tool. As for the speed, sqrt() only gets called once, so the difference shouldn't matter. But for what it's worth: [steve at sylar ~]$ python3 -m timeit -s "import math" "math.sqrt(1234567)" 1000000 loops, best of 3: 0.486 usec per loop [steve at sylar ~]$ python3 -m timeit "1234567**0.5" 1000000 loops, best of 3: 0.265 usec per loop So on my machine, the overhead of calling a function is about 0.2 micro-seconds. Compare that to: [steve at sylar ~]$ python3 -m timeit -s "n=1234567" "sum(x for x in range(1, int(n**0.5)) if n%x == 0)" 1000 loops, best of 3: 515 usec per loop So changing from math.sqrt(n) to n**0.5 increases the overall speed by approximately 0.04%. Truly a micro-optimization :) (I'm deliberately not including the time to import math here. I assume that the function proper_divisors() will be in a module with other maths related functions, and therefore you need to import it regardless.) -- Steven From g.nius.ck at gmail.com Mon Nov 8 22:53:00 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 08 Nov 2010 16:53:00 -0500 Subject: [Tutor] Server In-Reply-To: References: <4CD3533B.1030900@gmail.com> <4CD36213.3060903@aim.com> <4CD45883.3090502@gmail.com> Message-ID: <4CD8713C.1050805@gmail.com> On 11/5/2010 8:10 PM, Alan Gauld wrote: > > "Chris King" wrote > >>> If you are using Windows, turn off the built-in firewall. That's >>> what fixed my problems. >>> ~Corey > >> also, it is on the same network, so the server shouldn't be a problem > > I think Corey means the firewall on your PC if you have one. It could > be blocking outgoing traffic to uncommon port numbers or somesuch. > > Its worth trying if only to eliminate the possibility > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor The firewall pops up and I click allow. It has nothing to do with the firewall at all. Did you find any other errors at all? -------------- next part -------------- A non-text attachment was scrubbed... Name: server.py Type: text/x-python Size: 3334 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: client.py Type: text/x-python Size: 2167 bytes Desc: not available URL: From jbiquez at icsmx.com Mon Nov 8 23:15:00 2010 From: jbiquez at icsmx.com (Jorge Biquez) Date: Mon, 08 Nov 2010 16:15:00 -0600 Subject: [Tutor] Too different 2.6 vs 2.7? In-Reply-To: <1289250846.18465.1404252343@webmail.messagingengine.com> References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> <4CD8650B.1090504@free.fr> <1289250846.18465.1404252343@webmail.messagingengine.com> Message-ID: <201011082223.oA8MN3pI087543@krusty.intranet.com.mx> Hello all. So I guess the best is to have version 2.7 working. Thanks to all for the comments. Jorge Biquez At 03:14 p.m. 08/11/2010, python at bdurham.com wrote: >Jorge, > >Python 2.7 supports an updated version of the Tkinter GUI framework with >support for native themes (ttk). This makes it possible to create >professional looking user interfaces without having to install a >separate GUI framework like wxPython or pyQt. > >Malcolm From steve at pearwood.info Mon Nov 8 23:17:48 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Nov 2010 09:17:48 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: <4CD8770C.8090107@pearwood.info> Stefan Behnel wrote: > Hugo Arts, 08.11.2010 00:53: [...] >> On another note, getting rid of the list comprehension and using a >> generator expression will be even faster, since you won't have to >> build the list. > > I gave this suggestion a try. It is true for me when run in CPython 3.2: [...] > However, it is no longer true when I run the same thing in Cython: [...] > Lesson learned: > > Sometimes, it can be worth splitting a loop in two, one with a tight > filter for the values, and another one to work on the remaining values. Nice analysis, thank you. However, surely the most important lesson to be learned is: Don't make assumptions about what is faster, measure it and find out! -- Steven From jbiquez at icsmx.com Tue Nov 9 01:18:17 2010 From: jbiquez at icsmx.com (Jorge Biquez) Date: Mon, 08 Nov 2010 18:18:17 -0600 Subject: [Tutor] Commercial or Famous Applicattions.? Message-ID: <201011090026.oA90QP1S095565@krusty.intranet.com.mx> Hello all. Newbie question. Sorry. Can you mention applications/systems/solutions made with Python that are well known and used by public in general? ANd that maybe we do not know they are done with Python? I had a talk with a friend, "PHP-Only-Fan", and he said (you know the schema of those talks) that "his" language is better and that "just to prove it" there are not too many applications done with Python than the ones done with PHP and that "that of course is for something". That conversation , that by the way I guess is useless at all , makes me thing the idea of ask of applications done with Python. Not for debate the argument of that guy BUT to learn what can be done with Python. In grphical interface, schemas of jobs, etc. I know that there are tons of solutions but would like to hear of possible about the ones you have used most or recommend the most. As an example, I love and have used in the last years MAILMAN, never crashed, always works even on my small and old Intel Pentium III with a 10GB hard disk and 640KB of RAM. Still working and will work for sure (running under FreeBsd by the way). Thanks in advance for your comments. Jorge Biquez From ncastillo at umail.ucsb.edu Tue Nov 9 00:28:44 2010 From: ncastillo at umail.ucsb.edu (Natalie Kristine T. Castillo) Date: Mon, 08 Nov 2010 15:28:44 -0800 Subject: [Tutor] Columnar Transposition Cipher question Message-ID: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> Hi, I need help on how exactly to solve this: To send secret messages you and your partner have decided to use the columnar function you have written to perform columnar transposition cipher for this course. You have received the ciphertext EXLYHILOSHOOAETU from your friend. You two decide to use the keyword MARS. What message did your friend send you? Show your steps and do it by hand. From carroll at tjc.com Tue Nov 9 02:16:05 2010 From: carroll at tjc.com (Terry Carroll) Date: Mon, 8 Nov 2010 17:16:05 -0800 (PST) Subject: [Tutor] Too different 2.6 vs 2.7? In-Reply-To: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> Message-ID: On Mon, 8 Nov 2010, Jorge Biquez wrote: > Are there really BIG differences between version 2.6 and 2.7? I'm in a similar boat. I use Ubuntu 10.04 aw well as Windows XP, Vista and 7. I keep to similar levels just to avoid confusion and at present run Python 2.6 on all systems. If I had an urgent enough need, I'd go to ActivePython 2.7 on the Windows boxes, but so far, no need other than to have the latest. The only feature I'm pining for at all is the new argparse; but it depends on your needs. > Under my ubuntu configuration I can not install version 2.7, searching the > why, but the version 2.6 is maintained and installed by the ubuntu software > center..... It's possible to install 2.7 on Ubuntu, but I'm not piqued enough to do so. If you're interested, a couple posts on Ubuntu Forums describe it: http://wwww.ubuntuforums.org/showthread.php?t=1524491 http://ubuntuforums.org/showthread.php?t=1582739 > As a newby , trying to learn all the features of all the libraries. Will I > miss TOO much if I stay under version 2.6? Or it will be better to stay under > 2.7 (in that case under Windows XP) For myself, I think I'll be fine in 2.6. I usually upgrade when I see a particular feature I want. From alan.gauld at btinternet.com Tue Nov 9 02:20:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Nov 2010 01:20:43 -0000 Subject: [Tutor] Server References: <4CD3533B.1030900@gmail.com><4CD36213.3060903@aim.com> <4CD45883.3090502@gmail.com> <4CD8713C.1050805@gmail.com> Message-ID: "Chris King" wrote >> I think Corey means the firewall on your PC if you have one. It >> could >> be blocking outgoing traffic to uncommon port numbers or somesuch. > The firewall pops up and I click allow. It has nothing to do with > the > firewall at all. Did you find any other errors at all? OK, despite the fact that the firewall is evidently being triggered lets assume that it is not the firewall to blame, do you gt any other signs of life? Any error messages? Any responses at all? So far you haven't given us a whole lot of information to go on... no code, no OS, no network settings. It's hard to be specific. If the code works on localhost it is unlikely to be the code at fault. More likely to be a network issue, either a wrong IP address, port address or, sorry, a firewall setting. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 9 02:28:18 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Nov 2010 01:28:18 -0000 Subject: [Tutor] Too different 2.6 vs 2.7? References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> Message-ID: "Jorge Biquez" wrote > Are there really BIG differences between version 2.6 and 2.7? No. > As a newby , trying to learn all the features of all the libraries. That will take you a long time. Better to use it writing software IMHO. Learn the libraries you need as you need them. If you need something remember to look in the library first... I've been using Python for 12 years now and only used about 30% of the modules in the library. > Will I miss TOO much if I stay under version 2.6? Or it will be > better to stay under 2.7 (in that case under Windows XP) If 2.6 works stick with it for now till somebody in Ubuntu land fixes the issue. I still use 2.4 on my netbook, 2.5 on my Mac and 2.6 (and 3.1) on my desktop PC. I've been thinking of giving 2.7 a whirl but I'm in no hurry... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 9 02:30:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 9 Nov 2010 01:30:21 -0000 Subject: [Tutor] Commercial or Famous Applicattions.? References: <201011090026.oA90QP1S095565@krusty.intranet.com.mx> Message-ID: "Jorge Biquez" wrote > Can you mention applications/systems/solutions made with Python that > are well known and used by public in general? ANd that maybe we do > not know they are done with Python? The Python web site has an advocacy section, you will find several success stories there. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Tue Nov 9 02:46:36 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 8 Nov 2010 19:46:36 -0600 Subject: [Tutor] Commercial or Famous Applicattions.? In-Reply-To: <201011090026.oA90QP1S095565@krusty.intranet.com.mx> References: <201011090026.oA90QP1S095565@krusty.intranet.com.mx> Message-ID: just off the top of my head... NASA uses it. Lots of games use Python as their game logic/scripting language (how many use PHP? probably approaching 0. LUA is more popular than Python but Python is much more popular than PHP). The first ever bittorrent client (the official one) was written in Python. The game Eve Online is written completely in Python. Youtube uses lots of Python, Facebook uses some. Reddit is written in Python as well. Google App Engine has both Python and Java interfaces. They don't have a PHP interface; I wonder why? Lots of jobs at Google (even Java jobs and such) require Python experience; they don't tend to require PHP experience too. Because PHP doesn't really teach you much. The syntax is not nearly as elegant. It's buggy and rough around the edges. They have gross workarounds for a lot of things that should be language features. That's not to say that Python's the only language that is better than PHP for most things. Ruby is also a good option. But these languages are both infinitely more flexible _right now_ (not based almost solely for web apps) and better to use for almost everything than PHP. PHP has its place, and part of the reason it still has that place is because a lot of web hosts haven't started hosting Python and Ruby frameworks in a scalable, fast way. But it's not the frameworks' fault. That's just my 2c. On Mon, Nov 8, 2010 at 6:18 PM, Jorge Biquez wrote: > Hello all. > > Newbie question. Sorry. > > Can you mention applications/systems/solutions made with Python that are > well known and used by public in general? ANd that maybe we do not know they > are done with Python? > > I had a talk with a friend, "PHP-Only-Fan", and he said (you know the schema > of those talks) that "his" language is better and that "just to prove it" > there are not too many applications done with Python than the ones done with > PHP and that "that of course is for something". That conversation , that by > the way I guess is useless at all , makes me thing the idea of ask of > applications done with Python. Not for debate the argument of that guy BUT > to learn what can be done with Python. In grphical interface, schemas of > jobs, etc. I know that there are tons of solutions but would like to hear of > possible about the ones you have used most or recommend the most. > > As an example, I love and have used in the last years MAILMAN, never > crashed, always works even on my small and old Intel Pentium III with a 10GB > hard disk and 640KB of RAM. Still working and will work for sure (running > under FreeBsd by the way). > > Thanks in advance for your comments. > > Jorge Biquez > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Tue Nov 9 02:47:46 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 8 Nov 2010 19:47:46 -0600 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> Message-ID: On Mon, Nov 8, 2010 at 5:28 PM, Natalie Kristine T. Castillo wrote: > Hi, I need help on how exactly to solve this: That's nice. > > To send secret messages you and your partner have decided to use the > columnar function you have written to perform columnar transposition cipher > for this course. You have received the ciphertext EXLYHILOSHOOAETU from your > friend. You two decide to use the keyword MARS. What message did your friend > send you? Show your steps and do it by hand. > Where's the function you've written? From rabidpoobear at gmail.com Tue Nov 9 02:51:14 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 8 Nov 2010 19:51:14 -0600 Subject: [Tutor] Server In-Reply-To: <4CD8713C.1050805@gmail.com> References: <4CD3533B.1030900@gmail.com> <4CD36213.3060903@aim.com> <4CD45883.3090502@gmail.com> <4CD8713C.1050805@gmail.com> Message-ID: On Mon, Nov 8, 2010 at 3:53 PM, Chris King wrote: > ?On 11/5/2010 8:10 PM, Alan Gauld wrote: >> >> "Chris King" wrote >> >>>> If you are using Windows, turn off the built-in firewall. That's what >>>> fixed my problems. >>>> ~Corey >> >>> also, it is on the same network, so the server shouldn't be a problem >> >> I think Corey means the firewall on your PC if you have one. It could >> be blocking outgoing traffic to uncommon port numbers or somesuch. >> >> Its worth trying if only to eliminate the possibility >> > > The firewall pops up and I click allow. It has nothing to do with the > firewall at all. Did you find any other errors at all? > You should disable the firewall completely on both computers to perform an actual test. Also, perhaps be nicer to people who are giving up their time to try to help you? From wprins at gmail.com Tue Nov 9 02:51:48 2010 From: wprins at gmail.com (Walter Prins) Date: Tue, 9 Nov 2010 01:51:48 +0000 Subject: [Tutor] Commercial or Famous Applicattions.? In-Reply-To: <201011090026.oA90QP1S095565@krusty.intranet.com.mx> References: <201011090026.oA90QP1S095565@krusty.intranet.com.mx> Message-ID: Hi Jorge, Have a look at this page: http://www.python.org/about/quotes/ A few choice points to maybe make him think: 1.) Python is one of the top 3 languages at Google. (Where is PHP?...) 2.) Python can be used for GUI apps and has bindings for several GUI widget sets. (PHP?) 3.) Python can be used for Command line apps (With some work, PHP can be too, but it's not exactly natural.) 4.) Python can be used for shell type scripts (OK, so can PHP, but again it's not really its forte) 5.) Python can be used for text processing and is good at it (e.g. lxml, Beautiful soup, good regex support, etc. etc... PHP?) 6.) Python can be used for games (as demonstrated by Eve online for example. 50,000 simultaneous players. PHP? I think not...) 7.) Python can be used for heavy duty number crunching (e.g. Numpy and friends. PHP?...) 8.) Python can be used for image manipulation (e.g. PIL and friends. PHP?...) 9.) Python easily runs or is available on multiple platforms, including Windows, Linux, MacOS, as well as other more esoteric platforms, e.g. Android phones. (PHP?) etc. etc... I think that's enough for now... you get the picture. (Obviously I'm a bit biased ;) ) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Tue Nov 9 02:52:15 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 08 Nov 2010 20:52:15 -0500 Subject: [Tutor] Server In-Reply-To: References: <4CD3533B.1030900@gmail.com><4CD36213.3060903@aim.com> <4CD45883.3090502@gmail.com> <4CD8713C.1050805@gmail.com> Message-ID: <4CD8A94F.1060705@gmail.com> On 11/8/2010 8:20 PM, Alan Gauld wrote: > > "Chris King" wrote > >>> I think Corey means the firewall on your PC if you have one. It could >>> be blocking outgoing traffic to uncommon port numbers or somesuch. > >> The firewall pops up and I click allow. It has nothing to do with the >> firewall at all. Did you find any other errors at all? > > OK, despite the fact that the firewall is evidently being triggered > lets assume that it is not the firewall to blame, do you gt any > other signs of life? Any error messages? Any responses at all? > > So far you haven't given us a whole lot of information to go on... > no code, no OS, no network settings. It's hard to be specific. > > If the code works on localhost it is unlikely to be the code at fault. > More likely to be a network issue, either a wrong IP address, > port address or, sorry, a firewall setting. > > Actually, I fixed the problem myself. On the server, I had to set the host to an empty to string. Now I am wondering, how do you exit a server loop within the handler, so you can use the port again without it throwing a fit. From waynejwerner at gmail.com Tue Nov 9 02:55:05 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 8 Nov 2010 19:55:05 -0600 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> Message-ID: On Mon, Nov 8, 2010 at 5:28 PM, Natalie Kristine T. Castillo < ncastillo at umail.ucsb.edu> wrote: > Hi, I need help on how exactly to solve this: > > To send secret messages you and your partner have decided to use the > columnar function you have written to perform columnar transposition cipher > for this course. You have received the ciphertext EXLYHILOSHOOAETU from your > friend. You two decide to use the keyword MARS. What message did your friend > send you? Show your steps and do it by hand. This sounds an awful lot like homework. It's not our policy to solve homework, but if you get stuck we'll happily give you nudges in the right direction. This problem also happens to be language agnostic - meaning it doesn't matter whether you solve it in Python, Assembly, C++, Ruby, or by hand. Of course the problem description also says show your steps and do it by hand, which suggests that the problem is not terribly difficult to solve if you have some familiarity with the columnar transposition cipher. I've never heard of it before, but I'm sure www.google.com and http://en.wikipedia.orghave plenty to say on the subject. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Tue Nov 9 02:57:46 2010 From: g.nius.ck at gmail.com (Chris King) Date: Mon, 08 Nov 2010 20:57:46 -0500 Subject: [Tutor] Networking In-Reply-To: References: <4CA788E2.4060006@gmail.com> <33D037A9-0230-42B3-9AFC-A1884F00AE88@gmail.com> <4CA90FAF.1070002@gmail.com> <4CB3A1A7.9080804@gmail.com> <4CB7ACEB.1050405@gmail.com> Message-ID: <4CD8AA9A.5020800@gmail.com> On 10/14/2010 9:28 PM, James Mills wrote: > On Fri, Oct 15, 2010 at 11:22 AM, chris wrote: >>> But what if I want it to serve one client, go to another and then go back. >>> How does that work? > You do some I/O multi-plexing or multi-processing/threading. > > You might want to do some reading on this. > > cheers > James > or I could just have one client use multiple socket objects From matlocs at odscompanies.com Tue Nov 9 02:58:36 2010 From: matlocs at odscompanies.com (Shawn Matlock) Date: Mon, 8 Nov 2010 17:58:36 -0800 Subject: [Tutor] query result set In-Reply-To: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> Message-ID: <1160CE2227C1694BA39144335BC35025373CEF1D06@MAIL.pdx.odshp.com> I am able to successfully query a MySQL database using zxJDBC but the result set seems odd to me. It returns the following: [(u'envDB', u'systest2'), (u'envDir', u'st2'), (u'envCellName', u'Systest2Cell'), (u'envFrontEnd', u'systest2FrontEnd'), (u'envTag', u'system_test2')] Why is there a "u" before every entry? Can someone point me to an example that puts the results into a List (or Dictionary) without the "u"? Thank you, Shawn csdbConn = zxJDBC.connect("jdbc:mysql://myhost:3306/mydb", "User", "Password", "com.mysql.jdbc.Driver") csdbCursor = csdbConn.cursor(1) envsql = "select envVariable, envValue from ODS_ENV_DICT where envName = 'ST2'" csdbCursor.execute(envsql) print csdbCursor.fetchall() csdbCursor.close() csdbConn.close() From petluke at gmail.com Tue Nov 9 04:12:19 2010 From: petluke at gmail.com (Luke Pettit) Date: Tue, 9 Nov 2010 14:12:19 +1100 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> Message-ID: I can suggest that the X should probably be a "D" you may want to check this with your tutor Although as a python noob I don't have the foggiest on how to do this in python, but will keep this for an exercise for if, and when I do. On paper it's pretty simple once you Wikipedia it. On 9 November 2010 12:55, Wayne Werner wrote: > On Mon, Nov 8, 2010 at 5:28 PM, Natalie Kristine T. Castillo < > ncastillo at umail.ucsb.edu> wrote: > >> Hi, I need help on how exactly to solve this: >> >> To send secret messages you and your partner have decided to use the >> columnar function you have written to perform columnar transposition cipher >> for this course. You have received the ciphertext EXLYHILOSHOOAETU from your >> friend. You two decide to use the keyword MARS. What message did your friend >> send you? Show your steps and do it by hand. >> > > This sounds an awful lot like homework. It's not our policy to solve > homework, but if you get stuck we'll happily give you nudges in the right > direction. > > This problem also happens to be language agnostic - meaning it doesn't > matter whether you solve it in Python, Assembly, C++, Ruby, or by hand. > > Of course the problem description also says show your steps and do it by > hand, which suggests that the problem is not terribly difficult to solve if > you have some familiarity with the columnar transposition cipher. I've never > heard of it before, but I'm sure www.google.com and > http://en.wikipedia.org have plenty to say on the subject. > > HTH, > Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Luke Pettit -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 9 05:01:28 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 9 Nov 2010 15:01:28 +1100 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> Message-ID: <20101109040128.GA23247@cybersource.com.au> On Mon, Nov 08, 2010 at 03:28:44PM -0800, Natalie Kristine T. Castillo wrote: > Hi, I need help on how exactly to solve this: > > To send secret messages you and your partner have decided to use the > columnar function you have written to perform columnar transposition > cipher for this course. You have received the ciphertext > EXLYHILOSHOOAETU from your friend. You two decide to use the keyword > MARS. What message did your friend send you? Show your steps and do it > by hand. This link might help: http://en.wikipedia.org/wiki/Transposition_cipher#Columnar_transposition Otherwise, this isn't exactly on-topic for a Python list, particularly since you're told to do it by hand. But in case anyone is interested: http://pypi.python.org/pypi/obfuscate Good luck :) -- Steven From steve at pearwood.info Tue Nov 9 05:09:47 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 9 Nov 2010 15:09:47 +1100 Subject: [Tutor] query result set In-Reply-To: <1160CE2227C1694BA39144335BC35025373CEF1D06@MAIL.pdx.odshp.com> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> <1160CE2227C1694BA39144335BC35025373CEF1D06@MAIL.pdx.odshp.com> Message-ID: <20101109040947.GB23247@cybersource.com.au> On Mon, Nov 08, 2010 at 05:58:36PM -0800, Shawn Matlock wrote: > I am able to successfully query a MySQL database using zxJDBC but the result set seems odd to me. It returns the following: > > [(u'envDB', u'systest2'), (u'envDir', u'st2'), (u'envCellName', u'Systest2Cell'), (u'envFrontEnd', u'systest2FrontEnd'), (u'envTag', u'system_test2')] > > Why is there a "u" before every entry? Can someone point me to an example that puts the results into a List (or Dictionary) without the "u"? No, you have misunderstood what you are asking for. That is like asking for lists without [] or dicts without {}. In Python 2.x, there are two types of strings: byte strings, which have delimiters " ", and unicode (text) strings, which have delimiters u" and ". Notice that the u is not part of the string contents, but is part of the delimiter, just like the " in byte strings, or [ and ] for lists. Coming from a database, the strings are Unicode, which means that they could contain characters that can't be stored in byte-strings. So you have to use Unicode, which means the object repr() looks like: u"text inside the quotation marks" But if you print them, you get: text inside the quotation marks *without* the quotation marks included. The slight complication is that if you put the Unicode string inside a list, dict or tuple, Python prints the repr() which means you see the u" ". If you don't like it, write a helper function that prints the list the way you want, or try the pprint module. -- Steven > > Thank you, > Shawn > > > > csdbConn = zxJDBC.connect("jdbc:mysql://myhost:3306/mydb", "User", "Password", "com.mysql.jdbc.Driver") > > csdbCursor = csdbConn.cursor(1) > > envsql = "select envVariable, envValue from ODS_ENV_DICT where envName = 'ST2'" > > csdbCursor.execute(envsql) > > print csdbCursor.fetchall() > > csdbCursor.close() > csdbConn.close() > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rdmoores at gmail.com Tue Nov 9 06:31:37 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 8 Nov 2010 21:31:37 -0800 Subject: [Tutor] List comprehension question In-Reply-To: <4CD7E26C.3010908@pearwood.info> References: <4CD7E26C.3010908@pearwood.info> Message-ID: On Mon, Nov 8, 2010 at 03:43, Steven D'Aprano wrote: > Richard D. Moores wrote: > Coming back to your function: > > def proper_divisors(n): > ? ?sum_ = 0 > ? ?for x in range(1,n): > ? ? ? ?if n % x == 0: > ? ? ? ? ? ?sum_ += x > ? ?return sum_ > > > we can write that much more simply: > > def proper_divisors(n): > ? ?return sum(x for x in range(1, n) if n%x == 0) > > > And we can speed it up a bit by realising that there's no need to go all the > way up to n in the range. After all, we know that (say) 100%96 can't > possibly be zero. The largest factor of n is sqrt(n): > > > def proper_divisors(n): > ? ?return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0) > > > For large n, that will save a lot of time. That sqrt(n) works for speeding up the finding of primes, but here we want to use int(n/2) (and why didn't I think of that?), which results in about a 2x speedup. See . Dick From stefan_ml at behnel.de Tue Nov 9 07:43:36 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 09 Nov 2010 07:43:36 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: Richard D. Moores, 09.11.2010 06:31: > On Mon, Nov 8, 2010 at 03:43, Steven D'Aprano wrote: >> Richard D. Moores wrote: > >>> Coming back to your function: >>> >>> def proper_divisors(n): >>> sum_ = 0 >>> for x in range(1,n): >>> if n % x == 0: >>> sum_ += x >>> return sum_ >>> >>> we can write that much more simply: >>> >>> def proper_divisors(n): >>> return sum(x for x in range(1, n) if n%x == 0) >> >> And we can speed it up a bit by realising that there's no need to go all the >> way up to n in the range. After all, we know that (say) 100%96 can't >> possibly be zero. The largest factor of n is sqrt(n): >> >> def proper_divisors(n): >> return sum(x for x in range(1, int(math.sqrt(n))) if n%x == 0) >> >> >> For large n, that will save a lot of time. > > That sqrt(n) works for speeding up the finding of primes, but here we > want to use int(n/2) (and why didn't I think of that?), which results > in about a 2x speedup. Ah, good catch. Another lesson learned: When you optimise, make sure you have good unit test coverage that proves you didn't break anything by trying to make things faster. But Steven is right in that it's enough to run up to sqrt(n). You can improve things again by collecting not only the divisor you find but also its counterpart factor at the same time, i.e. when you find out that 2 is a divisor of n, add both 2 and n/2. Then the point to stop is really sqrt(n). Finally, sorting the resulting list will be a quick operation compared to finding the divisors. Stefan From rdmoores at gmail.com Tue Nov 9 07:47:07 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 8 Nov 2010 22:47:07 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: On Mon, Nov 8, 2010 at 21:31, Richard D. Moores wrote: > That sqrt(n) works for speeding up the finding of primes, but here we > want to use int(n/2) (and why didn't I think of that?), which results > in about a 2x speedup. See . NO! Use int(n/2)+1 . I'll correct that in and report back. Dick From rdmoores at gmail.com Tue Nov 9 08:49:44 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 8 Nov 2010 23:49:44 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: On Mon, Nov 8, 2010 at 22:47, Richard D. Moores wrote: > On Mon, Nov 8, 2010 at 21:31, Richard D. Moores wrote: > >> That sqrt(n) works for speeding up the finding of primes, but here we >> want to use int(n/2) (and why didn't I think of that?), which results >> in about a 2x speedup. See . > > NO! Use ?int(n/2)+1 . ?I'll correct that in > and report back. See But now I'll have to redo again using Stefan's ingenious suggestion. Dick From mzperx5911 at gmail.com Tue Nov 9 09:25:09 2010 From: mzperx5911 at gmail.com (First Ramses) Date: Tue, 9 Nov 2010 09:25:09 +0100 Subject: [Tutor] (no subject) Message-ID: -- mzperx -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Tue Nov 9 12:07:55 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 9 Nov 2010 03:07:55 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: On Mon, Nov 8, 2010 at 23:49, Richard D. Moores wrote: > On Mon, Nov 8, 2010 at 22:47, Richard D. Moores wrote: >> On Mon, Nov 8, 2010 at 21:31, Richard D. Moores wrote: >> >>> That sqrt(n) works for speeding up the finding of primes, but here we >>> want to use int(n/2) (and why didn't I think of that?), which results >>> in about a 2x speedup. See . >> >> NO! Use ?int(n/2)+1 . ?I'll correct that in >> and report back. > > See > > But now I'll have to redo again using Stefan's ingenious suggestion. > > Dick Here's what I wrote using Stefan's suggestion: def proper_divisors_sum(n): pd_list = [] for x in range(1, int(n**.5)+1): if n % x == 0: factor = int(x) factor2 = int(n/factor) pd_list.extend([factor, factor2]) pd_list = list(set(pd_list)) pd_list.sort() pd_list = pd_list[:-1] return sum(pd_list) Take a look at the difference in speed his suggestion made, and the larger n is, the greater the difference: At n = 100,000,000 the speed improvement over the fastest of the other 3 versions was 2579x! Employing append() instead of extend() as here: def proper_divisors_sum(n): pd_list = [] for x in range(1, int(n**.5)+1): if n % x == 0: factor = int(x) pd_list.append(factor) factor2 = int(n/factor) pd_list.append(factor2) pd_list = list(set(pd_list)) pd_list.sort() pd_list = pd_list[:-1] return sum(pd_list) improves speed by 20% or 30% for large n, but I didn't paste those results. I'll begin a new thread soon to ask for advice on optimizing a script that finds amiable pairs, and of course employs proper_divisors_sum(). Dick From stefan_ml at behnel.de Tue Nov 9 12:35:26 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 09 Nov 2010 12:35:26 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: Richard D. Moores, 09.11.2010 12:07: >>>> That sqrt(n) works for speeding up the finding of primes, but here we >>>> want to use int(n/2) (and why didn't I think of that?), which results >>>> in about a 2x speedup. See. >>> >>> NO! Use int(n/2)+1 . I'll correct that in >>> and report back. >> >> See >> >> But now I'll have to redo again using Stefan's ingenious suggestion. > > Here's what I wrote using Stefan's suggestion: > > def proper_divisors_sum(n): > pd_list = [] > for x in range(1, int(n**.5)+1): > if n % x == 0: > factor = int(x) > factor2 = int(n/factor) > pd_list.extend([factor, factor2]) > pd_list = list(set(pd_list)) > pd_list.sort() > pd_list = pd_list[:-1] > return sum(pd_list) Have a look at divmod(): http://docs.python.org/library/functions.html#divmod Note that you don't need to convert 'x' to an int. It already has that type (see the docs on range()). Also, int(n/factor) is the same as n//factor here. Stefan From jjk.saji at gmail.com Tue Nov 9 13:15:56 2010 From: jjk.saji at gmail.com (Joseph John) Date: Tue, 9 Nov 2010 16:15:56 +0400 Subject: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know Message-ID: Hi All I am trying our "Python" . My aim is to copy a file to a location and later removing the file.I had written a small script which works.It works only if I specify the source file name. I would like to make it work in a scenario in which I do not know the name of the source file(the source directory will have only one file at any time) I am posting the script which I have done,How to modify the script to copy the source file even if I do not know the name of the file my script is below ############################################### #!/usr/bin/python # This script aims to copy file from one directoy to anothe and later removing the files # This script works when I know the source file name, I want to this script to function even if I do not know the name of # the file in "/home/joseph/Projects/Training/Python/example/One/" import shutil # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/ src = "/home/joseph/Projects/Training/Python/example/One/FromOne" # dst2 = "/home/joseph/Projects/Training/Python/example/Two/" dst3 = "/home/joseph/Projects/Training/Python/example/Three/" # # #shutil.move(src, dst) shutil.copy(src,dst2) shutil.move(src,dst3) ###################################### -- Thanks Joseph John http://www.oss101.com/ From rdmoores at gmail.com Tue Nov 9 13:36:06 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 9 Nov 2010 04:36:06 -0800 Subject: [Tutor] Need help with script for finding pairs of amicable numbers Message-ID: Here's what I have so far: . My immediate question is, is there a general way to determine the multiplier of n in line 44? Of course, by trial and error I can find out pretty exactly what it should be to find a pair that I know of. But of course I want to go on and find the next pair after the last one in math world's list, (63020, 76084). (See line 9.) And of course, as a Tutoree I welcome any Tutor's advice on how to otherwise improve the script. BTW I forgot to remark out the "continue", line 53. Dick From evert.rol at gmail.com Tue Nov 9 13:38:50 2010 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 9 Nov 2010 13:38:50 +0100 Subject: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know In-Reply-To: References: Message-ID: <48C21125-6F7F-4562-91F3-8950528DB9E9@gmail.com> > Hi All > I am trying our "Python" . > My aim is to copy a file to a location and later removing the > file.I had written a small script which works.It works only if I > specify the source file name. I would like to make it work in a > scenario in which I do not know the name of the source file(the source > directory will have only one file at any time) Have a look at the os module, specifically os.listdir() The glob module could also be handy. Cheers, Evert > > I am posting the script which I have done,How to modify the script to > copy the source file even if I do not know the name of the file > my script is below > > ############################################### > #!/usr/bin/python > > # This script aims to copy file from one directoy to anothe and later > removing the files > # This script works when I know the source file name, I want to this > script to function even if I do not know the name of > # the file in "/home/joseph/Projects/Training/Python/example/One/" > > import shutil > # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/ > src = "/home/joseph/Projects/Training/Python/example/One/FromOne" > # > dst2 = "/home/joseph/Projects/Training/Python/example/Two/" > dst3 = "/home/joseph/Projects/Training/Python/example/Three/" > # > > # > #shutil.move(src, dst) > shutil.copy(src,dst2) > shutil.move(src,dst3) > > ###################################### > > > > > -- > Thanks > Joseph John > http://www.oss101.com/ > _______________________________________________ > 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 Tue Nov 9 13:43:35 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 9 Nov 2010 07:43:35 -0500 Subject: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know In-Reply-To: References: Message-ID: On Tue, Nov 9, 2010 at 7:15 AM, Joseph John wrote: > Hi All > I am trying our "Python" . > My aim is to copy a file to a location and later removing the > file.I had written a small script which works.It works only if I > specify the source file name. I would like to make it work in a > scenario in which I do not know the name of the source file(the source > directory will have only one file at any time) > > I am posting the script which I have done,How to modify the script to > copy the source file even if I do not know the name of the file > my script is below > > ############################################### > #!/usr/bin/python > > # This script aims to copy file from one directoy to anothe and later > removing the files > # This script works when I know the source file name, I want to this > script to function even if I do not know the name of > # the file in "/home/joseph/Projects/Training/Python/example/One/" > > import shutil > # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/ > src = "/home/joseph/Projects/Training/Python/example/One/FromOne" > # > dst2 = "/home/joseph/Projects/Training/Python/example/Two/" > dst3 = "/home/joseph/Projects/Training/Python/example/Three/" > # > > # > #shutil.move(src, dst) > shutil.copy(src,dst2) > shutil.move(src,dst3) > > ###################################### > > > > > -- > Thanks > Joseph John > http://www.oss101.com/ os.listdir(*path*)? Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjk.saji at gmail.com Tue Nov 9 14:25:53 2010 From: jjk.saji at gmail.com (Joseph John) Date: Tue, 9 Nov 2010 17:25:53 +0400 Subject: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know In-Reply-To: <48C21125-6F7F-4562-91F3-8950528DB9E9@gmail.com> References: <48C21125-6F7F-4562-91F3-8950528DB9E9@gmail.com> Message-ID: Thanks I was able to solve it by " dirList=os.listdir(src) for fname in dirList: print fname ffname = '/home/joseph/Projects/Training/Python/example/One/'+fname print ffname #shutil.copy(ffname,dst2) shutil.move(ffname,dst3) " On Tue, Nov 9, 2010 at 4:38 PM, Evert Rol wrote: >> Hi All >> ? I am trying our "Python" . >> ? My aim is to copy a file to a location and later removing the >> file.I had written a small script which works.It works only if I >> specify the source file name. I would like to make it work in a >> scenario in which I do not know the name of the source file(the source >> directory will have only one file at any time) > > Have a look at the os module, specifically os.listdir() > The glob module could also be handy. > > Cheers, > > ?Evert > >> >> I am posting the script which I have done,How to modify the script to >> copy the source file even if I do not know the name of the file >> my script is below >> >> ############################################### >> #!/usr/bin/python >> >> # This script aims to copy file from one directoy to anothe and later >> removing the files >> # This script works when I know the source file name, I want to this >> script to function even if I do not know the name of >> # the file in "/home/joseph/Projects/Training/Python/example/One/" >> >> import shutil >> # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/ >> src = "/home/joseph/Projects/Training/Python/example/One/FromOne" >> # >> dst2 = "/home/joseph/Projects/Training/Python/example/Two/" >> dst3 = "/home/joseph/Projects/Training/Python/example/Three/" >> # >> >> # >> #shutil.move(src, dst) >> shutil.copy(src,dst2) >> shutil.move(src,dst3) >> >> ###################################### >> >> >> >> >> -- >> Thanks >> Joseph John >> http://www.oss101.com/ >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > -- Thanks Joseph John http://www.oss101.com/ From rdmoores at gmail.com Tue Nov 9 14:41:51 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 9 Nov 2010 05:41:51 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: On Tue, Nov 9, 2010 at 03:35, Stefan Behnel wrote: > Richard D. Moores, 09.11.2010 12:07: >>>>> >>>>> That sqrt(n) works for speeding up the finding of primes, but here we >>>>> want to use int(n/2) (and why didn't I think of that?), which results >>>>> in about a 2x speedup. See. >>>> >>>> NO! Use ?int(n/2)+1 . ?I'll correct that in >>>> ?and report back. >>> >>> See >>> >>> But now I'll have to redo again using Stefan's ingenious suggestion. >> >> Here's what I wrote using Stefan's suggestion: >> >> def proper_divisors_sum(n): >> ? ? pd_list = [] >> ? ? for x in range(1, int(n**.5)+1): >> ? ? ? ? if n % x == 0: >> ? ? ? ? ? ? factor = int(x) >> ? ? ? ? ? ? factor2 = int(n/factor) >> ? ? ? ? ? ? pd_list.extend([factor, factor2]) >> ? ? pd_list = list(set(pd_list)) >> ? ? pd_list.sort() >> ? ? pd_list = pd_list[:-1] >> ? ? return sum(pd_list) > > Have a look at divmod(): > > http://docs.python.org/library/functions.html#divmod > > Note that you don't need to convert 'x' to an int. It already has that type > (see the docs on range()). Also, int(n/factor) is the same as n//factor > here. >From your suggestions I made 2 versions: def proper_divisors_sum1(n): pd_list = [] for x in range(1, int(n**.5)+1): quotient, remainder = divmod(n, x) if remainder == 0: pd_list.append(x) pd_list.append(quotient) pd_list = list(set(pd_list)) pd_list.sort() pd_list = pd_list[:-1] return sum(pd_list) def proper_divisors_sum2(n): pd_list = [] for x in range(1, int(n**.5)+1): if n % x == 0: pd_list.append(x) pd_list.append(n//x) pd_list = list(set(pd_list)) pd_list.sort() pd_list = pd_list[:-1] return sum(pd_list) The first actually slowed down what I had before, but the second made for a nice speed-up. Thanks, Stephan. Dick From evert.rol at gmail.com Tue Nov 9 14:47:48 2010 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 9 Nov 2010 14:47:48 +0100 Subject: [Tutor] How to copy file from a source, I do not know the source file name, Only path to the src directory I know In-Reply-To: References: <48C21125-6F7F-4562-91F3-8950528DB9E9@gmail.com> Message-ID: > I was able to solve it > by > " > dirList=os.listdir(src) > for fname in dirList: > print fname > ffname = '/home/joseph/Projects/Training/Python/example/One/'+fname tip: use os.path.join for concatenating paths. It's smart, and (in principle) OS-agnostic. Also, if you use 'os.listdir(src)', why not use src again when assigning ffname? Cheers, Evert > print ffname > #shutil.copy(ffname,dst2) > shutil.move(ffname,dst3) > " > > > On Tue, Nov 9, 2010 at 4:38 PM, Evert Rol wrote: >>> Hi All >>> I am trying our "Python" . >>> My aim is to copy a file to a location and later removing the >>> file.I had written a small script which works.It works only if I >>> specify the source file name. I would like to make it work in a >>> scenario in which I do not know the name of the source file(the source >>> directory will have only one file at any time) >> >> Have a look at the os module, specifically os.listdir() >> The glob module could also be handy. >> >> Cheers, >> >> Evert >> >>> >>> I am posting the script which I have done,How to modify the script to >>> copy the source file even if I do not know the name of the file >>> my script is below >>> >>> ############################################### >>> #!/usr/bin/python >>> >>> # This script aims to copy file from one directoy to anothe and later >>> removing the files >>> # This script works when I know the source file name, I want to this >>> script to function even if I do not know the name of >>> # the file in "/home/joseph/Projects/Training/Python/example/One/" >>> >>> import shutil >>> # "FromOne" is a file in /home/joseph/Projects/Training/Python/example/One/ >>> src = "/home/joseph/Projects/Training/Python/example/One/FromOne" >>> # >>> dst2 = "/home/joseph/Projects/Training/Python/example/Two/" >>> dst3 = "/home/joseph/Projects/Training/Python/example/Three/" >>> # >>> >>> # >>> #shutil.move(src, dst) >>> shutil.copy(src,dst2) >>> shutil.move(src,dst3) >>> >>> ###################################### >>> >>> >>> >>> >>> -- >>> Thanks >>> Joseph John >>> http://www.oss101.com/ >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > -- > Thanks > Joseph John > http://www.oss101.com/ From martin at linux-ip.net Tue Nov 9 14:51:51 2010 From: martin at linux-ip.net (Martin A. Brown) Date: Tue, 9 Nov 2010 14:51:51 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: Hello, : def proper_divisors_sum(n): : pd_list = [] : for x in range(1, int(n**.5)+1): : if n % x == 0: : factor = int(x) : pd_list.append(factor) : factor2 = int(n/factor) : pd_list.append(factor2) : pd_list = list(set(pd_list)) : pd_list.sort() : pd_list = pd_list[:-1] : return sum(pd_list) A few questions--noting, of course, that I'm not reading this with an eye toward performance, which it seems you are, but these occur to me: * Why use a list (pd_list = []), when you want unique divisors? Why not, pd = set() ? Then, instead of pd_list.append(factor), pd.add(factor) or something like pd.update((factor,factor2))? (See also my suggestion below.) * Also, since you are throwing away the divisor n, anyway, why not skip it from the beginning? Like this: pd_list = [1,] for x in range(2, int(n**.5)+1): * So, I'm not terribly math aware, but I don't think I have substantially changed the meaning of your program. I find breaking out the functions makes things a bit clearer to somebody who might be reading my code later. Combining these suggestions and splitting into separate functions (you don't really need to sort before summing), I end up with the below. Note, that I stuff the proper divisor 1 in the set at creation time. This is probably not worth it from an optimization perspective, but as I have learned, the only way to know is to time it (and I didn't time it). def proper_divisors_sum(n): return sum(proper_divisors(n)) def proper_divisors_sorted(n): return sorted(proper_divisors(n)) def proper_divisors(n): pd = set((1,)) for x in range(2, int(n**.5)+1): factor, mod = divmod(n,x) if mod == 0: pd.update((x,factor)) return list(pd) Have a great day, -Martin -- Martin A. Brown http://linux-ip.net/ From quasipedia at gmail.com Tue Nov 9 17:05:17 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 09 Nov 2010 17:05:17 +0100 Subject: [Tutor] Too different 2.6 vs 2.7? In-Reply-To: References: <201011082052.oA8KqmS9081669@krusty.intranet.com.mx> Message-ID: <1289318717.19082.16.camel@jabbar> On Mon, 2010-11-08 at 17:16 -0800, Terry Carroll wrote: > The only feature I'm pining for at all is the new argparse; but it > depends on your needs. Ubuntu 10.10 here (running python 2.6.6).... I use argparse without any problems: I believe the difference between 2.6 and 2.7 [I am not an expert on the subject, so correct me if I am wrong] is that with 2.7 argparse comes as *part of the standard library*, but the library per-se exists since some time, is in the repo, and can be used normally also in previous versions of python, once installed on the system. Mac. From rdmoores at gmail.com Tue Nov 9 17:17:55 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 9 Nov 2010 08:17:55 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: On Tue, Nov 9, 2010 at 05:51, Martin A. Brown wrote: > > Hello, > > ?: def proper_divisors_sum(n): > ?: ? ? pd_list = [] > ?: ? ? for x in range(1, int(n**.5)+1): > ?: ? ? ? ? if n % x == 0: > ?: ? ? ? ? ? ? factor = int(x) > ?: ? ? ? ? ? ? pd_list.append(factor) > ?: ? ? ? ? ? ? factor2 = int(n/factor) > ?: ? ? ? ? ? ? pd_list.append(factor2) > ?: ? ? pd_list = list(set(pd_list)) > ?: ? ? pd_list.sort() > ?: ? ? pd_list = pd_list[:-1] > ?: ? ? return sum(pd_list) > > A few questions--noting, of course, that I'm not reading this with > an eye toward performance, which it seems you are, but these occur > to me: > > ?* Why use a list (pd_list = []), when you want unique divisors? > ? ?Why not, pd = set() ? ?Then, instead of pd_list.append(factor), > ? ?pd.add(factor) or something like pd.update((factor,factor2))? > ? ?(See also my suggestion below.) > > ?* Also, since you are throwing away the divisor n, anyway, > ? ?why not skip it from the beginning? ?Like this: > > ? ? ?pd_list = [1,] > ? ? ?for x in range(2, int(n**.5)+1): > > ?* So, I'm not terribly math aware, but I don't think I have > ? ?substantially changed the meaning of your program. ?I find > ? ?breaking out the functions makes things a bit clearer to > ? ?somebody who might be reading my code later. > > Combining these suggestions and splitting into separate functions > (you don't really need to sort before summing), I end up with the > below. ?Note, that I stuff the proper divisor 1 in the set at > creation time. ?This is probably not worth it from an optimization > perspective, but as I have learned, the only way to know is to time > it (and I didn't time it). > > ? ? ?def proper_divisors_sum(n): > ? ? ? ? ?return sum(proper_divisors(n)) > > ? ? ?def proper_divisors_sorted(n): > ? ? ? ? ?return sorted(proper_divisors(n)) > > ? ? ?def proper_divisors(n): > ? ? ? ? ?pd = set((1,)) > ? ? ? ? ?for x in range(2, int(n**.5)+1): > ? ? ? ? ? ? ?factor, mod = divmod(n,x) > ? ? ? ? ? ? ?if mod == 0: > ? ? ? ? ? ? ? ? ?pd.update((x,factor)) > ? ? ? ? ?return list(pd) Thanks for your ideas, Martin. I adopted your idea of starting at 2, with an initial list of [1]. It resulted in a small increase in speed. And you're right, I don't need to sort. Speed is important, because the function is the heart of my amiable numbers script. Did you happen to see that post of mine? #Here's my fastest version before seeing Martin's post: def proper_divisors_sum1(n): pd_list = [] for x in range(1, int(n**.5)+1): if n % x == 0: pd_list.append(x) pd_list.append(n//x) pd_list = list(set(pd_list)) pd_list.sort() pd_list = pd_list[:-1] return sum(pd_list) #This uses several of Martin's ideas # It's now my fastest version def proper_divisors_sum2(n): pd = set((1,)) for x in range(2, int(n**.5)+1): if n % x == 0: pd.update((x, n//x)) return sum(list(pd)) Here's what I put together from all your points, except for the splitting off of several small functions: # This incorporates all of Martin's ideas # Seems that divmod() is a speed killer def proper_divisors_sum3(n): pd = set((1,)) for x in range(2, int(n**.5)+1): factor, mod = divmod(n,x) if mod == 0: pd.update((x,factor)) return sum(list(pd)) It may be that I've haven't done your suggestions justice, but that function is 76% slower than proper_divisors_sum2(). See for a speed test with n = 100,000 and 100,000 loops Thanks again, Martin. Dick From bgailer at gmail.com Tue Nov 9 18:00:56 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 09 Nov 2010 12:00:56 -0500 Subject: [Tutor] query result set In-Reply-To: <1160CE2227C1694BA39144335BC35025373CEF1D06@MAIL.pdx.odshp.com> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> <1160CE2227C1694BA39144335BC35025373CEF1D06@MAIL.pdx.odshp.com> Message-ID: <4CD97E48.9080604@gmail.com> When starting a new subject, please start with a new email. Do not "hijack" an existing one, as that causes your query to appear as part of the hijacked thread. -- Bob Gailer 919-636-4239 Chapel Hill NC From stefan_ml at behnel.de Tue Nov 9 18:36:43 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 09 Nov 2010 18:36:43 +0100 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: <20101109040128.GA23247@cybersource.com.au> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> <20101109040128.GA23247@cybersource.com.au> Message-ID: Steven D'Aprano, 09.11.2010 05:01: > http://pypi.python.org/pypi/obfuscate Hmm - why is the Windows installer on that page called "linux-i686"? Stefan From eike.welk at gmx.net Tue Nov 9 19:37:28 2010 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 9 Nov 2010 19:37:28 +0100 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> <20101109040128.GA23247@cybersource.com.au> Message-ID: <201011091937.28881.eike.welk@gmx.net> On Tuesday 09.11.2010 18:36:43 Stefan Behnel wrote: > Steven D'Aprano, 09.11.2010 05:01: > > http://pypi.python.org/pypi/obfuscate > > Hmm - why is the Windows installer on that page called "linux-i686"? It was probably created on Linux. Python's Distutils create installers for Windows even on Linux. They get file names that contain "linux-". You must rename them, otherwise your users get confused. I did never try them, because I have no Windows computer. Do these Windows installers work when they are created on Linux? Eike. From steve at pearwood.info Tue Nov 9 21:54:24 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Nov 2010 07:54:24 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> Message-ID: <4CD9B500.4090605@pearwood.info> Richard D. Moores wrote: > See for a speed test with n = > 100,000 and 100,000 loops As a general rule, you shouldn't try to roll your own speed tests. There are various subtleties that can throw your results right out. Timing small code snippets on modern multi-tasking computers is fraught with difficulties. Fortunately Python comes with that battery already included: the timeit module. You can use it from the shell like this: python -m timeit -s "setup code goes here" "test code goes here" At the Python interactive interpreter, the most useful pattern I've found is: from timeit import Timer t = Timer("proper_divisors(n)", "from __main__ import proper_divisors; n = 100000") min(t.repeat(repeat=5, number=100000)) Or if you're happy with Python's defaults, that last line can be just: min(t.repeat()) -- Steven From steve at pearwood.info Tue Nov 9 22:29:51 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Nov 2010 08:29:51 +1100 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: <201011091937.28881.eike.welk@gmx.net> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> <20101109040128.GA23247@cybersource.com.au> <201011091937.28881.eike.welk@gmx.net> Message-ID: <4CD9BD4F.3000309@pearwood.info> Eike Welk wrote: > On Tuesday 09.11.2010 18:36:43 Stefan Behnel wrote: >> Steven D'Aprano, 09.11.2010 05:01: >>> http://pypi.python.org/pypi/obfuscate >> Hmm - why is the Windows installer on that page called "linux-i686"? > > It was probably created on Linux. That would be it. > Python's Distutils create installers for > Windows even on Linux. They get file names that contain "linux-". You must > rename them, otherwise your users get confused. I didn't realise that. > I did never try them, because I have no Windows computer. Do these Windows > installers work when they are created on Linux? I'm pretty sure I tried it, once, but I might be confabulating. -- Steven From fomcl at yahoo.com Tue Nov 9 22:58:22 2010 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 9 Nov 2010 13:58:22 -0800 (PST) Subject: [Tutor] List comprehension question In-Reply-To: <4CD9B500.4090605@pearwood.info> References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> Message-ID: <968733.36678.qm@web110711.mail.gq1.yahoo.com> For larger blocks of code, cProfile may also be useful for speed tests. Cheers!! 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: Steven D'Aprano To: tutor at python.org Sent: Tue, November 9, 2010 9:54:24 PM Subject: Re: [Tutor] List comprehension question Richard D. Moores wrote: > See for a speed test with n = > 100,000 and 100,000 loops As a general rule, you shouldn't try to roll your own speed tests. There are various subtleties that can throw your results right out. Timing small code snippets on modern multi-tasking computers is fraught with difficulties. Fortunately Python comes with that battery already included: the timeit module. You can use it from the shell like this: python -m timeit -s "setup code goes here" "test code goes here" At the Python interactive interpreter, the most useful pattern I've found is: from timeit import Timer t = Timer("proper_divisors(n)", "from __main__ import proper_divisors; n = 100000") min(t.repeat(repeat=5, number=100000)) Or if you're happy with Python's defaults, that last line can be just: min(t.repeat()) -- 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 rdmoores at gmail.com Tue Nov 9 23:09:31 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 9 Nov 2010 14:09:31 -0800 Subject: [Tutor] List comprehension question In-Reply-To: <4CD9B500.4090605@pearwood.info> References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> Message-ID: On Tue, Nov 9, 2010 at 12:54, Steven D'Aprano wrote: > Richard D. Moores wrote: > >> See for a speed test with n = >> 100,000 and 100,000 loops > > As a general rule, you shouldn't try to roll your own speed tests. There are > various subtleties that can throw your results right out. Timing small code > snippets on modern multi-tasking computers is fraught with difficulties. Yes, but I thought that if I ran the tests the way I did, several times and then reversing the order of the functions, and seeing that the results were very similar, I could be pretty sure of my findings. Could you point out where taking even that amount of care could lead me astray? > > Fortunately Python comes with that battery already included: the timeit > module. You can use it from the shell like this: > > python -m timeit -s "setup code goes here" "test code goes here" > > At the Python interactive interpreter, the most useful pattern I've found > is: > > from timeit import Timer > t = Timer("proper_divisors(n)", > ? ?"from __main__ import proper_divisors; n = 100000") > min(t.repeat(repeat=5, number=100000)) > > > Or if you're happy with Python's defaults, that last line can be just: > > min(t.repeat()) That's terrific, Stephen! I've used timeit before, but only for really small snippets. With your encouragement I experimented and after some trial and error, I came up with this method for using your template: 1. Don't try to dump all you (Steven) wrote in at once. 2. First, do the import. >>> from timeit import Timer 3. Then dump in the function (steps 2 and 3 can be reversed, I think) 4. then >>>t = Timer("proper_divisors(n)", "from __main__ import proper_divisors; n = 100000") 5. Finally, >>>min(t.repeat(repeat=5, number=100000)) 6. Wait for the result. (please tell me if I could cut down the number of steps by combining a couple of them.) I was pleased that for def proper_divisors(n): pd = set((1,)) for x in range(2, int(n**.5)+1): if n % x == 0: pd.update((x, n//x)) return sum(list(pd)) I got 8.312734300029753 and for def proper_divisors(n): pd = set((1,)) for x in range(2, int(n**.5)+1): factor, mod = divmod(n,x) if mod == 0: pd.update((x,factor)) return sum(list(pd)) got 14.859849506012608 That's about the same speed ratio (1.79) that I reported here earlier, I believe. I quote: "It may be that I haven't done your suggestions justice, but that function is 76% slower than proper_divisors_sum2()" Question: When I dump in more that one line of any code (properly indented), after running it once, I've never known how to run it again without a redump. The up arrow just gets me one line at a time. So, how to do it? Thanks, Dick From alan.gauld at btinternet.com Wed Nov 10 01:13:11 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Nov 2010 00:13:11 -0000 Subject: [Tutor] List comprehension question References: <4CD7E26C.3010908@pearwood.info><4CD9B500.4090605@pearwood.info> Message-ID: "Richard D. Moores" wrote > Question: When I dump in more that one line of any code (properly > indented), after running it once, I've never known how to run it > again > without a redump. The up arrow just gets me one line at a time. So, > how to do it? It depends on your IDE. On IDLE I think its Alt-P and Alt-N to cycle through previous and next lines of history. On Pythonwin its Ctrl-Up/Ctrl-Down IDLE and Pythonwin put in whole blocks. The XP CMD prompt uses up/down keys but only does single lines A La Mode had some neat cut n paste features for correctly pasting in blocks of code evern from other places - like email.... Not sure about any of the others. Alan FG. From emile at fenx.com Wed Nov 10 01:20:55 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Nov 2010 16:20:55 -0800 Subject: [Tutor] Columnar Transposition Cipher question In-Reply-To: <4CD9BD4F.3000309@pearwood.info> References: <20101108152844.25348c1439fcwnn4@webaccess.umail.ucsb.edu> <20101109040128.GA23247@cybersource.com.au> <201011091937.28881.eike.welk@gmx.net> <4CD9BD4F.3000309@pearwood.info> Message-ID: On 11/9/2010 1:29 PM Steven D'Aprano said... > I'm pretty sure I tried it, once, but I might be confabulating. Cool -- I learned a new word today! I had to look it up as I thought you were profabulating... :) Emile From smiles at worksmail.net Wed Nov 10 03:29:58 2010 From: smiles at worksmail.net (C or L Smith) Date: Wed, 10 Nov 2010 08:14:58 +0545 Subject: [Tutor] List comprehension question References: Message-ID: >> 1. Re: List comprehension question (Richard D. Moores) >>> ?: def proper_divisors_sum(n): >>> A few questions--noting, of course, that I'm not reading this with >>> an eye toward performance, which it seems you are, but these occur >>> to me: Tim Peters had a beautiful little version of divisors at http://stackoverflow.com/questions/1010381/python-factorization A modified version of this is part of the python CAS system sympy (sympy.org). >From sympy you simply do: >>> from sympy import divisors >>> list(divisors(256)) [1, 2, 4, 8, 16, 32, 64, 128, 256] So your proper divisors would just be sum(divisors(n)) - n. The divisors function there is in the ntheory/factor_.py file. /c From rdmoores at gmail.com Wed Nov 10 08:24:22 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 9 Nov 2010 23:24:22 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: On Tue, Nov 9, 2010 at 18:29, C or L Smith wrote: > >From sympy you simply do: > >>>> from sympy import divisors >>>> list(divisors(256)) > [1, 2, 4, 8, 16, 32, 64, 128, 256] > > So your proper divisors would just be sum(divisors(n)) - n. > The divisors function there is in the ntheory/factor_.py file. Thanks for letting me know about this. def proper_divisors_sum(n): return sum(list(divisors(n))) - n Using Steven's suggested speed test this gets 6.2404818210135886 My up-to-now fastest version, def proper_divisors_sum(n): pd = set((1,)) for x in range(2, int(n**.5)+1): if n % x == 0: pd.update((x, n//x)) return sum(list(pd)) gets 6.1753780857622473 So they're about even. Dick From stefan_ml at behnel.de Wed Nov 10 08:38:23 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 10 Nov 2010 08:38:23 +0100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: Richard D. Moores, 10.11.2010 08:24: > def proper_divisors_sum(n): > pd = set((1,)) > for x in range(2, int(n**.5)+1): > if n % x == 0: > pd.update((x, n//x)) > return sum(list(pd)) You keep using redundant operations. What "sum(list(s))" does, for s being a set, is: 1) create a list of the length of s 2) iterate over s, copying elements into the list 3) sum up the values in the list What makes you think that the intermediate list is needed? $ python2.6 -m timeit -s 's = set(range(1000))' 'sum(list(s))' 10000 loops, best of 3: 20.7 usec per loop $ python2.6 -m timeit -s 's = set(range(1000))' 'sum(s)' 100000 loops, best of 3: 14.4 usec per loop Stefan From marupalli.charan at gmail.com Wed Nov 10 13:28:27 2010 From: marupalli.charan at gmail.com (marupalli charan) Date: Wed, 10 Nov 2010 17:58:27 +0530 Subject: [Tutor] Tutor Digest, Vol 81, Issue 39 In-Reply-To: References: Message-ID: Thanks, but first one not working!!! On 11/10/10, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: List comprehension question (Richard D. Moores) > 2. Re: query result set (bob gailer) > 3. Re: Columnar Transposition Cipher question (Stefan Behnel) > 4. Re: Columnar Transposition Cipher question (Eike Welk) > 5. Re: List comprehension question (Steven D'Aprano) > 6. Re: Columnar Transposition Cipher question (Steven D'Aprano) > 7. Re: List comprehension question (Albert-Jan Roskam) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Tue, 9 Nov 2010 08:17:55 -0800 > From: "Richard D. Moores" > To: "Martin A. Brown" > Cc: tutor at python.org > Subject: Re: [Tutor] List comprehension question > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Tue, Nov 9, 2010 at 05:51, Martin A. Brown wrote: >> >> Hello, >> >> ?: def proper_divisors_sum(n): >> ?: ? ? pd_list = [] >> ?: ? ? for x in range(1, int(n**.5)+1): >> ?: ? ? ? ? if n % x == 0: >> ?: ? ? ? ? ? ? factor = int(x) >> ?: ? ? ? ? ? ? pd_list.append(factor) >> ?: ? ? ? ? ? ? factor2 = int(n/factor) >> ?: ? ? ? ? ? ? pd_list.append(factor2) >> ?: ? ? pd_list = list(set(pd_list)) >> ?: ? ? pd_list.sort() >> ?: ? ? pd_list = pd_list[:-1] >> ?: ? ? return sum(pd_list) >> >> A few questions--noting, of course, that I'm not reading this with >> an eye toward performance, which it seems you are, but these occur >> to me: >> >> ?* Why use a list (pd_list = []), when you want unique divisors? >> ? ?Why not, pd = set() ? ?Then, instead of pd_list.append(factor), >> ? ?pd.add(factor) or something like pd.update((factor,factor2))? >> ? ?(See also my suggestion below.) >> >> ?* Also, since you are throwing away the divisor n, anyway, >> ? ?why not skip it from the beginning? ?Like this: >> >> ? ? ?pd_list = [1,] >> ? ? ?for x in range(2, int(n**.5)+1): >> >> ?* So, I'm not terribly math aware, but I don't think I have >> ? ?substantially changed the meaning of your program. ?I find >> ? ?breaking out the functions makes things a bit clearer to >> ? ?somebody who might be reading my code later. >> >> Combining these suggestions and splitting into separate functions >> (you don't really need to sort before summing), I end up with the >> below. ?Note, that I stuff the proper divisor 1 in the set at >> creation time. ?This is probably not worth it from an optimization >> perspective, but as I have learned, the only way to know is to time >> it (and I didn't time it). >> >> ? ? ?def proper_divisors_sum(n): >> ? ? ? ? ?return sum(proper_divisors(n)) >> >> ? ? ?def proper_divisors_sorted(n): >> ? ? ? ? ?return sorted(proper_divisors(n)) >> >> ? ? ?def proper_divisors(n): >> ? ? ? ? ?pd = set((1,)) >> ? ? ? ? ?for x in range(2, int(n**.5)+1): >> ? ? ? ? ? ? ?factor, mod = divmod(n,x) >> ? ? ? ? ? ? ?if mod == 0: >> ? ? ? ? ? ? ? ? ?pd.update((x,factor)) >> ? ? ? ? ?return list(pd) > > Thanks for your ideas, Martin. I adopted your idea of starting at 2, > with an initial list of [1]. It resulted in a small increase in > speed. And you're right, I don't need to sort. > > Speed is important, because the function is the heart of my amiable > numbers script. Did you happen to see that post of mine? > > #Here's my fastest version before seeing Martin's post: > def proper_divisors_sum1(n): > pd_list = [] > for x in range(1, int(n**.5)+1): > if n % x == 0: > pd_list.append(x) > pd_list.append(n//x) > pd_list = list(set(pd_list)) > pd_list.sort() > pd_list = pd_list[:-1] > return sum(pd_list) > > #This uses several of Martin's ideas > # It's now my fastest version > def proper_divisors_sum2(n): > pd = set((1,)) > for x in range(2, int(n**.5)+1): > if n % x == 0: > pd.update((x, n//x)) > return sum(list(pd)) > > Here's what I put together from all your points, except for the > splitting off of several small functions: > > # This incorporates all of Martin's ideas > # Seems that divmod() is a speed killer > def proper_divisors_sum3(n): > pd = set((1,)) > for x in range(2, int(n**.5)+1): > factor, mod = divmod(n,x) > if mod == 0: > pd.update((x,factor)) > return sum(list(pd)) > > It may be that I've haven't done your suggestions justice, but that > function is 76% slower than proper_divisors_sum2(). > > See for a speed test with n = > 100,000 and 100,000 loops > > Thanks again, Martin. > > Dick > > > ------------------------------ > > Message: 2 > Date: Tue, 09 Nov 2010 12:00:56 -0500 > From: bob gailer > To: tutor at python.org > Subject: Re: [Tutor] query result set > Message-ID: <4CD97E48.9080604 at gmail.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > When starting a new subject, please start with a new email. Do not > "hijack" an existing one, as that causes your query to appear as part of > the hijacked thread. > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > > ------------------------------ > > Message: 3 > Date: Tue, 09 Nov 2010 18:36:43 +0100 > From: Stefan Behnel > To: tutor at python.org > Subject: Re: [Tutor] Columnar Transposition Cipher question > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > Steven D'Aprano, 09.11.2010 05:01: >> http://pypi.python.org/pypi/obfuscate > > Hmm - why is the Windows installer on that page called "linux-i686"? > > Stefan > > > > ------------------------------ > > Message: 4 > Date: Tue, 9 Nov 2010 19:37:28 +0100 > From: Eike Welk > To: tutor at python.org > Subject: Re: [Tutor] Columnar Transposition Cipher question > Message-ID: <201011091937.28881.eike.welk at gmx.net> > Content-Type: Text/Plain; charset="iso-8859-1" > > On Tuesday 09.11.2010 18:36:43 Stefan Behnel wrote: >> Steven D'Aprano, 09.11.2010 05:01: >> > http://pypi.python.org/pypi/obfuscate >> >> Hmm - why is the Windows installer on that page called "linux-i686"? > > It was probably created on Linux. Python's Distutils create installers for > Windows even on Linux. They get file names that contain "linux-". You must > rename them, otherwise your users get confused. > > I did never try them, because I have no Windows computer. Do these Windows > installers work when they are created on Linux? > > > Eike. > > > ------------------------------ > > Message: 5 > Date: Wed, 10 Nov 2010 07:54:24 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] List comprehension question > Message-ID: <4CD9B500.4090605 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > Richard D. Moores wrote: > >> See for a speed test with n = >> 100,000 and 100,000 loops > > As a general rule, you shouldn't try to roll your own speed tests. There > are various subtleties that can throw your results right out. Timing > small code snippets on modern multi-tasking computers is fraught with > difficulties. > > Fortunately Python comes with that battery already included: the timeit > module. You can use it from the shell like this: > > python -m timeit -s "setup code goes here" "test code goes here" > > At the Python interactive interpreter, the most useful pattern I've > found is: > > from timeit import Timer > t = Timer("proper_divisors(n)", > "from __main__ import proper_divisors; n = 100000") > min(t.repeat(repeat=5, number=100000)) > > > Or if you're happy with Python's defaults, that last line can be just: > > min(t.repeat()) > > > > -- > Steven > > > ------------------------------ > > Message: 6 > Date: Wed, 10 Nov 2010 08:29:51 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Columnar Transposition Cipher question > Message-ID: <4CD9BD4F.3000309 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Eike Welk wrote: >> On Tuesday 09.11.2010 18:36:43 Stefan Behnel wrote: >>> Steven D'Aprano, 09.11.2010 05:01: >>>> http://pypi.python.org/pypi/obfuscate >>> Hmm - why is the Windows installer on that page called "linux-i686"? >> >> It was probably created on Linux. > > That would be it. > > > Python's Distutils create installers for >> Windows even on Linux. They get file names that contain "linux-". You must >> >> rename them, otherwise your users get confused. > > I didn't realise that. > >> I did never try them, because I have no Windows computer. Do these Windows >> >> installers work when they are created on Linux? > > I'm pretty sure I tried it, once, but I might be confabulating. > > > > -- > Steven > > > > ------------------------------ > > Message: 7 > Date: Tue, 9 Nov 2010 13:58:22 -0800 (PST) > From: Albert-Jan Roskam > To: Steven D'Aprano , tutor at python.org > Subject: Re: [Tutor] List comprehension question > Message-ID: <968733.36678.qm at web110711.mail.gq1.yahoo.com> > Content-Type: text/plain; charset="us-ascii" > > For larger blocks of code, cProfile may also be useful for speed tests. > > Cheers!! > 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: Steven D'Aprano > To: tutor at python.org > Sent: Tue, November 9, 2010 9:54:24 PM > Subject: Re: [Tutor] List comprehension question > > Richard D. Moores wrote: > >> See for a speed test with n = >> 100,000 and 100,000 loops > > As a general rule, you shouldn't try to roll your own speed tests. There are > various subtleties that can throw your results right out. Timing small code > snippets on modern multi-tasking computers is fraught with difficulties. > > Fortunately Python comes with that battery already included: the timeit > module. > You can use it from the shell like this: > > python -m timeit -s "setup code goes here" "test code goes here" > > At the Python interactive interpreter, the most useful pattern I've found > is: > > from timeit import Timer > t = Timer("proper_divisors(n)", > "from __main__ import proper_divisors; n = 100000") > min(t.repeat(repeat=5, number=100000)) > > > Or if you're happy with Python's defaults, that last line can be just: > > min(t.repeat()) > > > > -- 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: > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 81, Issue 39 > ************************************* > From jeffh at pona.net Wed Nov 10 19:21:45 2010 From: jeffh at pona.net (Jeff Honey) Date: Wed, 10 Nov 2010 13:21:45 -0500 Subject: [Tutor] variables question. Message-ID: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> I have a question about where variables are exposed in python. I have a monolothic script with a number of functions defined, can those functions share variables? can I instantiate them outside the function of where they are needed? do they need to be wrapped in quotes, ever? For example: blah = 123 foo = 'somestring' def function(foo): code that needs foo anotherfunction(blah) def anotherfunction(blah): code that needs blah code that uses foo ....how about this: def function(blah, foo): anotherfunc(blah) anotherfunc(foo) ...what about my python being called from some parent script (something OTHER than python) that instantiates blah and foo FOR me? Can I just plug those into my code like I would normally? I guess this is more about HOW and WHERE I can make variables available for use. -- ?????????????????? ? kyoboku kazeoshi ? ?????????????????? From ajarncolin at gmail.com Wed Nov 10 09:55:19 2010 From: ajarncolin at gmail.com (col speed) Date: Wed, 10 Nov 2010 15:55:19 +0700 Subject: [Tutor] Need help with script for finding pairs of amicable numbers Message-ID: > > ------------------------------ > > Message: 2 > Date: Tue, 09 Nov 2010 12:35:26 +0100 > From: Stefan Behnel > To: tutor at python.org > Subject: Re: [Tutor] List comprehension question > Message-ID: > Content-Type: text/plain; charset=UTF-8; format=flowed > > Richard D. Moores, 09.11.2010 12:07: > >>>> That sqrt(n) works for speeding up the finding of primes, but here we > >>>> want to use int(n/2) (and why didn't I think of that?), which results > >>>> in about a 2x speedup. See. > >>> > >>> NO! Use int(n/2)+1 . I'll correct that in > >>> and report back. > >> > >> See > >> > >> But now I'll have to redo again using Stefan's ingenious suggestion. > > > > Here's what I wrote using Stefan's suggestion: > > > > def proper_divisors_sum(n): > > pd_list = [] > > for x in range(1, int(n**.5)+1): > > if n % x == 0: > > factor = int(x) > > factor2 = int(n/factor) > > pd_list.extend([factor, factor2]) > > pd_list = list(set(pd_list)) > > pd_list.sort() > > pd_list = pd_list[:-1] > > return sum(pd_list) > > > > > > --------------------- > Just a thought, but maybe getting the sums using prime factors would be a > bit faster? Get the prime factors with their powers. Add 1 to the power and subtract 1 from that. Then divide that by the factor minus 1. multiply that by the next factor. An example is easier: Take 1800, it's prime factors are - 2**3, 3**2, 5**2. So we do: ((2**4-1)/1) * ((3**3-1)/2) * ((5**3-1)/4) = (15*26*124)/8 = 1800 I have a couple of programmes ( stolen from the internet) that work out the prime factors quite quickly, if you are interested. Regards Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Nov 10 10:30:12 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Nov 2010 20:30:12 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: Message-ID: <4CDA6624.1070302@pearwood.info> Richard D. Moores wrote: > def proper_divisors_sum(n): > return sum(list(divisors(n))) - n There's no need to call list first. sum() will happily operate on any sort of iterable -- lists, sums, iterators, generators, range objects. Anything except strings, which would be pointless even if you could do it, which you can't, but even so you can fool sum() to work with strings with a bit of effort. > Using Steven's suggested speed test > this gets 6.2404818210135886 > > My up-to-now fastest version, [...] > gets 6.1753780857622473 > > So they're about even. I'd say that the difference is probably statistically insignificant. Even if it's consistent on your PC, on another PC with a slightly different processor, slightly different memory, or a different operating system, it could very well go the other way. In any case, since those times are ~6 seconds per 100,000 loops, the real difference is only 60 microseconds -- completely trivial unless you're doing some *serious* number crunching. P.S. don't take that as a put down -- you should be pleased that your code is around as fast as Tim Peter's code :) -- Steven From danielle.davout at gmail.com Wed Nov 10 20:01:20 2010 From: danielle.davout at gmail.com (danielle davout) Date: Thu, 11 Nov 2010 02:01:20 +0700 Subject: [Tutor] unicode nightmare Message-ID: Hi, I really badly need any start of explanation .. Please help me ! I have got a list of 64 generators from which I generate files. 58 give what I expected 1 is getting me mad, not the first, not the last the fifth... I simplify it to v = u'\u0eb4' X = (1,) gen = ((v ,v) for x in X for y in X) What can be so wrong in this line, around it to give the 1lined file ?:? where ? "is" not u'\u0eb4' but u'\u0ec4' though a direct printing looks OK To write the file corresponding to my nth generator of my list h I use def ecrire(n): f= codecs.open("G"+str(n),"w","utf8") for x, tx in h[n]: f.write((x + U":"+ tx)) f.write('\n') f.close() But In its non simplified form h.append( (x + v + y ,tr[x]+ tr[v]+ tr[y]) for x in CC for y in OFC) ) before I have a chance to write anything in the file G5 I have got the KeyError: u'\u0ec4' yes tr is a dictionary that doesn't have u'\u0ec4' as a key but tr[v] is well definied ... (# /usr/lib/python2.5/encodings/utf_8.pyc matches /usr/lib/python2.5/encodings/utf_8.py import encodings.utf_8 # precompiled from /usr/lib/python2.5/encodings/utf_8.pyc Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14) [GCC 4.3.2] on linux2) From steve at pearwood.info Wed Nov 10 11:35:42 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Nov 2010 21:35:42 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> Message-ID: <4CDA757E.5000500@pearwood.info> Richard D. Moores wrote: > On Tue, Nov 9, 2010 at 12:54, Steven D'Aprano wrote: >> Richard D. Moores wrote: >> >>> See for a speed test with n = >>> 100,000 and 100,000 loops >> As a general rule, you shouldn't try to roll your own speed tests. There are >> various subtleties that can throw your results right out. Timing small code >> snippets on modern multi-tasking computers is fraught with difficulties. > > Yes, but I thought that if I ran the tests the way I did, several > times and then reversing the order of the functions, and seeing that > the results were very similar, I could be pretty sure of my findings. > Could you point out where taking even that amount of care could lead > me astray? Well, the biggest problem is that you're re-inventing the wheel. But in truth, what you did was not terrible, particularly if you're using Python 3 where range() is quite lightweight rather than a heavy operation that creates a big list. There are various traps when timing code: * There are commonly two functions you use for getting the time: time.time() and time.clock(). On Windows, the best one to use is clock(), but on other operating systems, you should probably use time(). The timeit module automatically chooses the right one for you. * Comparing apples and oranges. There's not a lot that timeit can do there, since it requires you *understand* what the code is that you are timing, but it helps by allowing you to split initialisation away from the code you are timing. * Timing too much. One trap is to do this: t = time.time() for _ in range(1000000): do_something() t = time.time() - t This is especially bad in Python 2.x! The problem is that you are including the time it takes to create a list of one million integers in your timing code. That's like starting the stop watch at a race while the athletes are still in the changing rooms, getting dressed, and yet you'd be amazed how often people do it! If the time taken by each call to do_something() is very large, then the extra time will be negligible, but if do_something is a fast snippet, it might take you nearly as long to build the list as it does to run the code you're trying to time! timeit ensures that as little as possible overhead is included in the execution being timed. * Forgetting that computers are multi-tasking machines these days. At every instant, the operating system is giving tiny time-slices to your program and potentially dozens of others. If you're busy loading a dozen web pages, playing a DVD, compiling a large program and trying to time a code snippet, it will be obvious that everything is going to be running slow. But if you time something *once*, what's not obvious is that just by chance you might get a number that is much slower than normal because the OS *just happened* to call your anti-virus during the test. timeit fights against that by running your code in a loop, and then working out the average time per loop, *and* then repeating the loop multiple times (three by default) and picking the lowest figure. Higher figures are slower due to external factors. * Forgetting your CPU cache effects. Modern CPUs do all sorts of amazing wizardry to make code run fast. Sometimes slow, but hopefully more often fast. The first time you run a piece of code, chances are it will be slower than normal, because the hardware caches will have other stuff in them. But the second time, the code and data will already be lined up in the cache and pipelines ready to go. This is why if you time something a dozen times, the *first* time could be two or three times slower than the rest. I've probably forgotten some... but anyway, the important thing is that there's lots of subtleties to timing code, and Tim Peters has already thought of them so you don't have to :) -- Steven From alan.gauld at btinternet.com Wed Nov 10 21:49:25 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Nov 2010 20:49:25 -0000 Subject: [Tutor] variables question. References: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> Message-ID: "Jeff Honey" wrote > I have a question about where variables are exposed in python. Take a look at the namespaces topic in my tutor for more details but... > I have a monolothic script with a number of functions defined, > can those functions share variables? Yes but its usually bad practice. Python considers module level variables to be "global". global vars can be read inside a functon within the same module. global vars can be changed inside a function in the same module provided they are declared as global within the function: foo = 42 def f(): global foo # use the global var foo = 66 return foo print foo print f() print foo > can I instantiate them outside the function of where they are > needed? Yes, see foo above > do they need to be wrapped in quotes, ever? For example: > > blah = 123 blah refers to an integer > foo = 'somestring' foo refers to a string. literal strings need quotes bar = raw_uinput('?') # bar refers to a strintg input by the user > def function(foo): > code that needs foo > anotherfunction(blah) No problem > def anotherfunction(blah): > code that needs blah > code that uses foo This needs a global foo line added at the top. > def function(blah, foo): > anotherfunc(blah) > anotherfunc(foo) No problem. blah and foo are local variables inside function(). They are passed as arguments to anotherfunc() whioch weill assign the objects to their parameters and treat as local variables within anotherfunc() > ..what about my python being called from some parent script > (something OTHER than python) Thats possible but trickier > that instantiates blah and foo FOR me? As is this. But bopth are easier if its another Python script. > Can I just plug those into my code like I would normally? No. > I guess this is more about HOW and WHERE I can > make variables available for use. See my tutorial topic... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 10 21:50:54 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Nov 2010 20:50:54 -0000 Subject: [Tutor] Tutor Digest, Vol 81, Issue 39 References: Message-ID: "marupalli charan" wrote > Thanks, but first one not working!!! First one of what? Please edit the message to pprovide some context and pay attention to the instruxctions that you so helpfully posted: >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: >> >> 1. Re: List comprehension question (Richard D. Moores) >> 2. Re: query result set (bob gailer) >> 3. Re: Columnar Transposition Cipher question (Stefan Behnel) >> 4. Re: Columnar Transposition Cipher question (Eike Welk) >> 5. Re: List comprehension question (Steven D'Aprano) >> 6. Re: Columnar Transposition Cipher question (Steven D'Aprano) >> 7. Re: List comprehension question (Albert-Jan Roskam) >> >> >> ---------------------------------------------------------------------- >> >> Message: 1 >> Date: Tue, 9 Nov 2010 08:17:55 -0800 >> From: "Richard D. Moores" >> To: "Martin A. Brown" >> Cc: tutor at python.org >> Subject: Re: [Tutor] List comprehension question >> Message-ID: >> >> Content-Type: text/plain; charset=UTF-8 >> >> On Tue, Nov 9, 2010 at 05:51, Martin A. Brown >> wrote: >>> >>> Hello, >>> >>> ?: def proper_divisors_sum(n): >>> ?: ? ? pd_list = [] >>> ?: ? ? for x in range(1, int(n**.5)+1): >>> ?: ? ? ? ? if n % x == 0: >>> ?: ? ? ? ? ? ? factor = int(x) >>> ?: ? ? ? ? ? ? pd_list.append(factor) >>> ?: ? ? ? ? ? ? factor2 = int(n/factor) >>> ?: ? ? ? ? ? ? pd_list.append(factor2) >>> ?: ? ? pd_list = list(set(pd_list)) >>> ?: ? ? pd_list.sort() >>> ?: ? ? pd_list = pd_list[:-1] >>> ?: ? ? return sum(pd_list) >>> >>> A few questions--noting, of course, that I'm not reading this with >>> an eye toward performance, which it seems you are, but these occur >>> to me: >>> >>> ?* Why use a list (pd_list = []), when you want unique divisors? >>> ? ?Why not, pd = set() ? ?Then, instead of pd_list.append(factor), >>> ? ?pd.add(factor) or something like pd.update((factor,factor2))? >>> ? ?(See also my suggestion below.) >>> >>> ?* Also, since you are throwing away the divisor n, anyway, >>> ? ?why not skip it from the beginning? ?Like this: >>> >>> ? ? ?pd_list = [1,] >>> ? ? ?for x in range(2, int(n**.5)+1): >>> >>> ?* So, I'm not terribly math aware, but I don't think I have >>> ? ?substantially changed the meaning of your program. ?I find >>> ? ?breaking out the functions makes things a bit clearer to >>> ? ?somebody who might be reading my code later. >>> >>> Combining these suggestions and splitting into separate functions >>> (you don't really need to sort before summing), I end up with the >>> below. ?Note, that I stuff the proper divisor 1 in the set at >>> creation time. ?This is probably not worth it from an optimization >>> perspective, but as I have learned, the only way to know is to >>> time >>> it (and I didn't time it). >>> >>> ? ? ?def proper_divisors_sum(n): >>> ? ? ? ? ?return sum(proper_divisors(n)) >>> >>> ? ? ?def proper_divisors_sorted(n): >>> ? ? ? ? ?return sorted(proper_divisors(n)) >>> >>> ? ? ?def proper_divisors(n): >>> ? ? ? ? ?pd = set((1,)) >>> ? ? ? ? ?for x in range(2, int(n**.5)+1): >>> ? ? ? ? ? ? ?factor, mod = divmod(n,x) >>> ? ? ? ? ? ? ?if mod == 0: >>> ? ? ? ? ? ? ? ? ?pd.update((x,factor)) >>> ? ? ? ? ?return list(pd) >> >> Thanks for your ideas, Martin. I adopted your idea of starting at >> 2, >> with an initial list of [1]. It resulted in a small increase in >> speed. And you're right, I don't need to sort. >> >> Speed is important, because the function is the heart of my amiable >> numbers script. Did you happen to see that post of mine? >> >> #Here's my fastest version before seeing Martin's post: >> def proper_divisors_sum1(n): >> pd_list = [] >> for x in range(1, int(n**.5)+1): >> if n % x == 0: >> pd_list.append(x) >> pd_list.append(n//x) >> pd_list = list(set(pd_list)) >> pd_list.sort() >> pd_list = pd_list[:-1] >> return sum(pd_list) >> >> #This uses several of Martin's ideas >> # It's now my fastest version >> def proper_divisors_sum2(n): >> pd = set((1,)) >> for x in range(2, int(n**.5)+1): >> if n % x == 0: >> pd.update((x, n//x)) >> return sum(list(pd)) >> >> Here's what I put together from all your points, except for the >> splitting off of several small functions: >> >> # This incorporates all of Martin's ideas >> # Seems that divmod() is a speed killer >> def proper_divisors_sum3(n): >> pd = set((1,)) >> for x in range(2, int(n**.5)+1): >> factor, mod = divmod(n,x) >> if mod == 0: >> pd.update((x,factor)) >> return sum(list(pd)) >> >> It may be that I've haven't done your suggestions justice, but that >> function is 76% slower than proper_divisors_sum2(). >> >> See for a speed test with n >> = >> 100,000 and 100,000 loops >> >> Thanks again, Martin. >> >> Dick >> >> >> ------------------------------ >> >> Message: 2 >> Date: Tue, 09 Nov 2010 12:00:56 -0500 >> From: bob gailer >> To: tutor at python.org >> Subject: Re: [Tutor] query result set >> Message-ID: <4CD97E48.9080604 at gmail.com> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> When starting a new subject, please start with a new email. Do not >> "hijack" an existing one, as that causes your query to appear as >> part of >> the hijacked thread. >> >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> >> >> ------------------------------ >> >> Message: 3 >> Date: Tue, 09 Nov 2010 18:36:43 +0100 >> From: Stefan Behnel >> To: tutor at python.org >> Subject: Re: [Tutor] Columnar Transposition Cipher question >> Message-ID: >> Content-Type: text/plain; charset=UTF-8; format=flowed >> >> Steven D'Aprano, 09.11.2010 05:01: >>> http://pypi.python.org/pypi/obfuscate >> >> Hmm - why is the Windows installer on that page called >> "linux-i686"? >> >> Stefan >> >> >> >> ------------------------------ >> >> Message: 4 >> Date: Tue, 9 Nov 2010 19:37:28 +0100 >> From: Eike Welk >> To: tutor at python.org >> Subject: Re: [Tutor] Columnar Transposition Cipher question >> Message-ID: <201011091937.28881.eike.welk at gmx.net> >> Content-Type: Text/Plain; charset="iso-8859-1" >> >> On Tuesday 09.11.2010 18:36:43 Stefan Behnel wrote: >>> Steven D'Aprano, 09.11.2010 05:01: >>> > http://pypi.python.org/pypi/obfuscate >>> >>> Hmm - why is the Windows installer on that page called >>> "linux-i686"? >> >> It was probably created on Linux. Python's Distutils create >> installers for >> Windows even on Linux. They get file names that contain "linux-". >> You must >> rename them, otherwise your users get confused. >> >> I did never try them, because I have no Windows computer. Do these >> Windows >> installers work when they are created on Linux? >> >> >> Eike. >> >> >> ------------------------------ >> >> Message: 5 >> Date: Wed, 10 Nov 2010 07:54:24 +1100 >> From: Steven D'Aprano >> To: tutor at python.org >> Subject: Re: [Tutor] List comprehension question >> Message-ID: <4CD9B500.4090605 at pearwood.info> >> Content-Type: text/plain; charset=UTF-8; format=flowed >> >> Richard D. Moores wrote: >> >>> See for a speed test with >>> n = >>> 100,000 and 100,000 loops >> >> As a general rule, you shouldn't try to roll your own speed tests. >> There >> are various subtleties that can throw your results right out. >> Timing >> small code snippets on modern multi-tasking computers is fraught >> with >> difficulties. >> >> Fortunately Python comes with that battery already included: the >> timeit >> module. You can use it from the shell like this: >> >> python -m timeit -s "setup code goes here" "test code goes here" >> >> At the Python interactive interpreter, the most useful pattern I've >> found is: >> >> from timeit import Timer >> t = Timer("proper_divisors(n)", >> "from __main__ import proper_divisors; n = 100000") >> min(t.repeat(repeat=5, number=100000)) >> >> >> Or if you're happy with Python's defaults, that last line can be >> just: >> >> min(t.repeat()) >> >> >> >> -- >> Steven >> >> >> ------------------------------ >> >> Message: 6 >> Date: Wed, 10 Nov 2010 08:29:51 +1100 >> From: Steven D'Aprano >> To: tutor at python.org >> Subject: Re: [Tutor] Columnar Transposition Cipher question >> Message-ID: <4CD9BD4F.3000309 at pearwood.info> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> Eike Welk wrote: >>> On Tuesday 09.11.2010 18:36:43 Stefan Behnel wrote: >>>> Steven D'Aprano, 09.11.2010 05:01: >>>>> http://pypi.python.org/pypi/obfuscate >>>> Hmm - why is the Windows installer on that page called >>>> "linux-i686"? >>> >>> It was probably created on Linux. >> >> That would be it. >> >> > Python's Distutils create installers for >>> Windows even on Linux. They get file names that contain "linux-". >>> You must >>> >>> rename them, otherwise your users get confused. >> >> I didn't realise that. >> >>> I did never try them, because I have no Windows computer. Do these >>> Windows >>> >>> installers work when they are created on Linux? >> >> I'm pretty sure I tried it, once, but I might be confabulating. >> >> >> >> -- >> Steven >> >> >> >> ------------------------------ >> >> Message: 7 >> Date: Tue, 9 Nov 2010 13:58:22 -0800 (PST) >> From: Albert-Jan Roskam >> To: Steven D'Aprano , tutor at python.org >> Subject: Re: [Tutor] List comprehension question >> Message-ID: <968733.36678.qm at web110711.mail.gq1.yahoo.com> >> Content-Type: text/plain; charset="us-ascii" >> >> For larger blocks of code, cProfile may also be useful for speed >> tests. >> >> Cheers!! >> 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: Steven D'Aprano >> To: tutor at python.org >> Sent: Tue, November 9, 2010 9:54:24 PM >> Subject: Re: [Tutor] List comprehension question >> >> Richard D. Moores wrote: >> >>> See for a speed test with >>> n = >>> 100,000 and 100,000 loops >> >> As a general rule, you shouldn't try to roll your own speed tests. >> There are >> various subtleties that can throw your results right out. Timing >> small code >> snippets on modern multi-tasking computers is fraught with >> difficulties. >> >> Fortunately Python comes with that battery already included: the >> timeit >> module. >> You can use it from the shell like this: >> >> python -m timeit -s "setup code goes here" "test code goes here" >> >> At the Python interactive interpreter, the most useful pattern I've >> found >> is: >> >> from timeit import Timer >> t = Timer("proper_divisors(n)", >> "from __main__ import proper_divisors; n = 100000") >> min(t.repeat(repeat=5, number=100000)) >> >> >> Or if you're happy with Python's defaults, that last line can be >> just: >> >> min(t.repeat()) >> >> >> >> -- 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: >> >> >> ------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> End of Tutor Digest, Vol 81, Issue 39 >> ************************************* >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Wed Nov 10 22:08:16 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 10 Nov 2010 13:08:16 -0800 Subject: [Tutor] variables question. In-Reply-To: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> References: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> Message-ID: On 11/10/2010 10:21 AM Jeff Honey said... > I have a question about where variables are exposed in python. You're looking for scoping rules -- see for example http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules where they get into some detail, but the short and older version is 1) search in local-global-builtin, and 2) if you assign to it in a scope, it's local to that scope. So, blah and foo below are visible in all the functions except any that specifically assign to blah or foo. HTH, Emile > > I have a monolothic script with a number of functions defined, can those functions share variables? can I instantiate them outside the function of where they are needed? do they need to be wrapped in quotes, ever? For example: > > blah = 123 > foo = 'somestring' > > def function(foo): > code that needs foo > anotherfunction(blah) > > def anotherfunction(blah): > code that needs blah > code that uses foo > > ....how about this: > > def function(blah, foo): > anotherfunc(blah) > anotherfunc(foo) > > ...what about my python being called from some parent script (something OTHER than python) that instantiates blah and foo FOR me? Can I just plug those into my code like I would normally? I guess this is more about HOW and WHERE I can make variables available for use. > > -- > ?????????????????? > ? kyoboku kazeoshi ? > ?????????????????? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From matlocs at odscompanies.com Wed Nov 10 23:18:48 2010 From: matlocs at odscompanies.com (Shawn Matlock) Date: Wed, 10 Nov 2010 14:18:48 -0800 Subject: [Tutor] put query result set into dictionary Message-ID: <1160CE2227C1694BA39144335BC35025373CF5BFD0@MAIL.pdx.odshp.com> Let's see if I can ask the right questions the right way. I am trying to put the results of a MySQL query into a dictionary. It fails because it includes the Unicode delimiter - "u'somevalue'". Can someone tell me the right way to do this, please? Thank you, Shawn csdbConn = zxJDBC.connect("jdbc:mysql://myhost:3306/mydb", "User", "Password", "com.mysql.jdbc.Driver") csdbCursor = csdbConn.cursor(1) envsql = "select envVariable, envValue from ODS_ENV_DICT where envName = 'ST2'" print 'envsql: ' + envsql csdbCursor.execute(envsql) envDict = {} for envVariable, envValue in csdbCursor.fetchall(): print envVariable, envValue envDict[envVariable].append(envValue) csdbCursor.close() csdbConn.close() ------------------ envsql: select envVariable, envValue from ODS_ENV_DICT where envName = 'ST2' envDB systest2 Traceback (most recent call last): File "H:\workspace\test\src\root\nested\example.py", line 33, in envDict[envVariable].append(envValue) KeyError: u'envDB' -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Wed Nov 10 23:44:45 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 10 Nov 2010 16:44:45 -0600 Subject: [Tutor] variables question. In-Reply-To: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> References: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> Message-ID: It's pretty typical for scoping rules. If you define variables outside of your funcs you can access them inside the func. If you want to change the value in the function you need to declare the scope as global. If you make another variable with the same name inside of a function it will shadow the outer variable. You could define the variables in a parent script if you want. This is actually how imports work basically. In config.py foo = "bar" In your py from config import foo def bar(): print foo ----------------------------- Sent from a mobile device with a bad e-mail client. ----------------------------- On Nov 10, 2010, at 12:21 PM, Jeff Honey wrote: > I have a question about where variables are exposed in python. > > I have a monolothic script with a number of functions defined, can those functions share variables? can I instantiate them outside the function of where they are needed? do they need to be wrapped in quotes, ever? For example: > > blah = 123 > foo = 'somestring' > > def function(foo): > code that needs foo > anotherfunction(blah) > > def anotherfunction(blah): > code that needs blah > code that uses foo > > ....how about this: > > def function(blah, foo): > anotherfunc(blah) > anotherfunc(foo) > > ...what about my python being called from some parent script (something OTHER than python) that instantiates blah and foo FOR me? Can I just plug those into my code like I would normally? I guess this is more about HOW and WHERE I can make variables available for use. > > -- > ?????????????????? > ? kyoboku kazeoshi ? > ?????????????????? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From carroll at tjc.com Thu Nov 11 00:16:19 2010 From: carroll at tjc.com (Terry Carroll) Date: Wed, 10 Nov 2010 15:16:19 -0800 (PST) Subject: [Tutor] Stupid bug Message-ID: This isn't a question, I'm just offering it as a cautionary tale and an opportunity to laugh at my own stupidity. I have a small function to calculate the MD5 checksum for a file. It's nothing fancy: ################################### import hashlib def md5(filename, bufsize=65536): """ Compute md5 hash of the named file bufsize is 64K by default """ m = hashlib.md5() with open(filename,"rb") as fd: content = fd.read(bufsize) while content != "": m.update(content) content = fd.read(bufsize) return m.hexdigest() ################################### I've discovered a need to calculate the checksum on the first 10K or so bytes of the file (faster when processing a whole CDROM or DVDROM full of large files; and also allows me to find when one file is a truncated copy of another). This seemed like an easy enough variation, and I came up with something like this: ################################### def md5_partial(filename, bufsize=65536, numbytes=10240): """ Compute md5 hash of the first numbytes (10K by default) of named file bufsize is 64K by default """ m = hashlib.md5() with open(filename,"rb") as fd: bytes_left = numbytes bytes_to_read = min(bytes_left, bufsize) content = fd.read(bytes_to_read) bytes_left = bytes_left - bytes_to_read while content != "" and bytes_left >0: m.update(content) bytes_to_read=min(bytes_left, bufsize) content = fd.read(bytes_to_read) bytes_left = bytes_left - bytes_to_read return m.hexdigest() ################################### Okay, not elegant, and violates DRY a little bit, but what the heck. I set up a small file (a few hundred bytes) and confirmed that md5 and md5_partial both returned the same value (where the number of bytes I was sampling exceeded the size of the file). Great, working as desired. But then when I tried a larger file, I was still getting the same checksum for both. It was clearly processing the entire file. I started messing with it; putting in counters and print statements, using the Gettysburg Address as sample daya and iterating over 20 bytes at a time, printing out each one, making sure it stopped appropriately. Still no luck. I spent 90 minutes over two sessions when I finally found my error. My invocation of the first checksum was: ################################### checksumvalue = my.hashing.md5("filename.txt") # (Not an error: I keep my own modules in Lib/site-packages/my/ ) print checksumvalue # # [several lines of code that among other things, define my new # function being tested] # checksumvalue2 = md5_partial("filename.txt", numbytes=200 print checksumvalue Turns out my function was working correctly all along; but with my typo, I was printing out the value from the first checksum each time. Doh! Well, no harm done, other than wasted time, and I did turn up a silly but harmless off-by-one error in the process. From joel.goldstick at gmail.com Thu Nov 11 01:19:24 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 10 Nov 2010 19:19:24 -0500 Subject: [Tutor] put query result set into dictionary In-Reply-To: <1160CE2227C1694BA39144335BC35025373CF5BFD0@MAIL.pdx.odshp.com> References: <1160CE2227C1694BA39144335BC35025373CF5BFD0@MAIL.pdx.odshp.com> Message-ID: On Wed, Nov 10, 2010 at 5:18 PM, Shawn Matlock wrote: > Let?s see if I can ask the right questions the right way. I am trying to > put the results of a MySQL query into a dictionary. It fails because it > includes the Unicode delimiter - ?u?somevalue??. Can someone tell me the > right way to do this, please? > > > > Thank you, > > Shawn > > Notice that you are returning strings. "u'somevalue'" . Your problem is not with the unicode, its with the quotes that wrap the unicode delimiter. I haven't used zxJDBC object, but I am guessing if you look into its documentation you can return what you really want, which is a unicode string, not a string containing the representation of a unicode string > > > csdbConn = zxJDBC.connect("jdbc:mysql://myhost:3306/mydb", "User", > "Password", "com.mysql.jdbc.Driver") > > > > csdbCursor = csdbConn.cursor(1) > > > > envsql = "select envVariable, envValue from ODS_ENV_DICT where envName = > 'ST2'" > > print 'envsql: ' + envsql > > > > csdbCursor.execute(envsql) > > > > envDict = {} > > for envVariable, envValue in csdbCursor.fetchall(): > > print envVariable, envValue > > envDict[envVariable].append(envValue) > > > > csdbCursor.close() > > csdbConn.close() > > > > ------------------ > > envsql: select envVariable, envValue from ODS_ENV_DICT where envName = > 'ST2' > > envDB systest2 > > Traceback (most recent call last): > > *File "H:\workspace\test\src\root\nested\example.py", line 33, in > * > > envDict[envVariable].append(envValue) > > KeyError: u'envDB' > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 11 01:46:26 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Nov 2010 00:46:26 -0000 Subject: [Tutor] unicode nightmare References: Message-ID: "danielle davout" wrote > I simplify it to > v = u'\u0eb4' > X = (1,) > gen = ((v ,v) for x in X for y in X) > > What can be so wrong in this line, around it to give the 1lined file > ?:? > where ? "is" not u'\u0eb4' but u'\u0ec4' though a direct printing > looks OK The code will produce a one line file with v repeated twice. Now why do you think the character is different? What have you done to check it? What do you mean by a direct printing? print v maybe? > To write the file corresponding to my nth generator of my list h I > use > def ecrire(n): > f= codecs.open("G"+str(n),"w","utf8") > for x, tx in h[n]: > f.write((x + U":"+ tx)) > f.write('\n') Personally I'd use f.write(U"%s:%s\n" % (x,tx)) but thats largely a matter of style preference I guess. But why do you have double parens in the first print? > But In its non simplified form > h.append( (x + v + y ,tr[x]+ tr[v]+ tr[y]) for x in CC for y in > OFC) ) > before I have a chance to write anything in the file G5 > I have got the KeyError: u'\u0ec4' > yes tr is a dictionary that doesn't have u'\u0ec4' as a key > but tr[v] is well definied ... OK, but the error is valid in that case. Which implies that you have bad data in CC. What exactly are you asking? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Nov 11 02:03:30 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Nov 2010 01:03:30 -0000 Subject: [Tutor] put query result set into dictionary References: <1160CE2227C1694BA39144335BC35025373CF5BFD0@MAIL.pdx.odshp.com> Message-ID: "Shawn Matlock" wrote > I am trying to put the results of a MySQL query into a dictionary. > It fails because it includes the Unicode delimiter - "u'somevalue'". I don't think so... > envsql = "select envVariable, envValue from ODS_ENV_DICT where > envName = 'ST2'" > csdbCursor.execute(envsql) > envDict = {} > for envVariable, envValue in csdbCursor.fetchall(): > envDict[envVariable].append(envValue) Append is a list operation but you don;t have a list (yet). You are just adding a single value to a dictionary. You need something like: envDict[envVariable] = envValue Or if you really want a list you need to check if the value is there first and then append. You could do that with setdefault() like so: envDict.setdefault(envVariable, []).append(envValue) Which returns the list if one exists or an empty list if it doesn't and appends the value to it, it then assigns the resulting list back to the dictionary at the key position > Traceback (most recent call last): > File "H:\workspace\test\src\root\nested\example.py", line 33, in > > envDict[envVariable].append(envValue) > KeyError: u'envDB' Despite the KeyError message its really because you are trying to use append on a non existent list: >>> d = {} >>> d[5].append(7) Traceback (most recent call last): File "", line 1, in KeyError: 5 Same error, no unicode in sight. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From Greg.Lindstrom at NovaSysHealth.com Wed Nov 10 21:36:47 2010 From: Greg.Lindstrom at NovaSysHealth.com (Greg Lindstrom) Date: Wed, 10 Nov 2010 14:36:47 -0600 Subject: [Tutor] Data Directory under site-packages Message-ID: <51F45499BCFE674F8A4EA4841F9CE6922412ABC561@STLEXVN01P.centene.com> Hello, I'm writing my first module that I intend to put under our company's "site-packages" directory for everyone to use in their programs. The problem I'm having is that I want to place files in a data directory under the module directory (under site-packages) and I don't know how to set the path so I pick up the files. If I use open('./data/myfile') I get the path of the file importing the module (which could be just about anywhere). I've tried various combinations using os.path.abspath() and os.path.dirname() but have the same problem. Is there a way I can use files in the subdirectory (I really do not want dozens more files in the main directory)? Thanks for your help, --greg CONFIDENTIALITY NOTICE: This communication contains information intended for the use of the individuals to whom it is addressed and may contain information that is privileged, confidential or exempt from other disclosure under applicable law. If you are not the intended recipient, you are notified that any disclosure, printing, copying, distribution or use of the contents is prohibited. If you have received this in error, please notify the sender immediately by telephone or by returning it by return mail and then permanently delete the communication from your system. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Thu Nov 11 03:45:44 2010 From: carroll at tjc.com (Terry Carroll) Date: Wed, 10 Nov 2010 18:45:44 -0800 (PST) Subject: [Tutor] Data Directory under site-packages In-Reply-To: <51F45499BCFE674F8A4EA4841F9CE6922412ABC561@STLEXVN01P.centene.com> References: <51F45499BCFE674F8A4EA4841F9CE6922412ABC561@STLEXVN01P.centene.com> Message-ID: On Wed, 10 Nov 2010, Greg Lindstrom wrote: > I'm writing my first module that I intend to put under our company's > "site-packages" directory for everyone to use in their programs. The > problem I'm having is that I want to place files in a data directory under > the module directory (under site-packages) and I don't know how to set the > path so I pick up the files. If I use open('./data/myfile') I get the path > of the file importing the module (which could be just about anywhere). I've > tried various combinations using os.path.abspath() and os.path.dirname() but > have the same problem. Is there a way I can use files in the subdirectory > (I really do not want dozens more files in the main directory)? I'm not sure I follow. You want to put data, i.e., non-python code, in the import path? That sounds unusual to me. You can find the filename from which a module is imported with the module's __file__ attribute; and then os.path.dirname() can get you the directory. So if you wanted to address a subdirectory named "data" in the same directory from which you imported a given module, or a file "myfile.txt" in that subdirectory, that's possible. Using the sqlite module as an example on my system: >>> import sqlite3 >>> sqlite3.__file__ 'C:\\Python26\\lib\\sqlite3\\__init__.pyc' >>> import os >>> os.path.dirname(sqlite3.__file__) 'C:\\Python26\\lib\\sqlite3' >>> os.path.join(os.path.dirname(sqlite3.__file__), "data") 'C:\\Python26\\lib\\sqlite3\\data' >>> os.path.join(os.path.dirname(sqlite3.__file__), "data", "myfile.txt") 'C:\\Python26\\lib\\sqlite3\\data\\myfile.txt' Is this the kind of thing you're thinking of? Again, it's highly unusual to put non-code data in the import path; I've never heard of this being done before, and it makes me shiver in revulsion. I'm not sure I can articulate exactly what bad effects it will have, apart from the inherent messiness of it, but I don't like it. From waynejwerner at gmail.com Thu Nov 11 04:40:34 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 10 Nov 2010 21:40:34 -0600 Subject: [Tutor] Stupid bug In-Reply-To: References: Message-ID: On Wed, Nov 10, 2010 at 5:16 PM, Terry Carroll wrote: > This isn't a question, I'm just offering it as a cautionary tale and an > opportunity to laugh at my own stupidity. > > Turns out my function was working correctly all along; but with my typo, I > was printing out the value from the first checksum each time. Doh! > > Well, no harm done, other than wasted time, and I did turn up a silly but > harmless off-by-one error in the process.\ I wish I could say that has never bitten me... but it has, several times. Including the sister bug - continually importing something and you still get the old function because you forgot to delete the .pyc file. Whoops! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 11 09:41:49 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 11 Nov 2010 08:41:49 +0000 (GMT) Subject: [Tutor] Fw: unicode nightmare In-Reply-To: References: Message-ID: <599930.89676.qm@web86701.mail.ird.yahoo.com> forward to the list Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ---- > From: danielle davout > To: Alan Gauld > Sent: Thursday, 11 November, 2010 4:19:22 > Subject: Re: [Tutor] unicode nightmare > > First thanks to answer ... even if I couldn't manage to be clear in > formulating my question > It already helps ;) I was confident enough that somebody of this > helpful group would answer to my S.O.S > to manage to have a night of sleep without nigthmare and a night of > sleep even short helps too :) > > I am able now better resume my problem and it doesn't look anymore > like a unicode problem at all. > (below, If necessary .., some of lines of codes that conduct me to > this conclusion) > In my script I construct a generator I want to use later on; for this > I make the use of what I thought an accessory (convenient) variable, I > do my business ... > and when I'm ready to use the generator it has changed "because" in > the mean time I have reused the same name of variable. > If I say I go as far as later on to remove altogether the variable by > the statement del(v) > I have a traceback complaining NameError: global name 'v' is not defined > If I don't reuse the same name (say as a quick test I put an exit() > before using it) > I have no complaint. > If I take care to change the name, not using any more loop to > construct all the generators I need, my script gives the results I > expected. > > It looks very puzzling to me and I would like to have some pointers to > be able to understand one day what have happened to me :) > Thanks, > > > > On Thu, Nov 11, 2010 at 7:46 AM, Alan Gauld wrote: > > > > "danielle davout" wrote > > > >> I simplify it to > >> v = u'\u0eb4' > >> X = (1,) > >> gen = ((v ,v) for x in X for y in X) > >> > >> What can be so wrong in this line, around it to give the 1lined file > >> ?:? > >> where ? "is" not u'\u0eb4' but u'\u0ec4' though a direct printing looks > >> OK > > > > The code will produce a one line file with v repeated twice. > > Now why do you think the character is different? > > What have you done to check it? > > > > What do you mean by a direct printing? > > > > print v > > > > maybe? > yes > >> To write the file corresponding to my nth generator of my list h I use > >> def ecrire(n): > >> f= codecs.open("G"+str(n),"w","utf8") > >> for x, tx in h[n]: > >> f.write((x + U":"+ tx)) > >> f.write('\n') > > > > Personally I'd use > > > > f.write(U"%s:%s\n" % (x,tx)) > ok > > but thats largely a matter of style preference I guess. > > But why do you have double parens in the first print? > remaining of several trials... > >> But In its non simplified form > >> h.append( (x + v + y ,tr[x]+ tr[v]+ tr[y]) for x in CC for y in OFC) ) > >> before I have a chance to write anything in the file G5 > >> I have got the KeyError: u'\u0ec4' > >> yes tr is a dictionary that doesn't have u'\u0ec4' as a key > >> but tr[v] is well defined ... > > > > OK, but the error is valid in that case. > > Which implies that you have bad data in CC. > > I'm sorry, I was not very clear on that point... nor CC nor OFC > contains u'\u0ec4' > and I haven't no problem with for example > h.append(((u"?" + x + y, tr[x]+e2 +tr[y]) for x in CC for y in OFC)) > if I define tr[u'\u0ec4'] I obtain a result but that is wrong on the > first part x + v + y > every thing looks like *the generator was not made with the value of v > that I believe to give* > > What exactly are you asking? > If I write : > 114 v = u'\u0eb4' > 115 X = (1,) > 116 h.append( ((v ,v) for x in X for y in X)) > 117 print v > 118 #exit() > v prints nicely > If I remove the last comment, v still prints nicely but I get the traceback > Traceback (most recent call last): > File "/home/dan/workspace/lao/src/renaud/tt.py", line 261, in > ecrire(n) > File "/home/dan/workspace/lao/src/renaud/tt.py", line 254, in ecrire > for x, tx in h[n]: > File "/home/dan/workspace/lao/src/renaud/tt.py", line 116, in > h.append( ((v ,v) for x in X for y in X)) > NameError: global name 'v' is not defined > > Where has gone my variable v ? Why it is considered as global as soon > I use it in a generator? > > If in 114 I write > v = w = u'\u0eb4' > and I delete w by del(w) and still want to print it I'm only told > that "name 'w' is not defined" > Why changing the value of v 200 lines below I can change the value of > the generator > Definitely it is not a unicode problem but of global variable > If I write > w = u'\u0eb4' > h.append( (x +w + y , tr[x]+ tr[w]+ tr[y]) for x in CC for y in OFC) ) > my file G5 is generated > ???:kik > ???:kim > ???:kiv > ..... > From rdmoores at gmail.com Thu Nov 11 13:01:34 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 11 Nov 2010 04:01:34 -0800 Subject: [Tutor] List comprehension question In-Reply-To: <4CDA6624.1070302@pearwood.info> References: <4CDA6624.1070302@pearwood.info> Message-ID: On Wed, Nov 10, 2010 at 01:30, Steven D'Aprano wrote: > > Richard D. Moores wrote: > >> def proper_divisors_sum(n): >> ? ?return sum(list(divisors(n))) - n > > There's no need to call list first. sum() will happily operate on any sort of iterable -- lists, sums, iterators, generators, range objects. Anything except strings, which would be pointless even if you could do it, which you can't, but even so you can fool sum() to work with strings with a bit of effort. > > >> Using Steven's suggested speed test >> this gets 6.2404818210135886 >> >> My up-to-now fastest version, > > [...] >> >> gets 6.1753780857622473 >> >> So they're about even. > > I'd say that the difference is probably statistically insignificant. Even if it's consistent on your PC, on another PC with a slightly different processor, slightly different memory, or a different operating system, it could very well go the other way. I think that's what I meant. :) > In any case, since those times are ~6 seconds per 100,000 loops, the real difference is only 60 microseconds -- completely trivial unless you're doing some *serious* number crunching. > > > P.S. don't take that as a put down -- you should be pleased that your code is around as fast as Tim Peter's code :) Nah. But where is Tim Peter's code? Dick From josep.m.fontana at gmail.com Thu Nov 11 13:08:11 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Thu, 11 Nov 2010 13:08:11 +0100 Subject: [Tutor] Creating one file out of all the files in a directory Message-ID: Hi, I'm trying to create a script to do the following. I have a directory containing hundreds of text files. I need to create a single file with the contents of all the files in the directory. Within that file, though, I need to create marks that indicate the division between the contents of each file that has wound up in that single file. I got this far but I'm stumped to continue: ----------------- code-------- import os path = '/Volumes/DATA/MyPath' os.chdir(path) file_names = glob.glob('*.txt') for subdir, dirs, files in os.walk(path): for file in files: f = open(file, 'r') text = f.readlines() f.close() f = open(file, 'a') f.write('\n\n' + '________________________________' + '\n') f.close() ------------ What's missing here is obvious. This iterates over all the files and creates the mark for the division at the end of each file. There is nothing, however, to pipe the output of this loop into a new file. I've checked the different manuals I own plus some more on the internet but I can't figure out how to do what's left. I could get by with a little help from my Tutor friends. Josep M. From evert.rol at gmail.com Thu Nov 11 13:41:51 2010 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 11 Nov 2010 13:41:51 +0100 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: References: Message-ID: > I'm trying to create a script to do the following. I have a directory > containing hundreds of text files. I need to create a single file with > the contents of all the files in the directory. Within that file, > though, I need to create marks that indicate the division between the > contents of each file that has wound up in that single file. > > I got this far but I'm stumped to continue: > > ----------------- code-------- > import os > path = '/Volumes/DATA/MyPath' > os.chdir(path) > file_names = glob.glob('*.txt') You don't use file_names any further. Depending on whether you want files from subdirectories or not, you can use the os.walk below or file_names. In the latter case, your loop just becomes: for file in file_names: f = open(file, 'r') etc Though I would use filename instead of file, since file is a Python built-in: >>> file > for subdir, dirs, files in os.walk(path): > for file in files: > f = open(file, 'r') > text = f.readlines() Since you don't care about lines in your files, but just the entire file contents, you could also simply use data = f.read() > f.close() > f = open(file, 'a') You're opening the same file from which you were just reading, and append to that. Since you do that for every file, that doesn't make much sense, imho. But see further down. > f.write('\n\n' + '________________________________' + '\n') So close ;-). What you're missing is the next write statement: f.write(data) (or f.write(''.join(text)) which shows why read() is nicer in this case: readlines() returns a list, not just a single string). > f.close() But actually, you can open and close the output file outside the entire loop; just name it differently (eg, before the first loop, outfile = open('outputfile', 'w') and in the loop: outfile.write(data) after the loop of course: outfile.close() In this case, though, there's one thing to watch out for: glob or os.walk will pick up your newly (empty) created file, so you should either put the all-containg file in a different directory (best practice) or insert an if-statement to check whether file[name] != 'outputfile' Finally, depending on the version of Python you're using, there are nice things you can do with the 'with' statement, which has an incredible advantage in case of file I/O errors (since you're not checking for any read errors). See eg http://effbot.org/zone/python-with-statement.htm (bottom part for example) or Google around. Cheers, Evert > ------------ > > What's missing here is obvious. This iterates over all the files and > creates the mark for the division at the end of each file. There is > nothing, however, to pipe the output of this loop into a new file. > I've checked the different manuals I own plus some more on the > internet but I can't figure out how to do what's left. > > I could get by with a little help from my Tutor friends. > > Josep M. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From rdmoores at gmail.com Thu Nov 11 14:04:10 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 11 Nov 2010 05:04:10 -0800 Subject: [Tutor] List comprehension question In-Reply-To: <4CDA757E.5000500@pearwood.info> References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> Message-ID: On Wed, Nov 10, 2010 at 02:35, Steven D'Aprano wrote: > Richard D. Moores wrote: >> >> On Tue, Nov 9, 2010 at 12:54, Steven D'Aprano wrote: >>> >>> Richard D. Moores wrote: >>> >>>> See for a speed test with n = >>>> 100,000 and 100,000 loops >>> >>> As a general rule, you shouldn't try to roll your own speed tests. There >>> are >>> various subtleties that can throw your results right out. Timing small >>> code >>> snippets on modern multi-tasking computers is fraught with difficulties. >> >> Yes, but I thought that if I ran the tests the way I did, several >> times and then reversing the order of the functions, and seeing that >> the results were very similar, I could be pretty sure of my findings. >> Could you point out where taking even that amount of care could lead >> me astray? > > Well, the biggest problem is that you're re-inventing the wheel. But in > truth, what you did was not terrible, particularly if you're using Python 3 > where range() is quite lightweight rather than a heavy operation that > creates a big list. > > There are various traps when timing code: > > * There are commonly two functions you use for getting the time: time.time() > and time.clock(). On Windows, the best one to use is clock(), but on other > operating systems, you should probably use time(). ?The timeit module > automatically chooses the right one for you. Thanks for this! My memory had it reversed: time() best for windows; clock() for the rest. So I'm now doing a lot of search and replace on old scripts. And I reread the timeit doc. I found this down at the bottom of : ==========begin quote from timeit module doc===================== To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement: def test(): "Stupid test function" L = [i for i in range(100)] if __name__=='__main__': from timeit import Timer t = Timer("test()", "from __main__ import test") print(t.timeit()) ========end quote from timeit module doc====================== Earlier in this thread you gave us/me this: ============begin wisdom from Steven================= At the Python interactive interpreter, the most useful pattern I've found is: from timeit import Timer t = Timer("proper_divisors(n)", "from __main__ import proper_divisors; n = 100000") min(t.repeat(repeat=5, number=100000)) Or if you're happy with Python's defaults, that last line can be just: min(t.repeat()) =======temporary end of wisdom from Steven================= I find using that at the interactive prompt a bit onerous -- lots of copy and pasting. And doubly so when comparing times for 2 or more functions. The timeit doc gave me the obvious idea of how to avoid the prompt and also easily compare the times of 2 or more functions. I'd like to know if doing it this way is correct: Please see Huh. Just realized that this timing method doesn't include the 5 repeats called for by Steven's method. So how about using a for loop? As in . Dick From zstumgoren at gmail.com Thu Nov 11 15:02:44 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 11 Nov 2010 09:02:44 -0500 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place Message-ID: Hi folks, I'm trying to gain a deeper understanding of why it's possible to modify list elements in-place *without* replacing them. For instance, why is the below possible? >>> class Dummy(object): ... pass ... >>> a = Dummy() >>> b = Dummy() >>> x = [a, b] # modify list elements in-place >>> x[1].name = 'The Dude' >>> print x[1].name The Dude >>> x[0].name = 'The Stranger' >>> for item in x: ... print item.name ... The Stranger The Dude # modify elements by iterating over the list >>> for item in x: ... item.start_date = 2010 >>> for item in x: ... print item.name, item.start_date ... The Stranger 2010 The Dude 2010 I figured the below quote offers the beginning of an explanation on this page: "The list object stores pointers to objects, not the actual objects themselves." http://effbot.org/zone/python-list.htm But I was hoping you all could provide a more in-depth explanation, or even better, direct me to some other readings and python code that implements this behavior. Can anyone point me in the right direction for further study? Thanks! Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Nov 11 15:56:02 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 11 Nov 2010 06:56:02 -0800 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place In-Reply-To: References: Message-ID: On Thu, Nov 11, 2010 at 06:02, Serdar Tumgoren wrote: > Hi folks, > I'm trying to gain a deeper understanding of why it's possible to modify > list elements in-place *without* replacing them. For instance, why is the > below possible? > >>>> class Dummy(object): > ...???? pass > ... >>>> a = Dummy() >>>> b = Dummy() >>>> x = [a, b] > # modify list elements in-place >>>> x[1].name = 'The Dude' >>>> print x[1].name > The Dude >>>> x[0].name = 'The Stranger' >>>> for item in x: > ...???? print item.name > ... > The Stranger > The Dude > # modify elements by iterating over the list >>>> for item in x: > ...???? item.start_date = 2010 > >>>> for item in x: > ...???? print item.name, item.start_date > ... > The Stranger 2010 > The Dude 2010 Would you have the same question about what takes place here?: >>> list_ = [3,4,5] >>> list_[1] = 10 >>> list_ [3, 10, 5] >>> Dick Moores From zstumgoren at gmail.com Thu Nov 11 17:30:14 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 11 Nov 2010 11:30:14 -0500 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place In-Reply-To: References: Message-ID: > > > Would you have the same question about what takes place here?: > > >>> list_ = [3,4,5] > >>> list_[1] = 10 > >>> list_ > [3, 10, 5] > >>> > > No surprise there. It's a familiar usage and it appears to be the canonical example (in textbooks/tuts) for demonstrating "in-place" object modification. In these examples the object being modified is the list itself, rather than the objects stored in the list. The examples typically show how the sort function sorts the actual list as opposed to returning a sorted copy of the list. But I think I see your point. The list object behaves the same as the objects stored inside the list. In other words, the list object is a reference to an ordered sequence of object references, and you're operating on those (referenced) objects rather than copies of the objects when you iterate over the list. Is that correct? If so, no doubt there's a simpler way to say all that? -------------- next part -------------- An HTML attachment was scrubbed... URL: From matlocs at odscompanies.com Thu Nov 11 17:56:37 2010 From: matlocs at odscompanies.com (Shawn Matlock) Date: Thu, 11 Nov 2010 08:56:37 -0800 Subject: [Tutor] put query result set into dictionary In-Reply-To: References: <1160CE2227C1694BA39144335BC35025373CF5BFD0@MAIL.pdx.odshp.com> Message-ID: <1160CE2227C1694BA39144335BC35025373CF5C18F@MAIL.pdx.odshp.com> That was it. Thank you, Alan. -----Original Message----- From: tutor-bounces+matlocs=odscompanies.com at python.org [mailto:tutor-bounces+matlocs=odscompanies.com at python.org] On Behalf Of Alan Gauld Sent: Wednesday, November 10, 2010 5:04 PM To: tutor at python.org Subject: Re: [Tutor] put query result set into dictionary "Shawn Matlock" wrote > I am trying to put the results of a MySQL query into a dictionary. > It fails because it includes the Unicode delimiter - "u'somevalue'". I don't think so... > envsql = "select envVariable, envValue from ODS_ENV_DICT where > envName = 'ST2'" > csdbCursor.execute(envsql) > envDict = {} > for envVariable, envValue in csdbCursor.fetchall(): > envDict[envVariable].append(envValue) Append is a list operation but you don;t have a list (yet). You are just adding a single value to a dictionary. You need something like: envDict[envVariable] = envValue Or if you really want a list you need to check if the value is there first and then append. You could do that with setdefault() like so: envDict.setdefault(envVariable, []).append(envValue) Which returns the list if one exists or an empty list if it doesn't and appends the value to it, it then assigns the resulting list back to the dictionary at the key position > Traceback (most recent call last): > File "H:\workspace\test\src\root\nested\example.py", line 33, in > > envDict[envVariable].append(envValue) > KeyError: u'envDB' Despite the KeyError message its really because you are trying to use append on a non existent list: >>> d = {} >>> d[5].append(7) Traceback (most recent call last): File "", line 1, in KeyError: 5 Same error, no unicode in sight. HTH, -- Alan Gauld 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 steve at pearwood.info Thu Nov 11 18:22:08 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 04:22:08 +1100 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place In-Reply-To: References: Message-ID: <4CDC2640.4090706@pearwood.info> Serdar Tumgoren wrote: > Hi folks, > I'm trying to gain a deeper understanding of why it's possible to modify > list elements in-place *without* replacing them. For instance, why is the > below possible? Why? Because the designer of Python, Guido van Rossum, wanted it to be possible, and he designed the language so that it would be. Do you perhaps mean *how* is it possible? >>>> class Dummy(object): > ... pass > ... >>>> a = Dummy() >>>> b = Dummy() >>>> x = [a, b] > # modify list elements in-place >>>> x[1].name = 'The Dude' >>>> print x[1].name > The Dude I don't understand why you are surprised by this behaviour. Python is not a purely functional language like Haskell, where data is always immutable. Most Python objects are mutable -- they can be modified in place. (Although the exceptions include some of the most commonly used built-in objects like ints, tuples, and strings.) Would you be surprised by this behaviour? b = Dummy() b.name = 'The Dude' print b.name => prints 'The Dude' If not, then why should it make any difference whether you refer to the instance via the name "b" or via the list item x[0]? They both refer to the same object. Objects can have many different references to it: x = [None, None] # placeholders y = [None] d = {} a = b = c = x[0] = x[1] = y[0] = d['key'] = Dummy() Now the names "a", "b", "c", the list items x[0], x[1], y[0], and the dictionary item d['key'] all refer to the same object. You can create new names on the fly: d = c e = x[0] for item in x: pass d['another key'] = y[0] or delete them: del a, c, x[1], d['key'] [...] > I figured the below quote offers the beginning of an explanation on this > page: > "The list object stores pointers to objects, not the actual objects > themselves." > http://effbot.org/zone/python-list.htm The use of pointers is an implementation detail for efficiency, and it refers to how Python's object model is implemented in C. It is important not to lose sight of the distinction between the semantics of Python objects themselves, and the way that those objects are implemented in lower-level languages such as C. In Python, if you have x[0] = Dummy(), the list object x stores the Dummy instance itself. That's what the code *means* -- create an instance of the Dummy class and store it in the list x. But of course for efficiency reasons, and ease of programming, the most obvious implementation will be to place the instance in the heap somewhere, and keep a pointer to it in the list. How else could you do it? You could store the entire object in the list, but that would be terribly inefficient. But it could be done -- you could, with difficulty, implement Python in a language like Fortran 77 (which has no dynamic memory allocation, and therefore no pointers), or in Haskell, which is purely functional. Or you could come up with a (slow, inefficient) implementation which moved around large instance objects instead of small pointers. There is no way to get access to the underlying pointers from pure Python code. From pure Python, pointers don't exist -- Python gives you no way to create or access pointers from Python code. All you have access to is objects. -- Steven From steve at pearwood.info Thu Nov 11 18:33:20 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 04:33:20 +1100 Subject: [Tutor] Stupid bug In-Reply-To: References: Message-ID: <4CDC28E0.50801@pearwood.info> Wayne Werner wrote: > Including the sister bug - continually importing something and you still get > the old function because you forgot to delete the .pyc file. Whoops! Er, whoops is right... I think you may have misinterpreted what you were seeing. When you import a module for the first time, Python checks the date stamps on the .pyc file (if it exists) and ONLY uses it if it is newer than the .py file. If you update the source code, and then import the module, the obsolete .pyc file will be ignored and over-ridden. You don't have to delete the .pyc file in order for Python to use a newer source file. However, if the date stamps are screwed up, of course anything could happen. Or if you move the .pyc files into an earlier part of the PYTHONPATH, so they are seen before the .py files. Note also that what I described only occurs the first time you import a module. The second and subsequent time you import a module, it is not retrieved from either the .py or the .pyc file, it is retrieved from the cache in sys.modules. Python is not really designed for reloading modules on the fly. There is the reload() function (built-in in Python 2.x, moved into a library in Python 3.x) but it is a fairly feeble thing, only good for the most simple interactive use. Unless you're using a library that offers proper reload functionality, the safest way to ensure you're using the latest version of the module you've just edited is to exist the interpreter and start it up again. -- Steven From steve at pearwood.info Thu Nov 11 18:41:34 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 04:41:34 +1100 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place In-Reply-To: References: Message-ID: <4CDC2ACE.6030801@pearwood.info> Serdar Tumgoren wrote: > But I think I see your point. The list object behaves the same as the > objects stored inside the list. Er, surely not... the list object is a list, the objects inside the list are ints. They do not behave the same. > In other words, the list object is a > reference to an ordered sequence of object references, and you're operating > on those (referenced) objects rather than copies of the objects when you > iterate over the list. Is that correct? If so, no doubt there's a simpler > way to say all that? "A list is an ordered sequence of objects. When you iterate over the list, you see the contents of the list, not copies. Python never copies objects unless you explicitly tell it to." -- Steven From kushal.kumaran at gmail.com Thu Nov 11 14:07:13 2010 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: Thu, 11 Nov 2010 18:37:13 +0530 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: References: Message-ID: <1289480833.13521.5.camel@Nokia-N900> ----- Original message ----- > Hi, > > I'm trying to create a script to do the following. I have a directory > containing hundreds of text files. I need to create a single file with > the contents of all the files in the directory. Within that file, > though, I need to create marks that indicate the division between the > contents of each file that has wound up in that single file. > Your current code adds the marker line to the original files. Is that intended? You can open the output file for writing by passing 'w' as the second argument to open. You would do this before your directory-walking loop. Then when you read the contents of any file, just write to your output file as well, along with your marker line. > I got this far but I'm stumped to continue: > > ----------------- code-------- > import os > path = '/Volumes/DATA/MyPath' > os.chdir(path) > file_names = glob.glob('*.txt') output_stream = open('outputfilename', 'w') > for subdir, dirs, files in os.walk(path): >? ? ? ? for file in files: >? ? ? ? ? ? ? ? f = open(file, 'r') >? ? ? ? ? ? ? ? text = f.readlines() output_stream.writelines(text) output_stream.write('______\n') >? ? ? ? ? ? ? ? f.close() >? ? ? ? ? ? ? ? f = open(file, 'a') >? ? ? ? ? ? ? ? f.write('\n\n' + '________________________________' + '\n') >? ? ? ? ? ? ? ? f.close() > output_stream.close() > ------------ > > What's missing here is obvious. This iterates over all the files and > creates the mark for the division at the end of each file. There is > nothing, however, to pipe the output of this loop into a new file. > I've checked the different manuals I own plus some more on the > internet but I can't figure out how to do what's left. > > I could get by with a little help from my Tutor friends. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tumgorenz at washpost.com Thu Nov 11 20:21:22 2010 From: tumgorenz at washpost.com (Serdar Tumgoren) Date: Thu, 11 Nov 2010 14:21:22 -0500 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place In-Reply-To: <4CDC2640.4090706@pearwood.info> References: <4CDC2640.4090706@pearwood.info> Message-ID: First off, thanks for the detailed response! I had a few follow-up questions below, if you're willing to indulge. Feel free to direct me to RTM some books on C and the python source code, of course :) > Why? Because the designer of Python, Guido van Rossum, wanted it to be > possible, and he designed the language so that it would be. > > Do you perhaps mean *how* is it possible? > Yes indeed, I suppose that is really what I was asking. > > The use of pointers is an implementation detail for efficiency, and it > refers to how Python's object model is implemented in C. > > It is important not to lose sight of the distinction between the semantics > of Python objects themselves, and the way that those objects are implemented > in lower-level languages such as C. > > In Python, if you have x[0] = Dummy(), the list object x stores the Dummy > instance itself. I think the above example gets to the source of my confusion. Clearly the instance remains accessible via x[0], but I somehow never thought of a specific list index as an obvious "symbol" for -- or reference to -- an instance. I suspect that my confusion stems from the day-to-day routine of instantiating an object and assigning it to a variable at the same time, often inside a loop, and then performing additional processing on this instance *before* storing it in a list or some other container. Above, it seems that you're *still* performing simultaneous instantiation and assignment (from a code perspective), but the "symbol" that you're assigning to is the list index itself. And that seems to explain why the Dummy instance remains accessible and is not garbage-collected. Is that a correct understanding? > That's what the code *means* -- create an instance of the Dummy class and > store it in the list x. But of course for efficiency reasons, and ease of > programming, the most obvious implementation will be to place the instance > in the heap somewhere, and keep a pointer to it in the list. How else could > you do it? You could store the entire object in the list, but that would be > terribly inefficient. But it could be done -- you could, with difficulty, implement Python in a > language like Fortran 77 (which has no dynamic memory allocation, and > therefore no pointers), or in Haskell, which is purely functional. Or you > could come up with a (slow, inefficient) implementation which moved around > large instance objects instead of small pointers. There is no way to get access to the underlying pointers from pure Python > code. From pure Python, pointers don't exist -- Python gives you no way to > create or access pointers from Python code. All you have access to is > objects. So is a reference simply a Python-level symbol (ie some collections of characters accessible from Python code) that corresponds to a pointer, which in turn points to the location in memory where the object is stored? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Thu Nov 11 21:11:34 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Thu, 11 Nov 2010 12:11:34 -0800 Subject: [Tutor] What is a "state variable"? Message-ID: The term comes up in the 2nd section of didn't help. k = 23 Is k then a state variable in that its state is 23? What sorts of variables are, and are not, state variables? The concept of a state variable seems central to Kent's article. If only I knew exactly what it was. Thanks, Dick Moores From emile at fenx.com Thu Nov 11 22:22:25 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 11 Nov 2010 13:22:25 -0800 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: On 11/11/2010 12:11 PM Richard D. Moores said... > The term comes up in the 2nd section of > > > didn't help. > > k = 23 > > Is k then a state variable in that its state is 23? What sorts of > variables are, and are not, state variables? > > The concept of a state variable seems central to Kent's article. If > only I knew exactly what it was. From the article, "A class is a container for shared state, combined with functions (methods) that operate on that state. By putting state variables into member fields, they are accessible to all the methods of the class without having to be passed as parameters." So, by his own definition state variables are parameters. Emile From wprins at gmail.com Thu Nov 11 23:47:13 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 11 Nov 2010 22:47:13 +0000 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: On 11 November 2010 20:11, Richard D. Moores wrote: > The term comes up in the 2nd section of > > > > > didn't help. > > k = 23 > > Is k then a state variable in that its state is 23? What sorts of > variables are, and are not, state variables? > My $0.02 worth: Firstly, the original page somewhat conflates classes and objects, although this is common and usually the author's meaning can be inferred if one understands object orientation properly and understand that both classes, and the objects (instances) made from that class can have their own state. Usually however people mean that objects (instances) have state variables, even when they talk about classes. The trouble is that classes are themselves objects, and can in fact have their own stat. But, ignore that for the minute. So what is state? Well, your toaster has a "powered" state, it's either "on" or "off". If you were to create a class to model/represent a toaster (e.g. from which you can create toaster instances), each of them would be either "on" or "off". Now, how would you implement this? Well, by using a variable to store what the current state of the toaster object's supposed to be, e.g. maybe a boolean variable calld "powered_on" that is true when that instance is supposed to be on, and false otherwise. So then, any variable (field member of an object) that serves to record what state an object instance is in, can legitimately be called a state variable. Now, the point the original article was making was that if you have several pure functions (e.g. structured programming style) where the only scopes available is either full on global or local to each function, then *every* variable that a function might modify/mutate must be passed to it as a parameter. Consequently, if a set of functions collectively operate on a bunch of data structures, they have to pass all the data to each other all the time. This is unavoidable in pure structured languages, except if you use global variables, which is frowned upon. Enter object orientation: If instead however, you turn those functions into a class, you can then instead have them all "share" the same variable(s) that's commonly visible to each of them due to paramter passing as shared "state" variables of the object they belong to, hence removing the need to pass the variables around all over the place. To be clear, it might be argued that *any* variable forming part of an object is by definition some sort of state variable for that object, since objects having different values for their data members will by definition be in slightly different states. Finally, the notion of state is commonly used in computer science, so is formalised there, some of those formalisms are mentioned in the other page you reference. Hope that helps somewhat, ask if that's not clear please. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Nov 11 23:52:00 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 11 Nov 2010 22:52:00 +0000 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: On 11 November 2010 22:47, Walter Prins wrote: > Enter object orientation: If instead however, you turn those functions > into a class, you can then instead have them all "share" the same > variable(s) that's commonly visible to each of them due to paramter passing > as shared "state" variables of the object they belong to, hence removing the > need to pass the variables around all over the place. > Sorry I read my own post and the above doesn't read very well. Here's an attempt at improving it: Enter object orientation: If instead however, you turn those functions into a class, you can then instead have them all "share" what would've been paramters or globals as object-level state variables, hence removing the need to pass parameters around all over the place. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Nov 12 00:35:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 10:35:32 +1100 Subject: [Tutor] A deeper explanation of ability to modify list elements in-place In-Reply-To: References: <4CDC2640.4090706@pearwood.info> Message-ID: <4CDC7DC4.6000906@pearwood.info> Serdar Tumgoren wrote: >> In Python, if you have x[0] = Dummy(), the list object x stores the Dummy >> instance itself. > > > I think the above example gets to the source of my confusion. Clearly the > instance remains accessible via x[0], but I somehow never thought of a > specific list index as an obvious "symbol" for -- or reference to -- an > instance. Yes, that's it -- objects can be referenced by *any* , er, reference in any other object. Unfortunately, I'm not aware of any useful synonym for "reference", to distinguish the Python-specific idea of a reference to an object from the plain English meaning of reference, which makes it a little confusing to talk about these things. Named variables are not the only references: you can create anonymous objects inside lists, dicts or sets, or pass instances directly to a function (where of course they get given a name), or by a closure: class Dummy: def __init__(self): print("created %s" % self) def __del__(self): print("deleted %s" % self) def func(): x = Dummy() def inner(): return x return inner f = func() del Dummy, func Despite both the class and func being deleted, the instance x remains alive so long as the inner function remains alive. > I suspect that my confusion stems from the day-to-day routine of > instantiating an object and assigning it to a variable at the same time, > often inside a loop, and then performing additional processing on this > instance *before* storing it in a list or some other container. Of course binding objects to names is a very common use, but it's hardly the only one. > Above, it seems that you're *still* performing simultaneous instantiation > and assignment (from a code perspective), but the "symbol" that you're > assigning to is the list index itself. Not to the index, which would be 0, 1, 2, ... but to the list item. > And that seems to explain why the Dummy instance remains accessible and is > not garbage-collected. Is that a correct understanding? Yes, you've got it! [...] >> There is no way to get access to the underlying pointers from pure Python >> code. From pure Python, pointers don't exist -- Python gives you no way to >> create or access pointers from Python code. All you have access to is >> objects. > > > So is a reference simply a Python-level symbol (ie some collections of > characters accessible from Python code) that corresponds to a pointer, which > in turn points to the location in memory where the object is stored? Now you're digging deep into the implementation... at *some level*, some piece of code must know where in memory the object itself lies. But that level is not Python code. It's hard to talk about these things without confusion. There are various levels: symbols like "x[1]" or "name.attribute" exist in source code. Another level is the byte-code, which has its own symbols for referring to objects. A third level is the implementation ("under the hood") of the language. In the CPython implementation, a reference will be a pointer to a chunk of memory (the object). But of course other implementations, such as PyPy, IronPython, Jython and many others may choose different implementations. But at the top level, no, Python has no idea about the memory location of objects. It is true that CPython uses memory locations for the ID of objects, but that's just a label, you can't do anything with it -- you can't take an address and fetch the object at that address, for instance. And other implementations make other choices: Jython and (I think) IronPython number objects sequentially 1, 2, 3, 4, ... as they are created, and use that as the unique ID, rather than the memory address. -- Steven From steve at pearwood.info Fri Nov 12 02:42:08 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 12:42:08 +1100 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: <4CDC9B70.7000106@pearwood.info> Walter Prins wrote: > Usually however people mean that objects (instances) have state variables, > even when they talk about classes. The trouble is that classes are > themselves objects, and can in fact have their own stat. This is true for Python, and Ruby, but not all languages. > So what is state? Well, your toaster has a "powered" state, it's either "on" > or "off". A better example would be the toaster setting, usually something like 1-5 or thereabouts. -- Steven From steve at pearwood.info Fri Nov 12 03:09:11 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 13:09:11 +1100 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: <4CDCA1C7.1090004@pearwood.info> Emile van Sebille wrote: > "A class is a container for shared state, combined with functions > (methods) that operate on that state. By putting state variables into > member fields, they are accessible to all the methods of the class > without having to be passed as parameters." > > So, by his own definition state variables are parameters. An example might help clarify this. Suppose you have a class with a method that takes various parameters: class Parrot: def talk(self, text, loud, squawk): if squawk: text += " Squawk!!!" if loud: text = text.upper() print(text) Parrot instances don't have any state (which kinda defeats the purpose of using an object, but never mind) but you have to provide extra arguments to the method: polly = Parrot() polly.talk("Polly wants a cracker!", False, True) We can give the instance state and reduce the arguments given to the method: class Parrot: def __init__(self, squawks=True, loud=False): self.squawks = squawks self.loud = loud def talk(self, text): if self.squawks: text += " Squawk!!!" if self.loud: text = text.upper() print(text) polly = Parrot() polly.talk("Polly wants a cracker!") In Python, nearly all objects have state. Even ints and floats have state -- their state is their value. Exceptions are: None NotImplemented direct instances of object (not subclasses of object) and possibly one or two others that I haven't thought of. -- Steven From steve at pearwood.info Fri Nov 12 03:24:23 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 13:24:23 +1100 Subject: [Tutor] variables question. In-Reply-To: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> References: <67B4366BA7B3E14586958A5F4F0697272766441446@IAD2MBX03.mex02.mlsrvr.com> Message-ID: <4CDCA557.4070804@pearwood.info> Jeff Honey wrote: > I have a question about where variables are exposed in python. > > I have a monolothic script with a number of functions defined, can those functions share variables? can I instantiate them outside the function of where they are needed? do they need to be wrapped in quotes, ever? It sounds to me that you've come to Python from bash or shell scripting. Python has no real equivalent to the idea of quoting variable names, and there's never any need to quote variables to protect them from being accidentally evaluated. There's no risk in doing this: x = 1 s = "del x" print(s) and having the variable x accidentally deleted because you neglected to quote the variable s correctly. Nor is there any simple way you can do this: a = "something" b = "a" print($b) # prints "something" although there is eval and exec, both of which are dangerous/advanced and should be avoided unless you really know what you're doing. Aside: the idiomatic way of doing that in Python would be: data = {"a": "something"} key = "a" print(data[key]) # prints "something" [...] > ...what about my python being called from some parent script (something OTHER than python) that instantiates blah and foo FOR me? If you want to gather information from external sources, you need to choose a way to have that information fed into your script. The easiest way is to use command-line arguments. Python has lots of different ways to get to command-line arguments -- see the getopt and optparse modules in the standard library, and the argparse third-party module, and probably others. Another way is with environment variables. Python can read env variables set by the calling process using os.getenv. -- Steven From steve at pearwood.info Fri Nov 12 06:07:03 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 16:07:03 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CDA6624.1070302@pearwood.info> Message-ID: <4CDCCB77.5070404@pearwood.info> Richard D. Moores wrote: > On Wed, Nov 10, 2010 at 01:30, Steven D'Aprano wrote: >> P.S. don't take that as a put down -- you should be pleased that your code is around as fast as Tim Peter's code :) > > Nah. But where is Tim Peter's code? The timeit module was written by Tim Peters. Since then, others have contributed as well, but the basic recipe is his. For those who don't know, Tim Peters, a.k.a. the timbot, is one of the old-time Python demigods. He is responsible for not one, but two, awesomely fast sort routines: the original list.sort() method was his, and then around Python 2.3 (I think) he re-wrote it using a new sort method which is even faster, added stability, and has fewer special cases than the previous version. This sort algorithm has since been adopted by Android and Java 7. -- Steven From stefan_ml at behnel.de Fri Nov 12 07:23:11 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 12 Nov 2010 07:23:11 +0100 Subject: [Tutor] List comprehension question In-Reply-To: <4CDCCB77.5070404@pearwood.info> References: <4CDA6624.1070302@pearwood.info> <4CDCCB77.5070404@pearwood.info> Message-ID: Steven D'Aprano, 12.11.2010 06:07: > Richard D. Moores wrote: >> On Wed, Nov 10, 2010 at 01:30, Steven D'Aprano wrote: > >>> P.S. don't take that as a put down -- you should be pleased that your >>> code is around as fast as Tim Peter's code :) >> >> Nah. But where is Tim Peter's code? > > The timeit module was written by Tim Peters. Since then, others have > contributed as well, but the basic recipe is his. The OP might have been referring to the stackoverflow comment that quotes the algorithm solving the OP's problem: http://stackoverflow.com/questions/1024640/calculating-phik-for-1kn > For those who don't know, Tim Peters, a.k.a. the timbot, is one of the > old-time Python demigods. He is responsible for not one, but two, > awesomely fast sort routines: the original list.sort() method was his, > and then around Python 2.3 (I think) he re-wrote it using a new sort > method which is even faster, added stability, and has fewer special > cases than the previous version. This sort algorithm has since been > adopted by Android and Java 7. It's commonly referred to as "Timsort". http://en.wikipedia.org/wiki/Timsort http://bugs.python.org/file4451/timsort.txt http://corte.si/posts/code/timsort/index.html Stefan From m_stover43812us at yahoo.com Fri Nov 12 07:28:53 2010 From: m_stover43812us at yahoo.com (Michael Stover) Date: Thu, 11 Nov 2010 22:28:53 -0800 (PST) Subject: [Tutor] Grabbing Info from Text files? Message-ID: <561556.85490.qm@web82307.mail.mud.yahoo.com> Hello, I have been getting lost when trying to find the needed information on how to grab information from text files to be used in a python script I am working on. Essentially the script is calling upon other programs to grab specific information about files and putting that information into basic text files. When I say basic I mean basic, each piece of information has its own line such as: InfoOne=? InfoTwo=? Where the ? is a value ranging from 1 character up to 5 (usually numbers), and it is the value I represented with ? that I need to grab. I am hoping it is possible to grab 1 line at a time so variables can be set for use later in my script. I have tried to "decipher" the python documents on this, but honestly, being a dabbler in python I am getting "lost, dazed and confused" as friends would put it. Thankfully this is not for any homework assignments, it is merely a script I am working on for making some repetitive tasks more automated, such as grabbing information about video files, and if needed convert them. I have yet to find a program that does what I am aiming for so I started creating a python script (as python is already installed on my Linux distro). It just seems to have become more complicated that I had hoped, but I am at a point now were I do not want to leave it unfinished. If an example of my script is needed I am more than willing to provide it for clarification of what I am trying to do. Thanks, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From marupalli.charan at gmail.com Fri Nov 12 10:08:41 2010 From: marupalli.charan at gmail.com (marupalli charan) Date: Fri, 12 Nov 2010 14:38:41 +0530 Subject: [Tutor] Tutor Digest, Vol 81, Issue 48 In-Reply-To: References: Message-ID: Re:please, send me programms as a file ( like "word.py" ) for easy understanding of the programmes. On 11/12/10, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Re: A deeper explanation of ability to modify list elements > in-place (Steven D'Aprano) > 2. Re: Creating one file out of all the files in a directory > (Kushal Kumaran) > 3. Re: A deeper explanation of ability to modify list elements > in-place (Serdar Tumgoren) > 4. What is a "state variable"? (Richard D. Moores) > 5. Re: What is a "state variable"? (Emile van Sebille) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 12 Nov 2010 04:41:34 +1100 > From: Steven D'Aprano > To: Python Tutor > Subject: Re: [Tutor] A deeper explanation of ability to modify list > elements in-place > Message-ID: <4CDC2ACE.6030801 at pearwood.info> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Serdar Tumgoren wrote: > >> But I think I see your point. The list object behaves the same as the >> objects stored inside the list. > > Er, surely not... the list object is a list, the objects inside the list > are ints. They do not behave the same. > > > > In other words, the list object is a >> reference to an ordered sequence of object references, and you're >> operating >> on those (referenced) objects rather than copies of the objects when you >> iterate over the list. Is that correct? If so, no doubt there's a simpler >> way to say all that? > > "A list is an ordered sequence of objects. When you iterate over the > list, you see the contents of the list, not copies. Python never copies > objects unless you explicitly tell it to." > > > > -- > Steven > > > > ------------------------------ > > Message: 2 > Date: Thu, 11 Nov 2010 18:37:13 +0530 > From: Kushal Kumaran > To: "Josep M. Fontana" , tutor at python.org > Subject: Re: [Tutor] Creating one file out of all the files in a > directory > Message-ID: <1289480833.13521.5.camel at Nokia-N900> > Content-Type: text/plain; charset="utf-8" > > > ----- Original message ----- >> Hi, >> >> I'm trying to create a script to do the following. I have a directory >> containing hundreds of text files. I need to create a single file with >> the contents of all the files in the directory. Within that file, >> though, I need to create marks that indicate the division between the >> contents of each file that has wound up in that single file. >> > > Your current code adds the marker line to the original files. Is that > intended? > > You can open the output file for writing by passing 'w' as the second > argument to open. You would do this before your directory-walking loop. > Then when you read the contents of any file, just write to your output file > as well, along with your marker line. > >> I got this far but I'm stumped to continue: >> >> ----------------- code-------- >> import os >> path = '/Volumes/DATA/MyPath' >> os.chdir(path) >> file_names = glob.glob('*.txt') > > output_stream = open('outputfilename', 'w') > >> for subdir, dirs, files in os.walk(path): >>? ? ? ? for file in files: >>? ? ? ? ? ? ? ? f = open(file, 'r') >>? ? ? ? ? ? ? ? text = f.readlines() > > output_stream.writelines(text) > output_stream.write('______\n') > >>? ? ? ? ? ? ? ? f.close() >>? ? ? ? ? ? ? ? f = open(file, 'a') >>? ? ? ? ? ? ? ? f.write('\n\n' + '________________________________' + >> '\n') >>? ? ? ? ? ? ? ? f.close() >> > > output_stream.close() > >> ------------ >> >> What's missing here is obvious. This iterates over all the files and >> creates the mark for the division at the end of each file. There is >> nothing, however, to pipe the output of this loop into a new file. >> I've checked the different manuals I own plus some more on the >> internet but I can't figure out how to do what's left. >> >> I could get by with a little help from my Tutor friends. >> > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 3 > Date: Thu, 11 Nov 2010 14:21:22 -0500 > From: Serdar Tumgoren > To: "Steven D'Aprano" > Cc: Python Tutor > Subject: Re: [Tutor] A deeper explanation of ability to modify list > elements in-place > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > First off, thanks for the detailed response! I had a few follow-up questions > below, if you're willing to indulge. Feel free to direct me to RTM some > books on C and the python source code, of course :) > > >> Why? Because the designer of Python, Guido van Rossum, wanted it to be >> possible, and he designed the language so that it would be. >> >> Do you perhaps mean *how* is it possible? >> > Yes indeed, I suppose that is really what I was asking. > > >> >> The use of pointers is an implementation detail for efficiency, and it >> refers to how Python's object model is implemented in C. >> >> It is important not to lose sight of the distinction between the semantics >> of Python objects themselves, and the way that those objects are >> implemented >> in lower-level languages such as C. >> >> In Python, if you have x[0] = Dummy(), the list object x stores the Dummy >> instance itself. > > > I think the above example gets to the source of my confusion. Clearly the > instance remains accessible via x[0], but I somehow never thought of a > specific list index as an obvious "symbol" for -- or reference to -- an > instance. I suspect that my confusion stems from the day-to-day routine of > instantiating an object and assigning it to a variable at the same time, > often inside a loop, and then performing additional processing on this > instance *before* storing it in a list or some other container. > > Above, it seems that you're *still* performing simultaneous instantiation > and assignment (from a code perspective), but the "symbol" that you're > assigning to is the list index itself. > > And that seems to explain why the Dummy instance remains accessible and is > not garbage-collected. Is that a correct understanding? > > >> That's what the code *means* -- create an instance of the Dummy class and >> store it in the list x. But of course for efficiency reasons, and ease of >> programming, the most obvious implementation will be to place the instance >> in the heap somewhere, and keep a pointer to it in the list. How else >> could >> you do it? You could store the entire object in the list, but that would >> be >> terribly inefficient. > > > > But it could be done -- you could, with difficulty, implement Python in a >> language like Fortran 77 (which has no dynamic memory allocation, and >> therefore no pointers), or in Haskell, which is purely functional. Or you >> could come up with a (slow, inefficient) implementation which moved around >> large instance objects instead of small pointers. > > > There is no way to get access to the underlying pointers from pure Python >> code. From pure Python, pointers don't exist -- Python gives you no way to >> create or access pointers from Python code. All you have access to is >> objects. > > > So is a reference simply a Python-level symbol (ie some collections of > characters accessible from Python code) that corresponds to a pointer, which > in turn points to the location in memory where the object is stored? > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > > > ------------------------------ > > Message: 4 > Date: Thu, 11 Nov 2010 12:11:34 -0800 > From: "Richard D. Moores" > To: tutor at python.org > Subject: [Tutor] What is a "state variable"? > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > The term comes up in the 2nd section of > > > didn't help. > > k = 23 > > Is k then a state variable in that its state is 23? What sorts of > variables are, and are not, state variables? > > The concept of a state variable seems central to Kent's article. If > only I knew exactly what it was. > > Thanks, > > Dick Moores > > > ------------------------------ > > Message: 5 > Date: Thu, 11 Nov 2010 13:22:25 -0800 > From: Emile van Sebille > To: tutor at python.org > Subject: Re: [Tutor] What is a "state variable"? > Message-ID: > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 11/11/2010 12:11 PM Richard D. Moores said... >> The term comes up in the 2nd section of >> >> >> didn't help. >> >> k = 23 >> >> Is k then a state variable in that its state is 23? What sorts of >> variables are, and are not, state variables? >> >> The concept of a state variable seems central to Kent's article. If >> only I knew exactly what it was. > > > From the article, > > "A class is a container for shared state, combined with functions > (methods) that operate on that state. By putting state variables into > member fields, they are accessible to all the methods of the class > without having to be passed as parameters." > > So, by his own definition state variables are parameters. > > Emile > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 81, Issue 48 > ************************************* > From alan.gauld at btinternet.com Fri Nov 12 10:23:38 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Nov 2010 09:23:38 -0000 Subject: [Tutor] A deeper explanation of ability to modify list elementsin-place References: <4CDC2640.4090706@pearwood.info> Message-ID: "Serdar Tumgoren" wrote > So is a reference simply a Python-level symbol (ie some collections > of > characters accessible from Python code) that corresponds to a > pointer, which > in turn points to the location in memory where the object is stored? Or to think of it in Python terms a reference or name is simply a key in a dictionary, with one such dictionary per namespace. When you do a dir() you are asking for the keys - the names - in that namespace. The objects that the names refer to are the values in the dictionary. But then it gets circular since the dictionary does not store the objects, just references to the objects - but those references could be pointers depending on implementation :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Nov 12 10:27:55 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Nov 2010 09:27:55 -0000 Subject: [Tutor] What is a "state variable"? References: Message-ID: "Richard D. Moores" wrote > Is k then a state variable in that its state is 23? What sorts of > variables are, and are not, state variables? > > The concept of a state variable seems central to Kent's article. If > only I knew exactly what it was. First, do you understand what ste is in mathematical/computing terms? That is critical to understanding what state variables are? For example if I say that the state of any object can be represented by a vector whose values correspond to the collected set of variables of the object, does that make sense? If not, we need to go back to consider what state is and why it is important in computing. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Nov 12 10:32:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Nov 2010 09:32:48 -0000 Subject: [Tutor] Tutor Digest, Vol 81, Issue 48 References: Message-ID: "marupalli charan" wrote > Re:please, send me programms as a file ( like "word.py" ) for easy > understanding of the programmes. Please read the instructions below and follow them. And please remove extraneous content. That way you asre more likely to get a listening ear. You have many sample python scripts in your python distribution if you want to study code. There are also more complex examples on Sourceforge. Search for projects using Python. > On 11/12/10, tutor-request at python.org > wrote: >> Send Tutor mailing list submissions to >> tutor at python.org >> >> To subscribe or unsubscribe via the World Wide Web, visit >> http://mail.python.org/mailman/listinfo/tutor >> or, via email, send a message with subject or body 'help' to >> tutor-request at python.org >> >> You can reach the person managing the list at >> tutor-owner at python.org >> >> When replying, please edit your Subject line so it is more specific >> than "Re: Contents of Tutor digest..." >> >> >> Today's Topics: -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cwitts at compuscan.co.za Fri Nov 12 10:50:41 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Fri, 12 Nov 2010 11:50:41 +0200 Subject: [Tutor] Grabbing Info from Text files? In-Reply-To: <561556.85490.qm@web82307.mail.mud.yahoo.com> References: <561556.85490.qm@web82307.mail.mud.yahoo.com> Message-ID: <4CDD0DF1.20407@compuscan.co.za> On 12/11/2010 08:28, Michael Stover wrote: > Hello, > I have been getting lost when trying to find the needed information on > how to grab information from text files to be used in a python script > I am working on. Essentially the script is calling upon other programs > to grab specific information about files and putting that information > into basic text files. When I say basic I mean basic, each piece of > information has its own line such as: > InfoOne=? > InfoTwo=? > Where the ? is a value ranging from 1 character up to 5 (usually > numbers), and it is the value I represented with ? that I need to > grab. I am hoping it is possible to grab 1 line at a time so variables > can be set for use later in my script. > I have tried to "decipher" the python documents on this, but honestly, > being a dabbler in python I am getting "lost, dazed and confused" as > friends would put it. > Thankfully this is not for any homework assignments, it is merely a > script I am working on for making some repetitive tasks more > automated, such as grabbing information about video files, and if > needed convert them. I have yet to find a program that does what I am > aiming for so I started creating a python script (as python is already > installed on my Linux distro). It just seems to have become more > complicated that I had hoped, but I am at a point now were I do not > want to leave it unfinished. If an example of my script is needed I am > more than willing to provide it for clarification of what I am trying > to do. > Thanks, > Mike > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If you can ensure that a header is written to those text files so they're in format such as [SectionHeader] InfoOne=Value InfoTwo=Value ... then you can take a look at the ConfigParser module where you would simply read the file and all your values would be read in in neat pairs. $ cat test.conf [Blah] OptOne=1 OptTwo=2 OptThree=3 $ python Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ConfigParser import ConfigParser >>> cfg = ConfigParser() >>> cfg.read('test.conf') ['test.conf'] >>> cfg.items('Blah') [('optone', '1'), ('optthree', '3'), ('opttwo', '2')] The other way to do it yourself is to iterate over the lines in the file, split the key and value and store it in a dictionary for later use. -- Kind Regards, Christian Witts From steve at pearwood.info Fri Nov 12 11:11:04 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Nov 2010 21:11:04 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> Message-ID: <4CDD12B8.6080605@pearwood.info> Richard D. Moores wrote: > I find using that at the interactive prompt a bit onerous -- lots of > copy and pasting. And doubly so when comparing times for 2 or more > functions. Does your Python not support readline? Normally, if you press UP ARROW or DOWN ARROW, Python will cycle through the previous interpreter lines. Another approach is to write helper functions, or use string interpolation, to make it easy to re-use code: setup = "from __main__ import %s as func" test = "func(1000)" t1 = Timer(test, setup % "my_func") t1 = Timer(test, setup % "your_func") A third approach might be to treat your testing as a script. Put all your test code in a module, and then run it: python time_test.py > The timeit doc gave me the obvious idea of how to avoid the prompt and > also easily compare the times of 2 or more functions. I'd like to know > if doing it this way is correct: Please see > You're vulnerable to statistical outliers (which are remarkably common on multi-tasking operating systems!) cause by the OS calling some other program in the middle of yours. Call each time test three or five times, and use the smallest. > Huh. Just realized that this timing method doesn't include the 5 > repeats called for by Steven's method. So how about using a for loop? > As in . You're still re-inventing the wheel. timeit already includes a method for doing exactly that: repeat. From the documentation: def repeat(self, repeat=default_repeat, number=default_number): """Call timeit() a few times. This is a convenience function that calls the timeit() repeatedly, returning a list of results. ... 97% of the time you think you want to call timeit, you actually should be calling min(timer.repeat()) instead. -- Steven From rdmoores at gmail.com Fri Nov 12 12:15:17 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 03:15:17 -0800 Subject: [Tutor] List comprehension question In-Reply-To: <4CDD12B8.6080605@pearwood.info> References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> Message-ID: On Fri, Nov 12, 2010 at 02:11, Steven D'Aprano wrote: > Richard D. Moores wrote: > >> I find using that at the interactive prompt a bit onerous -- lots of >> copy and pasting. And doubly so when comparing times for 2 or more >> functions. > > Does your Python not support readline? Normally, if you press UP ARROW or > DOWN ARROW, Python will cycle through the previous interpreter lines. Do you mean my IDE? IDLE does that with Alt+P and Alt+N. I'm dealing with multi-line functions, not single lines. If I paste a function at the prompt, IDLE will bring the whole thing back with Alt+P. Problem is, IDLE isn't my IDE -- Wing is. > Another approach is to write helper functions, or use string interpolation, > to make it easy to re-use code: > > setup = "from __main__ import %s as func" > test = "func(1000)" > t1 = Timer(test, setup % "my_func") > t1 = Timer(test, setup % "your_func") > > A third approach might be to treat your testing as a script. Put all your > test code in a module, and then run it: > > python time_test.py OK, but why can't I do what the timeit doc suggests, only put 2 or more functions in the file, as I do here: def test(): "Stupid test function" L = [] for i in range(100): L.append(i) if __name__=='__main__': from timeit import Timer t = Timer("test()", "from __main__ import test") print t.timeit() >> The timeit doc gave me the obvious idea of how to avoid the prompt and >> also easily compare the times of 2 or more functions. I'd like to know >> if doing it this way is correct: Please see >> > > You're vulnerable to statistical outliers (which are remarkably common on > multi-tasking operating systems!) cause by the OS calling some other program > in the middle of yours. Call each time test three or five times, and use the > smallest. Sure, I do that with the for loops, don't I? >> Huh. Just realized that this timing method doesn't include the 5 >> repeats called for by Steven's method. So how about using a for loop? >> As in . > > You're still re-inventing the wheel. timeit already includes a method for > doing exactly that: repeat. From the documentation: > > ? ?def repeat(self, repeat=default_repeat, number=default_number): > ? ? ? ?"""Call timeit() a few times. > > ? ? ? ?This is a convenience function that calls the timeit() > ? ? ? ?repeatedly, returning a list of results. ... I'm sorry, Steven, but I could you revise this code to use repeat=5 instead of the for loop? I can't see how to do it. if __name__=='__main__': from timeit import Timer for y in range(5): t = Timer("proper_divisors_sum1(500000)", "from __main__ import proper_divisors_sum") print round(t.timeit(number=10000),3) Thanks, Dick From rdmoores at gmail.com Fri Nov 12 12:35:19 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 03:35:19 -0800 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: On Fri, Nov 12, 2010 at 01:27, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> Is k then a state variable in that its state is 23? What sorts of >> variables are, and are not, state variables? >> >> The concept of a state variable seems central to Kent's article. If >> only I knew exactly what it was. > > First, do you understand what ste is in mathematical/computing terms? > That is critical to understanding what state variables are? > > For example if I say that the state of any object can be represented > by a vector whose values correspond to the collected set of variables > of the object, does that make sense? No. Not the vector idea. Sorry. > If not, we need to go back to consider what state is and why > it is important in computing. From smokefloat at gmail.com Fri Nov 12 14:08:16 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 08:08:16 -0500 Subject: [Tutor] Building input for a function call Message-ID: Hey Buddy Pals, In the below *function*(if you can call it that yet:) I'm trying to do the following: interpolate this string: 'OptionMenu(self.frame,self.var,'%s','%s')' with this list turned into variables: ['default1', 'default2'] which would become: self.default1 = 'default1' self.default2 = 'default2' So that I have: OptionMenu(self.frame,self.var,self.default1,self.default2) or even: OptionMenu(self.frame,self.var,'default1','default2') Starting from the top: from self.obtup I obtain a tuple: (7, 8) I then use the tuple to identify an object the numbers in self.obtup represent, and build a list from this in self.list: ['default1', 'default2'] I then build a string for a later to be used menu with: self.string = 'OptionMenu(self.frame,self.var' + str(self.listlen * ',%s') + ')' which gives: self.string = OptionMenu(self.frame,self.var,%s,%s) And then build a variable list self.list2 = ['self.default1 = ', 'self.default2 = '] So that I have: self.default1 = self.default2 = Then append to those the variables they represent so that I have self.default1 = 'default1' self.default2 = 'default2' When I get to the step above, trying to use eval()(the data is restricted to variable names, but I know a misnamed with a invalid character could cause problems) in a loop, so that it uses the combined as a variable, but get an error for the '='. I've tried several different methods this seemed like the best course, but maybe not. *Note files self.f1 and self.f2 are temporary holders for: OptionMenu(self.frame,self.var,'%s','%s') = where the %s's should be replaced with the vars or strings. and self.f2 is 'self.default1 = ', 'self.default2 = ' Which could probably be handled a better way than a file. @trace def obOpMenu(self): import time self.oblist = self.canvas.find_withtag('object') print self.oblist self.list = [] for item in self.oblist: self.itemname = self.canvas.gettags(item) if self.itemname[1] != 'default': self.list.append(self.itemname[1]) print self.list self.f1 = open('/home/david/pythonfiles/pythonscripts/roughdraftapps/kubit_kaaba/obmenu.txt','w') self.f2 = open('/home/david/pythonfiles/pythonscripts/roughdraftapps/kubit_kaaba/obmenuvar.txt','w') self.listlen = len(self.list) self.string = 'OptionMenu(self.frame,self.var' + str(self.listlen * ",'%s'") + ')' self.list2 = [] for line in self.list: self.list2.append('self.%s = ' % (line)) print self.string, self.list2 self.count = 0 for num in range(len(self.list)): print self.list2[num] self.f2.write(str(self.list2).strip('[]')) self.f2.close() #time.sleep(1) #self.f2 = open('/home/david/pythonfiles/pythonscripts/roughdraftapps/kubit_kaaba/obmenuvar.txt','r') #self.f1.write(self.string % self.list2) self.f1.close() #time.sleep(1) #self.f1 = open('/home/david/pythonfiles/pythonscripts/roughdraftapps/kubit_kaaba/obmenu.txt','r') ''' #if len(str(self.oblist)) > 2: for field in self.f1.read(): self.abc = q.strip().split( "," ) #self.var = StringVar(root) #self.var.set(self.list[0]) #self.optionmenu = self.f1.read() #self.optionmenu.grid(row = 1,column = 2) ''' Thanks, David From smokefloat at gmail.com Fri Nov 12 14:15:24 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 08:15:24 -0500 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> Message-ID: > ? ? ? ?repeatedly, returning a list of results. ... > > I'm sorry, Steven, but I could you revise this code to use repeat=5 > instead of the for loop? I can't see how to do it. >>> help(timeit.Timer repeat(self, repeat=3, number=1000000) | Call timeit() a few times. | | This is a convenience function that calls the timeit() | repeatedly, returning a list of results. The first argument | specifies how many times to call timeit(), defaulting to 3; | the second argument specifies the timer argument, defaulting | to one million. | | Note: it's tempting to calculate mean and standard deviation | from the result vector and report these. However, this is not | very useful. In a typical case, the lowest value gives a | lower bound for how fast your machine can run the given code | snippet; higher values in the result vector are typically not | caused by variability in Python's speed, but by other | processes interfering with your timing accuracy. So the min() | of the result is probably the only number you should be | interested in. After that, you should look at the entire | vector and apply common sense rather than statistics. > > if __name__=='__main__': > ? ?from timeit import Timer > ? ?for y in range(5): > ? ? ? ?t = Timer("proper_divisors_sum1(500000)", "from __main__ > import proper_divisors_sum") > ? ? ? ?print round(t.timeit(number=10000),3) > > Thanks, > > Dick > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From smokefloat at gmail.com Fri Nov 12 14:16:27 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 08:16:27 -0500 Subject: [Tutor] Building input for a function call In-Reply-To: References: Message-ID: Apologies, forgot to add I'm using 2.6.4 on ubuntu 9.10 From jeffh at pona.net Fri Nov 12 14:21:18 2010 From: jeffh at pona.net (Jeff Honey) Date: Fri, 12 Nov 2010 08:21:18 -0500 Subject: [Tutor] variables question. Message-ID: <67B4366BA7B3E14586958A5F4F069727276644144B@IAD2MBX03.mex02.mlsrvr.com> Steven D'Aprano, et al, Thanks everyone for the thorough explanations on variable use and scope in Python. It was enlightening...and sometimes confusing, but I'm working on that. It just points out all the new things I have yet to learn about the language. -- ?????????????????? ? kyoboku kazeoshi ? ?????????????????? From rdmoores at gmail.com Fri Nov 12 15:41:48 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 06:41:48 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> Message-ID: On Fri, Nov 12, 2010 at 05:15, David Hutto wrote: >> ? ? ? ?repeatedly, returning a list of results. ... >> >> I'm sorry, Steven, but I could you revise this code to use repeat=5 >> instead of the for loop? I can't see how to do it. > >>>> help(timeit.Timer > > ?repeat(self, repeat=3, number=1000000) > ?| ? ? ?Call timeit() a few times. > ?| > ?| ? ? ?This is a convenience function that calls the timeit() > ?| ? ? ?repeatedly, returning a list of results. ?The first argument > ?| ? ? ?specifies how many times to call timeit(), defaulting to 3; > ?| ? ? ?the second argument specifies the timer argument, defaulting > ?| ? ? ?to one million. > ?| > ?| ? ? ?Note: it's tempting to calculate mean and standard deviation > ?| ? ? ?from the result vector and report these. ?However, this is not > ?| ? ? ?very useful. ?In a typical case, the lowest value gives a > ?| ? ? ?lower bound for how fast your machine can run the given code > ?| ? ? ?snippet; higher values in the result vector are typically not > ?| ? ? ?caused by variability in Python's speed, but by other > ?| ? ? ?processes interfering with your timing accuracy. ?So the min() > ?| ? ? ?of the result is probably the only number you should be > ?| ? ? ?interested in. ?After that, you should look at the entire > ?| ? ? ?vector and apply common sense rather than statistics. Look, I've already shown I know where the docs are, and have read them. I don't understand how to use repeat() with my code. Wasn't that clear to you? From wangoloj at yahoo.com Fri Nov 12 15:45:21 2010 From: wangoloj at yahoo.com (Wangolo Joel) Date: Fri, 12 Nov 2010 14:45:21 +0000 (GMT) Subject: [Tutor] Tutor Digest, Vol 81, Issue 35 In-Reply-To: Message-ID: <826058.98716.qm@web29715.mail.ird.yahoo.com> Hello tutor i want to thnak you for that efort but it's enough . I no longer want? you messages a bout python sorry .The reason is my conputer is infected with alot of TROJANs and WORMS , VIRUSES,SPYWARES and all to me comes from you poeple so i just want to a void you. ? I will learn python through the PDF i Read and the Google python class vidoe than you viruses destroying my PC I NO LONGER WANT YOU MESSAGES DON'T REPLY ME -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Fri Nov 12 16:13:49 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 10:13:49 -0500 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> Message-ID: Apologies, missed that part. Didn't mean to seem rude. import timeit def anyName(): pass for num in range(10): t = timeit.Timer('anyName()','from __main__ import anyName') print t.repeat(repeat=5) #or import timeit def anyName(): pass t = timeit.Timer('anyName()','from __main__ import anyName') print t.repeat(repeat=5) If I get the gist of what you're asking. From stefan_ml at behnel.de Fri Nov 12 16:28:18 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 12 Nov 2010 16:28:18 +0100 Subject: [Tutor] Tutor Digest, Vol 81, Issue 35 In-Reply-To: <826058.98716.qm@web29715.mail.ird.yahoo.com> References: <826058.98716.qm@web29715.mail.ird.yahoo.com> Message-ID: Wangolo Joel, 12.11.2010 15:45: > I NO LONGER WANT YOU MESSAGES > DON'T REPLY ME Nice try. Stefan PS: You can unsubscribe at any time by following the instructions on the mailing list web site. See the footer of any message sent to this list. From delegbede at dudupay.com Fri Nov 12 16:05:26 2010 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Fri, 12 Nov 2010 15:05:26 +0000 Subject: [Tutor] Tutor Digest, Vol 81, Issue 35 In-Reply-To: <826058.98716.qm@web29715.mail.ird.yahoo.com> References: <826058.98716.qm@web29715.mail.ird.yahoo.com> Message-ID: <1547071685-1289574345-cardhu_decombobulator_blackberry.rim.net-591999257-@bda2349.bisx.produk.on.blackberry> Hi Joel, To start with, I sincerely appreciate your concern and I am deeply sorry your computer is so infected. Having said that, I think it is unfair to pile all the blames and as a matter of fact, any at all, on this group. That is very unfair to say the least. I don't have an idea of how long you have been on this mailing list but I am quite sure you are not the first to subscribe and you can't be the last. It therefore bothers me that you are the onlt person I have heard say such a terrible thing about this group despite all measures in place to avoid sending malicious elements. I hope you are aware this group doesn't allow attachments except you are suggesting the viruses you are talking about are the letters and numerals in the mails. That then underscores your knowledge as an IT person. Second, you had an option to stick with your PDF and google stuff before coming on this mailing list. If you are all of a sudden attached to your PDF again, it ia matured enough to unsubscribe and be thankful for the things you have learnt in here. While I hope you would have a change of mind and apologise for your very harsh and false accusations, I hope you would also understand that everybody here despite our different backgrounds have gone thus far because we play by the rules and we are interested in not only learning python but teaching too and making everyone smile. Have a great day. Regards Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Wangolo Joel Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Fri, 12 Nov 2010 14:45:21 To: Subject: Re: [Tutor] Tutor Digest, Vol 81, Issue 35 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From rdmoores at gmail.com Fri Nov 12 17:00:23 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 08:00:23 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> Message-ID: On Fri, Nov 12, 2010 at 07:13, David Hutto wrote: > import timeit > > > def anyName(): > ? ? ? ?pass > > t = timeit.Timer('anyName()','from __main__ import anyName') > print t.repeat(repeat=5) > > > If I get the gist of what you're asking. > Yes. That's it! Thank you! And if I don't want the default number of 1 million, I can use print t.repeat(repeat=5,number=3000) See where I compare speeds of 2 functions. Dick From patty at cruzio.com Fri Nov 12 18:09:02 2010 From: patty at cruzio.com (Patty) Date: Fri, 12 Nov 2010 09:09:02 -0800 Subject: [Tutor] Tutor Digest, Vol 81, Issue 35 References: <826058.98716.qm@web29715.mail.ird.yahoo.com> <1547071685-1289574345-cardhu_decombobulator_blackberry.rim.net-591999257-@bda2349.bisx.produk.on.blackberry> Message-ID: <36B1B9A902DB4D268EF56CD483402104@mycomputer> Hi - I just wanted to comment that my Windows XP system hasn't found any threats like this coming from the Python list emails. I also have a netbook with Windows 7 Starter and no problems there either. I am using AVG 9.0.869 on both systems which is *Great* for security and if a threat is found, it will give you the email with just the header and a note in the body that AVG didn't allow the message through because it detected a virus or malicious something or other. Patty ----- Original Message ----- From: To: "tutor" Sent: Friday, November 12, 2010 7:05 AM Subject: Re: [Tutor] Tutor Digest, Vol 81, Issue 35 > Hi Joel, > > To start with, I sincerely appreciate your concern and I am deeply sorry > your computer is so infected. > > Having said that, I think it is unfair to pile all the blames and as a > matter of fact, any at all, on this group. That is very unfair to say the > least. > > I don't have an idea of how long you have been on this mailing list but I > am quite sure you are not the first to subscribe and you can't be the > last. > It therefore bothers me that you are the onlt person I have heard say such > a terrible thing about this group despite all measures in place to avoid > sending malicious elements. I hope you are aware this group doesn't allow > attachments except you are suggesting the viruses you are talking about > are the letters and numerals in the mails. That then underscores your > knowledge as an IT person. > > Second, you had an option to stick with your PDF and google stuff before > coming on this mailing list. If you are all of a sudden attached to your > PDF again, it ia matured enough to unsubscribe and be thankful for the > things you have learnt in here. > > While I hope you would have a change of mind and apologise for your very > harsh and false accusations, I hope you would also understand that > everybody here despite our different backgrounds have gone thus far > because we play by the rules and we are interested in not only learning > python but teaching too and making everyone smile. > > Have a great day. > > Regards > Sent from my BlackBerry wireless device from MTN > > -----Original Message----- > From: Wangolo Joel > Sender: tutor-bounces+delegbede=dudupay.com at python.org > Date: Fri, 12 Nov 2010 14:45:21 > To: > Subject: Re: [Tutor] Tutor Digest, Vol 81, Issue 35 > > _______________________________________________ > 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 smokefloat at gmail.com Fri Nov 12 19:21:40 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 13:21:40 -0500 Subject: [Tutor] Building input for a function call In-Reply-To: References: Message-ID: This is a more precise question, the above was after trying different methods, and it got a little confusing. Why in the below does using in line 12:self.objectsvars = 'menuitemhere','menuitemhere','menuitemhere','menuitemhere', not work, but placing 'menuitemhere','menuitemhere','menuitemhere','menuitemhere' in line 17 directly work? def obOpMenu(self): print 'Dummy' #This is my tony robins help import time self.oblist = self.canvas.find_withtag('object') print self.oblist self.list = [] for item in self.oblist: self.itemname = self.canvas.gettags(item) if self.itemname[1] != 'default': self.list.append(self.itemname[1]) print self.list self.objectsvars = 'menuitemhere','menuitemhere','menuitemhere','menuitemhere' print type(self.objectsvars[0]) self.var = StringVar(self.root) self.var.set(self.objectsvars[0]) self.optionmenu = OptionMenu(self.frame,self.var,self.objectsvars) self.optionmenu.grid(row = 1,column = 2) Hope that's clearer:) From evert.rol at gmail.com Fri Nov 12 20:09:13 2010 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 12 Nov 2010 20:09:13 +0100 Subject: [Tutor] Building input for a function call In-Reply-To: References: Message-ID: <4AC0332B-850A-4292-909B-5C81CDCDD39C@gmail.com> > This is a more precise question, the above was after trying different methods, > and it got a little confusing. > > Why in the below does using in line 12:self.objectsvars = > 'menuitemhere','menuitemhere','menuitemhere','menuitemhere', not work, > but placing 'menuitemhere','menuitemhere','menuitemhere','menuitemhere' > in line 17 directly work? Singled out the two lines for clarity: > 12: self.objectsvars = 'menuitemhere','menuitemhere','menuitemhere','menuitemhere' > 17: self.optionmenu = OptionMenu(self.frame,self.var,self.objectsvars) Because in the first case, you're passing 3 items to OptionMene: self.frame, self.var & a tuple. The tuple itself contains four items, but it is still a single item as passed to OptionMenu. In the second case, you're passing 6 items total. If you want to use self.objectsvars, using the asterisk notation to expand your list or tuple: OptionMenu(self.frame, self.var, *self.objectsvars) Though I believe (haven't tried) that that actually doesn't work (depending on how OptionMenu.__init_ is defined), and you may need to pack everything into a single tuple, and expand that: OptionMenu( *((self.frame, self.var) + self.objects)) So in that case, I'm adding a 2-tuple and a 4-tuple, and then expanding that. I need extra parentheses, otherwise only the 2-tuple gets expanded. Which of the above two cases you need, depends on how OptionMenu.__init__ is declared: def __init__(self, frame, var, *args) should allow for the first, while def __init__(self, *args) will work in the second case, since frame and var aren't picked up separately when calling the function. Google and read around for 'Python args kwargs', if this went somewhat over your head. Or just try and play with it some more. Cheers, Evert > > > def obOpMenu(self): > print 'Dummy' #This is my tony robins help > import time > self.oblist = self.canvas.find_withtag('object') > print self.oblist > self.list = [] > for item in self.oblist: > self.itemname = self.canvas.gettags(item) > if self.itemname[1] != 'default': > self.list.append(self.itemname[1]) > print self.list > self.objectsvars = 'menuitemhere','menuitemhere','menuitemhere','menuitemhere' > print type(self.objectsvars[0]) > self.var = StringVar(self.root) > self.var.set(self.objectsvars[0]) > > self.optionmenu = OptionMenu(self.frame,self.var,self.objectsvars) > self.optionmenu.grid(row = 1,column = 2) > > > Hope that's clearer:) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From rhettbrindle at yahoo.com Fri Nov 12 20:58:58 2010 From: rhettbrindle at yahoo.com (R Johnson) Date: Fri, 12 Nov 2010 11:58:58 -0800 (PST) Subject: [Tutor] 'pydoc' is not recognized as an internal or external command, ... Message-ID: <326390.17201.qm@web112713.mail.gq1.yahoo.com> Hello All, I'm currently attempting to work my way through Zed Shaw's "Learn Python the Hard Way" (suggested by co-workers) and have come across an instruction to: 1. In Terminal where you normally run python to run your scripts, type: pydoc raw_input. Read what it says. So in a terminal, at the command prompt I type: pydoc raw_input. I'm going out on a limb here - I don't believe the following is what I was supposed to read: 'pydoc' is not recognized as an internal or external command, operable program or batch file. The word pydoc is in single quotes. So, I go back to the terminal and type: python Then I type: pydoc raw_input The computer spits back: File "", line1 pydoc raw_input SyntaxError: invalid syntax (There is a carrot symbol under the "t" of input.) What I've done so far to figure it out: 1. Searching Google and here on the tutor mailing list. I cannot find this exact same phrase - there are many similar ones on the two pages of returned search results, but not the exact same phrase. I assume from the verbiage that I don't have "something" installed or I have installed "something" incorrectly but what exactly I cannot tell. 2. Searching this page: http://docs.python.org/library/pydoc.html This page contains lots of great information if you already know what you are doing but not information for how to start or troubleshoot "pydoc." For one as new as myself this might as well be in a dead language that has no Rosetta Stone. 3. Picked the brains of the co-workers who recommended the book - they are as confused as me as to why it's not working. They don't seem to have needed it. Any suggestions? Thank you, R. -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Fri Nov 12 21:20:24 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 15:20:24 -0500 Subject: [Tutor] 'pydoc' is not recognized as an internal or external command, ... In-Reply-To: <326390.17201.qm@web112713.mail.gq1.yahoo.com> References: <326390.17201.qm@web112713.mail.gq1.yahoo.com> Message-ID: For what you're looking for you could use: >>>help(raw_input) In the python terminal,meaning type python first. For pydoc on ubuntu in the command line, pydoc -p 1234 and then take your browser to http://localhost:1234, you might need to select the work offline mode. On windows IIRC it's about the same. I can check if you need it. From smokefloat at gmail.com Fri Nov 12 21:33:34 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 15:33:34 -0500 Subject: [Tutor] Building input for a function call In-Reply-To: <4AC0332B-850A-4292-909B-5C81CDCDD39C@gmail.com> References: <4AC0332B-850A-4292-909B-5C81CDCDD39C@gmail.com> Message-ID: > > Singled out the two lines for clarity: >> 12: ? ? ? ? ? self.objectsvars = 'menuitemhere','menuitemhere','menuitemhere','menuitemhere' >> 17: ? ? ? ? ? self.optionmenu = OptionMenu(self.frame,self.var,self.objectsvars) > > > Because in the first case, you're passing 3 items to OptionMene: self.frame, self.var & a tuple. The tuple itself contains four items, but it is still a single item as passed to OptionMenu. I found out it was a tuple after I posted, which is why the error. It becomes OptionMenu(self.frame,self.var, ('menuitemhere' , 'menuitemhere' , 'menuitemhere' , 'menuitemhere')) This is how it's supposed to be init'd: OptionMenu(self.frame,self.var, 'menuitemhere' , 'menuitemhere' , 'menuitemhere' , 'menuitemhere') Where the args are a series of single strings, the first two are self.frame(which is the parentframe and self.var(which is a starting reference for the menu) > In the second case, you're passing 6 items total. > It can be as many as I need, in the first email I was trying to state that I have a list of random length that has to be placed into those end values as args. > If you want to use self.objectsvars, using the asterisk notation to expand your list or tuple: > OptionMenu(self.frame, self.var, *self.objectsvars) by expand, do you mean remove the tuple value, and leave the contents(I'll try either way) > > Though I believe (haven't tried) that that actually doesn't work (depending on how OptionMenu.__init_ is defined), and you may need to pack everything into a single tuple, and expand that: > OptionMenu( *((self.frame, self.var) + self.objects)) > > So in that case, I'm adding a 2-tuple and a 4-tuple, and then expanding that. I need extra parentheses, otherwise only the 2-tuple gets expanded. In think this would work in the apply() method I tried, which took a tuple argument, but I didn't need backward compatability, so I was using the function outright. Again I'll see if that will work. > > Which of the above two cases you need, depends on how OptionMenu.__init__ is declared: > > ?def __init__(self, frame, var, *args) > > should allow for the first, while > > ?def __init__(self, *args) > > will work in the second case, since frame and var aren't picked up separately when calling the function. > > > Google and read around for 'Python args kwargs', if this went somewhat over your head. Or just try and play with it some more. Probably both, but I don't think that's the appropriate search term I need at this point. This is my current revision which writes a python file then calls the function, but not quite right yet: def obOpMenu(self): print 'Dummy' #This is my tony robins help self.oblist = self.canvas.find_withtag('object') print self.oblist self.list = [] for item in self.oblist: self.itemname = self.canvas.gettags(item) if self.itemname[1] != 'default': self.list.append(self.itemname[1]) print self.list self.objectsvars = str(self.list).strip('[]') print self.objectsvars self.listlen = len(self.list) self.var = StringVar(self.root) self.var.set(self.objectsvars[0]) self.f1 = open('/home/david/pythonfiles/pythonscripts/roughdraftapps/kubit_kaaba/other.py','w') self.f1.write("""from Tkinter import * def thisDef(frame,var): optionmenu = OptionMenu(frame,var,%s) return optionmenu""" % (str(self.list).strip('[]'))) self.f1.close() self.optionmenu = thisDef(self.frame,self.var) print self.optionmenu,'*' From smokefloat at gmail.com Fri Nov 12 22:09:12 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 16:09:12 -0500 Subject: [Tutor] Building input for a function call In-Reply-To: References: <4AC0332B-850A-4292-909B-5C81CDCDD39C@gmail.com> Message-ID: Fixed with: def obOpMenu(self): self.oblist = self.canvas.find_withtag('object') self.list = [] for item in self.oblist: self.itemname = self.canvas.gettags(item) if self.itemname[1] != 'default': self.list.append(self.itemname[1]) self.objectsvars = str(self.list).strip('[]') self.var = StringVar(self.root) self.var.set(self.objectsvars[0]) self.f1 = open('/home/david/pythonfiles/pythonscripts/roughdraftapps/kubit_kaaba/other.py','w') self.f1.write("""from Tkinter import * def thisDef(frame,var): optionmenu = OptionMenu(frame,var,%s) optionmenu.grid(row = 1,column = 2) return optionmenu""" % (str(self.list).strip('[]'))) self.f1.close() from other import * self.optionmenu = thisDef(self.frame,self.var) From steve at pearwood.info Sat Nov 13 00:26:17 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Nov 2010 10:26:17 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> Message-ID: <4CDDCD19.2080002@pearwood.info> Richard D. Moores wrote: > OK, but why can't I do what the timeit doc suggests, only put 2 or > more functions in the file, as I do here: > > > def test(): > "Stupid test function" > L = [] > for i in range(100): > L.append(i) > > if __name__=='__main__': > from timeit import Timer > t = Timer("test()", "from __main__ import test") > print t.timeit() There's nothing wrong with that, except that running the test *once* (as you do) is subject to greater chance fluctuations than running it multiple times: change the last line to: print min(t.repeat()) Note that you don't *have* to do this, the world will not end if you don't, but your timing results will be just a little more accurate if you do. If you want to time multiple functions, just use multiple timer objects: t1 = Timer("test()", "from __main__ import test") t2 = Timer("spam()", "from module import spam") t3 = Timer("ham()", "from module import ham") > I'm sorry, Steven, but I could you revise this code to use repeat=5 > instead of the for loop? I can't see how to do it. You don't need to choose repeat=5. The default is 3, but you can specify any number you like. I just like 5 :) > if __name__=='__main__': > from timeit import Timer > for y in range(5): > t = Timer("proper_divisors_sum1(500000)", "from __main__ > import proper_divisors_sum") > print round(t.timeit(number=10000),3) if __name__=='__main__': from timeit import Timer t = Timer("proper_divisors_sum(500000)", "from __main__ import proper_divisors_sum") best = t.repeat(number=10000, repeat=5) print round(best, 3) -- Steven From steve at pearwood.info Sat Nov 13 00:44:41 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Nov 2010 10:44:41 +1100 Subject: [Tutor] 'pydoc' is not recognized as an internal or external command, ... In-Reply-To: <326390.17201.qm@web112713.mail.gq1.yahoo.com> References: <326390.17201.qm@web112713.mail.gq1.yahoo.com> Message-ID: <4CDDD169.2020208@pearwood.info> R Johnson wrote: > 'pydoc' is not recognized as an internal or external command, operable program > or batch file. This means that the program "pydoc" is not installed on your computer, or is installed somewhere where the operating system (I'm guessing you're using Windows?) can't find it. Use the Find File command, and see if you can find something called "pydoc". You may need to call the full path to the program, e.g.: C:\My Documents\path\to\program\pydoc raw_input or you may need to install it :) > So, I go back to the terminal and type: python > Then I type: pydoc raw_input > The computer spits back: > File "", line1 > pydoc raw_input > SyntaxError: invalid syntax > (There is a carrot symbol under the "t" of input.) pydoc is an external tool made with Python, it is not a Python command you can run. However, Python does come with an internal tool that is nearly as powerful: help(). From the Python prompt, type: help(raw_input) and Enter, and you will get something very close to what pydoc would have given you. -- Steven From malaclypse2 at gmail.com Sat Nov 13 00:56:08 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 12 Nov 2010 18:56:08 -0500 Subject: [Tutor] 'pydoc' is not recognized as an internal or external command, ... In-Reply-To: <4CDDD169.2020208@pearwood.info> References: <326390.17201.qm@web112713.mail.gq1.yahoo.com> <4CDDD169.2020208@pearwood.info> Message-ID: On Fri, Nov 12, 2010 at 6:44 PM, Steven D'Aprano wrote: > Use the Find File command, and see if you can find something called "pydoc". > You may need to call the full path to the program, e.g.: > > C:\My Documents\path\to\program\pydoc raw_input On my windows PC, it's c:\Python31\Lib\pydoc.py So, to do what the tutorial is suggesting, you would need to open a command prompt (cmd.exe) and run: c:\Python31\Lib\pydoc.py raw_input Note: Since I have python 3.1 installed, that wouldn't actually work, because python 3.1 no longer has a raw_input function -- it's been renamed to just input. If you want to be able to run pydoc.py without specifying the full path every time, I could add C:\Python31\Lib to my PATH environment variable. -- Jerry From patrickforbes at mac.com Fri Nov 12 21:28:21 2010 From: patrickforbes at mac.com (Patrick Forbes) Date: Fri, 12 Nov 2010 15:28:21 -0500 Subject: [Tutor] Python 2.5 Problem Message-ID: <37B03249-AA15-4609-B062-0F320C8B5116@mac.com> Let me start by saying I got here as I was trying to get a DRM killer to work so that I could actually read e-books I own (purchased). I was pointed towards ignoblekey/pub pyw's and couldn't figure out to work them. I was told to use Python 2.6 but couldn't find it as I was unaware it was buried in the Library and didn't know how to work Terminal. I made several boo boo's and lost the Python 2.5 that my Mac once had and tried to get 2.7 installed. Was informed 2.5 was the better choice. 2.7 didn't put its stuff where it was supposed to be and when I found 2.5, it's installation failed: -------------- next part -------------- A non-text attachment was scrubbed... Name: Picture 1.png Type: image/png Size: 95327 bytes Desc: not available URL: -------------- next part -------------- Now what? Patrick Forbes 121 Lafayette Boulevard Whitby, Ontario L1P 1S4 905-233-4607 From steve at pearwood.info Sat Nov 13 01:53:02 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Nov 2010 11:53:02 +1100 Subject: [Tutor] Python 2.5 Problem In-Reply-To: <37B03249-AA15-4609-B062-0F320C8B5116@mac.com> References: <37B03249-AA15-4609-B062-0F320C8B5116@mac.com> Message-ID: <4CDDE16E.6020100@pearwood.info> Patrick Forbes wrote: > I was pointed towards ignoblekey/pub pyw's and couldn't figure out to > work them. I was told to use Python 2.6 but couldn't find it as I was > unaware it was buried in the Library and didn't know how to work > Terminal. I made several boo boo's and lost the Python 2.5 that my Mac > once had and tried to get 2.7 installed. Was informed 2.5 was the better > choice. 2.7 didn't put its stuff where it was supposed to be and when I > found 2.5, it's installation failed: This mailing list is for help in learning the programming language Python. You would be better off asking for help on some Apple Macintosh forum: "I've accidentally trashed the system Python 2.5, how do I reinstall it?" "How do I install Python 2.6 or 2.7 without trashing the system Python?" You'll need to mention what version of Mac OS you're running. If the Mac forum can't help, the general purpose Python forum might have some Mac users who can help. Try the python-list at python.org mailing list, or if you prefer Usenet, comp.lang.python. Good luck! -- Steven From alan.gauld at btinternet.com Sat Nov 13 02:07:24 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Nov 2010 01:07:24 -0000 Subject: [Tutor] What is a "state variable"? References: Message-ID: "Richard D. Moores" wrote >> For example if I say that the state of any object can be >> represented >> by a vector whose values correspond to the collected set of >> variables >> of the object, does that make sense? > > No. Not the vector idea. Sorry. A vector is just a fancy mathematical name for an array of values. In the case of state the values are those of the set of relevant variables that control the behaviour of the program. In the case of an object it is usually the set of attributes of the object plus any local/environment variables. (An object can be thought of as a container in the same way as a list or dictionary) So the state variables of a class are those that affect the functioning of the class. As an example we might have a simple traffic light that cycles through the 3 states (green, amber red) at a set time interval. The only state variable is likely to be one holding the current state name. But we could make it more complex by having the traffic light interval controlled by traffic density based on a count of the number of cars passing during a green phase. Now we have two factors controlling the state change - the old value and the counter - two state variables. We then might introduce different intervals per state change - so we get a set of 4 timer values - now 6 state variables. And so on. We might also have some other variables that are purely data such as the location of the light, or the date of installation. But these may have no effect on the function of the light. These are attributes but they are not state variables - they don't affect the state. Of course, in practice they may affect the state of other operations, like a scheduled cleaning operation - in which case they become state variables but in a different state vector since the cleaning state machine is separate from the lighting state machine. State machines are very important in software engineering, particularly for safety critical systems as they are one of the few specification and design techniques in CS that are both mathematically rigorous, have provably correct implementations and are practical to build.(usually by building a dispatch table of states and their events) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From m_stover43812us at yahoo.com Sat Nov 13 03:43:05 2010 From: m_stover43812us at yahoo.com (Michael Stover) Date: Fri, 12 Nov 2010 18:43:05 -0800 (PST) Subject: [Tutor] Grabbing Information from txt files Message-ID: <809816.42314.qm@web82305.mail.mud.yahoo.com> My apologies for my last email, admittedly I was more tired that I thought as after re-reading it and the emails coming in, I found that I did not provided "proper" information. 1. I have a script that is detecting multiple various bits of information of a video file using MediaInfo and putting that information into a txt file with the format of: (Example:) num_vid_track=? num_aud_track=? num_sub_track=? Granted that is only part of the information being obtained but it's all in the same format. I have been trying multiple ways of grabbing this information for re-use, including using this snippet, suggested to me by fellow users of the #python irc channel.. import shlex as shlex_ from subprocess import Popen, PIPE def shell(args, input=None, stdout=PIPE, stderr=PIPE, shlex=False, **kwargs): """Gets the output of a command run in a subprocess. Arguments: args: A sequence of strings, or a single string if shlex=True. input: A string to be written to the process's stdin. Any extra keyword arguments are forwarded to Popen. Returns: A tuple of (stdout, stderr) >>> shell('basename /a/hello', shlex=True) ('hello\n','') """ if shlex: args = shlex_.split(args) stdin = PIPE if input is not None else None p = Popen(args, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs) return p.communicate(input=input) Then using a command line similar to: p = subprocess.Popen(['foo', 'bar'], stdout=subprocess.PIPE); stdout, _ = p.communicate() Where 'foo','bar' obviously is the program I am calling with its arguements. The only issue is, I can barely understand the documentation I kept getting pointed to for retrieving the information captured from stdout. Which is why I went with another friends suggestion of outputting all of the information to a text file. Sorry if this seems to have veered off course, but which method would be more recommended to implement? So far I have been able to write a different python script for a general conversion of videos from multiple different formats to a single format my xbox 360 can read (with or without is optional media update). Again sorry for my previous email, and thank you in advance for the assistance and suggestions, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhettbrindle at yahoo.com Sat Nov 13 04:11:47 2010 From: rhettbrindle at yahoo.com (R Johnson) Date: Fri, 12 Nov 2010 19:11:47 -0800 (PST) Subject: [Tutor] 'pydoc' is not recognized as an internal or external command, ... In-Reply-To: <4CDDD169.2020208@pearwood.info> References: <326390.17201.qm@web112713.mail.gq1.yahoo.com> <4CDDD169.2020208@pearwood.info> Message-ID: <279955.56986.qm@web112713.mail.gq1.yahoo.com> Thank you to all who have responded. I have a bit of an update that reflects some of these suggestions. I was able to snag some time from one of the more experienced engineers and here is what we found: On my system (Windows 7) the path to the lib file is C:\Python26\lib and "pydoc.py" is in this folder. So, he had me run: python -m pydoc raw_input at that prompt. Sure enough, this returned what looked like help information for raw_input. And, when we he had me follow the trail: Start > Control Panel > System > Advanced Settings > Environment Variables Python26 was in the PATH. ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Fri, November 12, 2010 5:44:41 PM Subject: Re: [Tutor] 'pydoc' is not recognized as an internal or external command, ... R Johnson wrote: > 'pydoc' is not recognized as an internal or external command, operable program >or batch file. This means that the program "pydoc" is not installed on your computer, or is installed somewhere where the operating system (I'm guessing you're using Windows?) can't find it. Use the Find File command, and see if you can find something called "pydoc". You may need to call the full path to the program, e.g.: C:\My Documents\path\to\program\pydoc raw_input or you may need to install it :) > So, I go back to the terminal and type: python > Then I type: pydoc raw_input > The computer spits back: File "", line1 > pydoc raw_input > SyntaxError: invalid syntax > (There is a carrot symbol under the "t" of input.) pydoc is an external tool made with Python, it is not a Python command you can run. However, Python does come with an internal tool that is nearly as powerful: help(). >From the Python prompt, type: help(raw_input) and Enter, and you will get something very close to what pydoc would have given you. -- 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 wprins at gmail.com Sat Nov 13 04:14:16 2010 From: wprins at gmail.com (Walter Prins) Date: Sat, 13 Nov 2010 03:14:16 +0000 Subject: [Tutor] Grabbing Information from txt files In-Reply-To: <809816.42314.qm@web82305.mail.mud.yahoo.com> References: <809816.42314.qm@web82305.mail.mud.yahoo.com> Message-ID: Random thoughts: 1.) Maybe you should be looking at something like Fuppes instead: http://fuppes.ulrich-voelkel.de/ ? 2.) Even so, continuing with your current direction: there appears to be a module/wrapper of MediaInfo for Python, thus removing the need to scrape information from MediaInfo's output, which is what I presume you're trying to do above. Might be useful. See here: http://forum.doom9.org/showthread.php?t=96516&page=11 Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Nov 13 04:25:26 2010 From: smokefloat at gmail.com (David Hutto) Date: Fri, 12 Nov 2010 22:25:26 -0500 Subject: [Tutor] Grabbing Information from txt files In-Reply-To: <809816.42314.qm@web82305.mail.mud.yahoo.com> References: <809816.42314.qm@web82305.mail.mud.yahoo.com> Message-ID: On Fri, Nov 12, 2010 at 9:43 PM, Michael Stover wrote: > My apologies for my last email, admittedly I was more tired that I thought > as after re-reading it and the emails coming in, I found that I did not > provided "proper" information. > > 1. I have a script that is detecting multiple various bits of information of > a video file using MediaInfo and putting that information into a txt file > with the format of: > (Example:) > num_vid_track=? > num_aud_track=? > num_sub_track=? > > Granted that is only part of the information being obtained but it's all in > the same format. > I have been trying multiple ways of grabbing this information for re-use, > including using this snippet, suggested to me by fellow users of the #python > irc channel.. > > import shlex as shlex_ > from subprocess import Popen, PIPE > > def shell(args, input=None, stdout=PIPE, stderr=PIPE, shlex=False, > **kwargs): > ??? """Gets the output of a command run in a subprocess. > > ??? Arguments: > ??????? args:?? A sequence of strings, or a single string if shlex=True. > ??????? input:? A string to be written to the process's stdin. > ??????? Any extra keyword arguments are forwarded to Popen. > > ??? Returns: > ??????? A tuple of (stdout, stderr) > > ??? >>> shell('basename /a/hello', shlex=True) > ??? ('hello\n','') > ??? """ > ??? if shlex: > ??????? args = shlex_.split(args) > ??? stdin = PIPE if input is not None else None > ??? p = Popen(args, stdin=stdin, stdout=stdout, stderr=stderr, **kwargs) > ??? return p.communicate(input=input) > > Then using a command line similar to: > p = subprocess.Popen(['foo', 'bar'], stdout=subprocess.PIPE); stdout, _ = > p.communicate() > > Where 'foo','bar' obviously is the program I am calling with its arguements. > The only issue is, I can barely understand the documentation I kept getting > pointed to for retrieving the information captured from stdout. Which is why > I went with another friends suggestion of outputting all of the information > to a text file. Sorry if this seems to have veered off course, but which > method would be more recommended to implement? So far I have been able to > write a different python script for a general conversion of videos from > multiple different formats to a single format my xbox 360 can read (with or > without is optional media update). > > Again sorry for my previous email, and thank you in advance for the > assistance and suggestions, > Mike > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > It'll alll become clear soon danielson/grasshoppa. From m_stover43812us at yahoo.com Sat Nov 13 04:33:59 2010 From: m_stover43812us at yahoo.com (Michael) Date: Fri, 12 Nov 2010 19:33:59 -0800 (PST) Subject: [Tutor] Grabbing Information from txt files Message-ID: <573741.19198.qm@web82306.mail.mud.yahoo.com> >Random thoughts: > >1.) Maybe you should be looking at something like Fuppes instead: >http://fuppes.ulrich-voelkel.de/ ? >2.) Even so, continuing with your current direction: there appears to >be a >module/wrapper of MediaInfo for Python, thus removing the need to >scrape >information from MediaInfo's output, which is what I presume you're >trying >to do above. Might be useful. See here: >http://forum.doom9.org/showthread.php?t=96516&page=11 > >Walter I didn't get Fruppes in any of my original searches, I will give that a try, and I have tried the module/wrapper for MediaInfo but have to wait for a bug fix as it does not work correctly with 64bit Linux. At least not with Python 2.6, and I am reluctant to upgrade to Python 3 due to compatibility issues. From rdmoores at gmail.com Sat Nov 13 07:14:43 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 22:14:43 -0800 Subject: [Tutor] What is a "state variable"? In-Reply-To: References: Message-ID: On Fri, Nov 12, 2010 at 17:07, Alan Gauld wrote: > > "Richard D. Moores" wrote > >>> For example if I say that the state of any object can be represented >>> by a vector whose values correspond to the collected set of variables >>> of the object, does that make sense? I think I would have understood this if you have used "array of values" instead of "vector". >> >> No. Not the vector idea. Sorry. > > A vector is just a fancy mathematical name for an array of values. > In the case of state the values are those of the set of relevant > variables that control the behaviour of the program. > > In the case of an object it is usually the set of attributes of the > object plus any local/environment variables. (An object can be > thought of as a container in the same way as a list or dictionary) > > So the state variables of a class are those that affect the > functioning of the class. > > As an example Your increasingly complex but clear example was very useful to me. Thank you. Dick From steve at pearwood.info Sat Nov 13 08:16:23 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Nov 2010 18:16:23 +1100 Subject: [Tutor] Grabbing Information from txt files In-Reply-To: <809816.42314.qm@web82305.mail.mud.yahoo.com> References: <809816.42314.qm@web82305.mail.mud.yahoo.com> Message-ID: <4CDE3B47.5000804@pearwood.info> Michael Stover wrote: > My apologies for my last email, admittedly I was more tired that I thought as > after re-reading it and the emails coming in, I found that I did not provided > "proper" information. > > 1. I have a script that is detecting multiple various bits of information of a > video file using MediaInfo and putting that information into a txt file with the > format of: > (Example:) > num_vid_track=? > num_aud_track=? > num_sub_track=? > > Granted that is only part of the information being obtained but it's all in the > same format. > I have been trying multiple ways of grabbing this information for re-use, > including using this snippet, suggested to me by fellow users of the #python irc > channel.. [snip] > only issue is, I can barely understand the documentation I kept getting pointed > to for retrieving the information captured from stdout. Which is why I went with > another friends suggestion of outputting all of the information to a text file. > Sorry if this seems to have veered off course, but which method would be more > recommended to implement? There's absolutely nothing wrong with an "assembly line" of components: Use MediaInfo to write data to a text file; Use Python to read the text file and process it; Use to modify the video according to the text file; etc. You don't need a single monolithic script to do everything... if you have an easy way of calling MediaInfo and getting it to write its data to text files, stick with that. -- Steven From rdmoores at gmail.com Sat Nov 13 08:25:38 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 23:25:38 -0800 Subject: [Tutor] List comprehension question In-Reply-To: <4CDDCD19.2080002@pearwood.info> References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> <4CDDCD19.2080002@pearwood.info> Message-ID: On Fri, Nov 12, 2010 at 15:26, Steven D'Aprano wrote: > Richard D. Moores wrote: > >> OK, but why can't I do what the timeit doc suggests, only put 2 or >> more functions in the file, as I do here: >> >> >> def test(): >> ? ?"Stupid test function" >> ? ?L = [] >> ? ?for i in range(100): >> ? ? ? ?L.append(i) >> >> if __name__=='__main__': >> ? ?from timeit import Timer >> ? ?t = Timer("test()", "from __main__ import test") >> ? ?print t.timeit() > > > There's nothing wrong with that, except that running the test *once* (as you > do) is subject to greater chance fluctuations than running it multiple > times: change the last line to: > > print min(t.repeat()) > > Note that you don't *have* to do this, the world will not end if you don't, > but your timing results will be just a little more accurate if you do. > > If you want to time multiple functions, just use multiple timer objects: > > t1 = Timer("test()", "from __main__ import test") > t2 = Timer("spam()", "from module import spam") > t3 = Timer("ham()", "from module import ham") > > >> I'm sorry, Steven, but could you revise this code to use repeat=5 >> instead of the for loop? I can't see how to do it. > > You don't need to choose repeat=5. The default is 3, but you can specify any > number you like. I just like 5 :) So I'll go with your 5. >> if __name__=='__main__': >> ? ?from timeit import Timer >> ? ?for y in range(5): >> ? ? ? ?t = Timer("proper_divisors_sum1(500000)", "from __main__ >> import proper_divisors_sum") >> ? ? ? ?print round(t.timeit(number=10000),3) > > if __name__=='__main__': > ? ?from timeit import Timer > ? ?t = Timer("proper_divisors_sum(500000)", > ? ? ? ?"from __main__ import proper_divisors_sum") > ? ?best = t.repeat(number=10000, repeat=5) > ? ?print round(best, 3) t.repeat(number=10000, repeat=5) is a list of the 5 times, not the best of the 5. So I used min(t.repeat(number=10000, repeat=5)) See Thanks very much, Steven! From rdmoores at gmail.com Sat Nov 13 08:53:03 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 12 Nov 2010 23:53:03 -0800 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> <4CDDCD19.2080002@pearwood.info> Message-ID: On Fri, Nov 12, 2010 at 23:25, Richard D. Moores wrote: > See Sorry, forgot to paste. Dick From steve at pearwood.info Sat Nov 13 10:12:55 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Nov 2010 20:12:55 +1100 Subject: [Tutor] List comprehension question In-Reply-To: References: <4CD7E26C.3010908@pearwood.info> <4CD9B500.4090605@pearwood.info> <4CDA757E.5000500@pearwood.info> <4CDD12B8.6080605@pearwood.info> <4CDDCD19.2080002@pearwood.info> Message-ID: <4CDE5697.3030201@pearwood.info> Richard D. Moores wrote: > On Fri, Nov 12, 2010 at 15:26, Steven D'Aprano wrote: >> best = t.repeat(number=10000, repeat=5) >> print round(best, 3) > > t.repeat(number=10000, repeat=5) is a list of the 5 times, not the > best of the 5. Oops! Good catch. Sorry about that. -- Steven From mehgcap at gmail.com Sun Nov 14 07:23:51 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 14 Nov 2010 01:23:51 -0500 Subject: [Tutor] program hangs in while loop using wx.yield Message-ID: Hi all, I had this working back in the summer, but have since had to restructure some things in the code. Now, my program is hanging while it waits for the human player to take his/her turn, and I am not sure how to free it; as long as it hangs, the player cannot do anything, so it continues to hang... You get the idea. Here is the loop: while not self.grid.turnOver: print("in while") #just a test to make sure I got this far wx.Yield() time.sleep(1) #end while self.grid is a Grid object which, among other things, is a wx frame with a sizer inside of it. This Grid class has many functions, and some of them change the Grid's "turnOver" variable. Therefore, I loop until I see that the user performed an action on the grid that sets the Grid's turnOver to true, at which point the loop stops and the other user (a computer in this case) can go. The problem is that this loop makes the app hang, with Windows saying it is not responding. Of course, the user can now not do anything at all, so I have to use ctrl-c from the cmd window where I launched it to kill it. Does anyone have a thought? Grid has no loops in it where the program could be getting stuck and, besides, it hangs immediately, not even giving me time to call any Grid function. Is this solvable, or should I just use threads? I hate to launch every new turn in a separate thread as it seems that this would quickly get out of hand, but if I have to I can do it. TIA. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Sun Nov 14 10:04:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Nov 2010 09:04:59 -0000 Subject: [Tutor] program hangs in while loop using wx.yield References: Message-ID: "Alex Hall" wrote > I had this working back in the summer, but have since had to > restructure some things in the code. Now, my program is hanging > while > it waits for the human player to take his/her turn, and I am not > sure > how to free it; I don't really understand this concept in a GUI? Why would you be waitying for the user? Surely you should just go back to the mainloop and let the GUI control the users input? Then after processing that call the computer move code. Something like: def handle_user_move_event(): processMoveOnGUI() movedata = generateComputerMove() processMoveOnGUI() return Thats what I would expect to see. > while not self.grid.turnOver: > print("in while") #just a test to make sure I got this far > wx.Yield() > time.sleep(1) > #end while So this is presumably buried in some very long and complex method that you have written and you are briefly giving control back to wxPython before continuing your processing? Except that you appear to just cycle continually giving back control? It doesn't seem to make sense. > some of them change the Grid's "turnOver" variable. Therefore, I > loop > until I see that the user performed an action on the grid that sets > the Grid's turnOver to true, at which point the loop stops and the > other user (a computer in this case) can go. Why are you doing all this inside ane event handler? Why don't you just make your move and hand back to the GUI? > The problem is that this loop makes the app hang, > with Windows saying it is not responding. Of > course, the user can now not do anything at all, so I have to use > ctrl-c from the cmd window where I launched it to kill it. No idea why its doing that. Have you tried playing with the Yield parameter and return value to see if they give a clue? But frankly I'd look to reconstruct the code to avoid the use of Yield completely. Yield should almost be a last resort... > time to call any Grid function. Is this solvable, or should I just > use > threads? Based on the loop you posted you shouldn't need threads, just exit your method and wait for the user to do something and catch that event to restart your code. Leave it to the GUI. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From josep.m.fontana at gmail.com Sun Nov 14 17:59:53 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sun, 14 Nov 2010 17:59:53 +0100 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: <1289480833.13521.5.camel@Nokia-N900> References: <1289480833.13521.5.camel@Nokia-N900> Message-ID: Hi Kushal, First of all, thanks a lot for your help. > > Your current code adds the marker line to the original files. Is that > intended? Well, no, this wasn't intended. The part of the code that did that was introduced in one of the many attempts to solve the problem. I knew that this was an unwanted result but since I didn't know how to get out of the situation I got myself in I decided to send the code as it was so that people in this list could see more clearly what the problems with my code were. > You can open the output file for writing by passing 'w' as the second > argument to open. You would do this before your directory-walking loop. Then > when you read the contents of any file, just write to your output file as > well, along with your marker line. Is there any reason to open the file before the directory-walking loop? Below I enclose the code I wrote with your help and Evert's help. In that code the output file is opened inside the loop and the script works as expected. Even if it works, this might not be the best way to do it. Please tell me. I'm learning and I don't just want my code to work but I want it to be as elegant and efficient as possible. >> ----------------- code-------- >> import os >> path = '/Volumes/DATA/MyPath' >> os.chdir(path) >> file_names = glob.glob('*.txt') > > output_stream = open('outputfilename', 'w') > >> for subdir, dirs, files in os.walk(path): >>? ? ? ? for file in files: >>? ? ? ? ? ? ? ? f = open(file, 'r') >>? ? ? ? ? ? ? ? text = f.readlines() > > output_stream.writelines(text) > output_stream.write('______\n') > >>? ? ? ? ? ? ? ? f.close() >>? ? ? ? ? ? ? ? f = open(file, 'a') >>? ? ? ? ? ? ? ? f.write('\n\n' + '________________________________' + '\n') >>? ? ? ? ? ? ? ? f.close() >> > > output_stream.close() > >> ------------ OK, here's what I did: ------------ import os path = '/Volumes/myPath' os.chdir(path) for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: #see tomboy note 'with statement' data = f.read() with open('/Volumes/myPath2/output.txt', 'a') as output_file: output_file.write('\n\n\n\n') output_file.write(data) output_file.write('\n\n\n\n') ----------------- if you notice, the output file is opened on the fourth line counting from the end, inside the loop. After following Evert's recommendations and yours, this seemed the most logical place to do it. As I said, it works like a charm but I don't know if I have committed some crime of style. Josep M. From josep.m.fontana at gmail.com Sun Nov 14 18:27:41 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sun, 14 Nov 2010 18:27:41 +0100 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: References: Message-ID: Hi Evert, Again, thanks a lot. Too bad you and Kushal don't live close. I would like to invite you to a beer or a coffe or something. >> >> ----------------- code-------- >> import os >> path = '/Volumes/DATA/MyPath' >> os.chdir(path) >> file_names = glob.glob('*.txt') > > You don't use file_names any further. Depending on whether you want files from subdirectories or not, you can use the os.walk below or file_names. You are totally right. Since I had used glob in another script before, I tried to use it in this one as well before I tried with os.walk() and then I left it there forgetting that with os.walk() it was no longer necessary. >> for subdir, dirs, files in os.walk(path): >> ? ?for file in files: >> ? ? ? ?f = open(file, 'r') >> ? ? ? ?text = f.readlines() > > Since you don't care about lines in your files, but just the entire file contents, you could also simply use > data = f.read() Yes. Thanks. This is much better. I knew this from having read a chapter on working with files somewhere but I wound up using .readlines() because in my search for a solution I saw some piece of code that used it and got the results I wanted, > So close ;-). > What you're missing is the next write statement: > f.write(data) > > (or > f.write(''.join(text)) > which shows why read() is nicer in this case: readlines() returns a list, not just a single string). > >> ? ? ? ?f.close() > > But actually, you can open and close the output file outside the entire loop; just name it differently (eg, before the first loop, > outfile = open('outputfile', 'w') OK, I ask you (or anybody reading this) the same question I asked Kushal: why is it better to open the output file outside the entire loop. I understand why it should be closed outside the loop but if you see the code I came up with after your comments, I open the output file inside the loop and the script still works perfectly well. Is there any good reason to do it differently from the way I did it? Here's what I did: ----------------- import os path = '/Volumes/myPath' os.chdir(path) for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: #see tomboy note 'with statement' data = f.read() with open('/Volumes/myPath2/output.txt', 'a') as output_file: output_file.write('\n\n\n\n') output_file.write(data) output_file.write('\n\n\n\n') ----------------- I came up with this way of doing because I was trying to follow your advice of using the 'with' statement and this was the first way that I could think of to implement it. Since in the little test that I ran it worked, I left it like that but I would like to know whether there is a more elegant way to implement this so that I learn good habits. > In this case, though, there's one thing to watch out for: glob or os.walk will pick up your newly (empty) created file, so you should either put the all-containg file in a different directory (best practice) or insert an if-statement to check whether file[name] != 'outputfile' You'll have seen that I opted for the best practice but I still used an if statement with file[name] != 'outputfile' in order to solve some problems I was having with a hidden file created by Mac OSX (.DS_Store). The output file contained some strange characters at the beginning and it took me a while to figure out that this was caused by the fact that the loop read the contents of the .DS_Store file. > Finally, depending on the version of Python you're using, there are nice things you can do with the 'with' statement, which has an incredible advantage in case of file I/O errors (since you're not checking for any read errors). > See eg http://effbot.org/zone/python-with-statement.htm (bottom part for example) or Google around. Great advice. I took the opportunity to learn about the 'with' statement and it will be very helpful in the future. While they don't come up with virtual drinks that are realistic enough to be enjoyable, I can only offer you my thanks for your time. Josep M. From evert.rol at gmail.com Sun Nov 14 18:42:18 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 14 Nov 2010 18:42:18 +0100 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: References: Message-ID: > Again, thanks a lot. Too bad you and Kushal don't live close. I would > like to invite you to a beer or a coffe or something. Thanks for the offer. Some time ever in the far, far future perhaps ;-). > >> So close ;-). >> What you're missing is the next write statement: >> f.write(data) >> >> (or >> f.write(''.join(text)) >> which shows why read() is nicer in this case: readlines() returns a list, not just a single string). >> >>> f.close() >> >> But actually, you can open and close the output file outside the entire loop; just name it differently (eg, before the first loop, >> outfile = open('outputfile', 'w') > > OK, I ask you (or anybody reading this) the same question I asked > Kushal: why is it better to open the output file outside the entire > loop. I understand why it should be closed outside the loop but if you > see the code I came up with after your comments, I open the output > file inside the loop and the script still works perfectly well. Is > there any good reason to do it differently from the way I did it? Your code will work fine. My reason (and there may be others) to do it this way is just to avoid a marginal bit of overhead. Closing and opening the file each time will cost some extra time. So that's why I would have moved the with statement for the output_file outside both loops. Though as said, I guess that the overhead in general is very little. > Here's what I did: > > ----------------- > import os > path = '/Volumes/myPath' > os.chdir(path) > for subdir, dirs, files in os.walk(path): > for filename in files: > if filename != '.DS_Store': > with open(filename, 'r') as f: #see tomboy note 'with statement' > data = f.read() > with open('/Volumes/myPath2/output.txt', 'a') as > output_file: > output_file.write('\n\n\n\n') > output_file.write(data) > output_file.write('\n\n\n\n') > ----------------- > > I came up with this way of doing because I was trying to follow your > advice of using the 'with' statement and this was the first way that I > could think of to implement it. Since in the little test that I ran it > worked, I left it like that but I would like to know whether there is > a more elegant way to implement this so that I learn good habits. This is fine: 'with open(, ) as :' is, afaik, the standard way now to open a file in Python. >> In this case, though, there's one thing to watch out for: glob or os.walk will pick up your newly (empty) created file, so you should either put the all-containg file in a different directory (best practice) or insert an if-statement to check whether file[name] != 'outputfile' > > You'll have seen that I opted for the best practice but I still used > an if statement with file[name] != 'outputfile' in order to solve some > problems I was having with a hidden file created by Mac OSX > (.DS_Store). The output file contained some strange characters at the > beginning and it took me a while to figure out that this was caused by > the fact that the loop read the contents of the .DS_Store file. Yes, there'll few ways to avoid separate filenames apart from an if statement. Cheers, Evert From alan.gauld at btinternet.com Sun Nov 14 18:44:08 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Nov 2010 17:44:08 -0000 Subject: [Tutor] Creating one file out of all the files in a directory References: Message-ID: "Josep M. Fontana" wrote > OK, I ask you (or anybody reading this) the same question I asked > Kushal: why is it better to open the output file outside the entire > loop. Because you only need to open it once and leave it open. You are opening it each and every time which is wasteful. It could on some OSDS also lead to problems. And if you were writing a new file rather than appending it would overwrite the contents each time which would be bad. > see the code I came up with after your comments, I open the output > file inside the loop and the script still works perfectly well. Consider that more a matter of luck than good judgement. > Is there any good reason to do it differently from the way I did it? Yes, see above. > I came up with this way of doing because I was trying to follow your > advice of using the 'with' statement and this was the first way that > I > could think of to implement it. Just put the with statement for the output file outside the loop: with open('/Volumes/myPath2/output.txt', 'a') as output_file: for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: #see tomboy note 'with statement' data = f.read() output_file.write('\n\n\n\n') output_file.write(data) output_file.write('\n\n\n\n') BTW you could use a single write with: output_file.write( '\n\n\n\n%s\n\n\n\n" % (filename, data) ) But thats largely a matter of personal style. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From josep.m.fontana at gmail.com Sun Nov 14 19:34:26 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sun, 14 Nov 2010 19:34:26 +0100 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: References: Message-ID: Thanks Alan, why is it better to open the output file outside the entire >> loop. > > Because you only need to open it once and leave it open. > You are opening it each and every time which is wasteful. > It could on some OSDS also lead to problems. And if you > were writing a new file rather than appending it would overwrite > the contents each time which would be bad. Dah, yes, you are totally right and now that I think about it it seems pretty obvious. Now, why didn't I think about it? That's the problem. > Just put the with statement for the output file outside the loop: You mean like this? It seems to work. ... with open('/Volumes/myPath2/output.txt', 'a') as output_file: for subdir, dirs, files in os.walk(path): for filename in files: if filename != '.DS_Store': with open(filename, 'r') as f: data = f.read() output_file.write( "\n\n\n\n%s\n\n\n\n" % (filename, data) ) > > BTW you could use a single write with: > > output_file.write( '\n\n\n\n%s\n\n\n\n" % (filename, > data) ) > > But thats largely a matter of personal style. Well, since I don't have any personal style yet, I might as well go with the style of good programmers I learn from. If you notice in the revised code I introduced above, I replaced the single quote with a double quote to match the double quote you had used at the end. This was a typo, right? Josep M. From mehgcap at gmail.com Sun Nov 14 19:35:09 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 14 Nov 2010 13:35:09 -0500 Subject: [Tutor] program hangs in while loop using wx.yield In-Reply-To: References: Message-ID: On 11/14/10, Alan Gauld wrote: > "Alex Hall" wrote > >> I had this working back in the summer, but have since had to >> restructure some things in the code. Now, my program is hanging >> while >> it waits for the human player to take his/her turn, and I am not >> sure >> how to free it; > > I don't really understand this concept in a GUI? > Why would you be waitying for the user? > Surely you should just go back to the mainloop > and let the GUI control the users input? Then > after processing that call the computer move code. > Something like: > > def handle_user_move_event(): > processMoveOnGUI() > movedata = generateComputerMove() > processMoveOnGUI() > return > > Thats what I would expect to see. The problem is that I want to go until there is a winner. You are right about just letting the mainloop of the gui handle input (I forgot the gui is already looping and waiting for input) but I would like to make the user pause while the computer goes, this way the user cannot just keep hammering out moves as fast as possible and input can be given to the user properly. Therefore, I have gotten rid of the loop I sent originally, but I still have a loop which switches between the two players as well as passing the results of one player's move to the other. If I fire (it is Battleship) and hit your ship,and I am the computer, then this loop will give you the information about where I fired. You will check to see if it was a hit and, since it was, pass back information about what was hit. You will also update the gui to reflect the new status of the damaged ship. However, while I am doing this, I do not want you firing as fast as possible, and I want you to take in the results before you are allowed to fire. I realize it is all rather confusing without seeing the code, but the loop itself is somewhat complex unless you can see what all the functions are doing. Still, here is the new loop: while not player1.isWinner or not player2.isWinner: if player1.grid.turnOver: print("player2 is going") player1.grid.speak("player 2 is going.") player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did player1.lock() #so p1 cannot interact with the gui player2.takeTurn() #decides what to do and updates its Grid object accordingly player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just output what p2 did after takeTurn() is over elif player2.grid.turnOver: print("player1 is going") player1.enemyMove=player2.grid.cmd player1.unlock() #p1 can now interact with the gui player1.grid.speak("It is now your turn.") player1.takeTurn() #end if #wx.Yield() time.sleep(.1) #end while > >> while not self.grid.turnOver: >> print("in while") #just a test to make sure I got this far >> wx.Yield() >> time.sleep(1) >> #end while > > So this is presumably buried in some very long and complex method > that you have written and you are briefly giving control back to > wxPython > before continuing your processing? Except that you appear to just > cycle continually giving back control? It doesn't seem to make sense. I am honestly not sure how all the control flows, but this loop is gone so hopefully it will not be a problem. > >> some of them change the Grid's "turnOver" variable. Therefore, I >> loop >> until I see that the user performed an action on the grid that sets >> the Grid's turnOver to true, at which point the loop stops and the >> other user (a computer in this case) can go. > > Why are you doing all this inside ane event handler? Why don't > you just make your move and hand back to the GUI? > > >> The problem is that this loop makes the app hang, >> with Windows saying it is not responding. Of >> course, the user can now not do anything at all, so I have to use >> ctrl-c from the cmd window where I launched it to kill it. > > No idea why its doing that. Have you tried playing with the > Yield parameter and return value to see if they give a clue? > > But frankly I'd look to reconstruct the code to avoid the use > of Yield completely. Yield should almost be a last resort... > >> time to call any Grid function. Is this solvable, or should I just >> use >> threads? > > > Based on the loop you posted you shouldn't need threads, > just exit your method and wait for the user to do something > and catch that event to restart your code. Leave it to the GUI. > > HTH, > > -- > Alan Gauld > 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 > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From josep.m.fontana at gmail.com Sun Nov 14 19:40:43 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sun, 14 Nov 2010 19:40:43 +0100 Subject: [Tutor] Creating one file out of all the files in a directory In-Reply-To: References: Message-ID: >> Again, thanks a lot. Too bad you and Kushal don't live close. I would >> like to invite you to a beer or a coffe or something. > > Thanks for the offer. Some time ever in the far, far future perhaps ;-). Well, if you or the other people who have been so helpful to me in this list ever happen to be in Barcelona, please let me know and I will certainly treat you to a beer or two (or whatever drink you prefer). Josep M. From ingoogni at gmail.com Sun Nov 14 20:06:40 2010 From: ingoogni at gmail.com (ingo) Date: Sun, 14 Nov 2010 20:06:40 +0100 Subject: [Tutor] python at midnight Message-ID: While processing weather data from the http://www.knmi.nl/ and building a small domotica system I ran into the following 'shortcomming' from the python doc: "class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints or longs, in the following ranges: [...] 0 <= hour < 24 [...] If an argument outside those ranges is given, ValueError is raised." from http://en.wikipedia.org/wiki/ISO_8601 : "ISO 8601 uses the 24-hour clock system. The basic format is [hh][mm][ss] and the extended format is [hh]:[mm]:[ss]. * [hh] refers to a zero-padded hour between 00 and 24 (where 24 is only used to notate midnight at the end of a calendar day). [...] Midnight is a special case and can be referred to as both "00:00" and "24:00". The notation "00:00" is used at the beginning of a calendar day and is the more frequently used. At the end of a day use "24:00". Note that "2007-04-05T24:00" is the same instant as "2007-04-06T00:00" (see Combined date and time representations below)." The use of 24:00 is very comfortable when using hourly datasets, the first set of a day is saved under 1:00, the fifth (4:00 to 5:00) under 5:00 and the last (23:00 - 24:00) under 24:00. No need to suddenly use 23:59:59 or 0:00 the next day. Actually in another part of Python SQLlite's date and time functions accept and output the 24:00. Adding some Python to an existing database made me aware of the problem. Questions, Is there a date time library that accepts the 24:00? mxDateTime doesn't. Is there a way to set the limit 'from the outside' (subclassing???) or a simple way around? How to get this functionality added to Python? i. From tim at johnsons-web.com Sun Nov 14 21:26:24 2010 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 14 Nov 2010 11:26:24 -0900 Subject: [Tutor] Recommend a MVC framework Message-ID: <20101114202624.GA1968@johnsons-web.com> I've been web programming for 15 years now. 8 of it using python. Lately I have been 'studying' PHP via the CodeIgnitor Framework. Since python remains my first choice, but since I am also impressed with the concept of CodeIgnitor, I would welcome recommendations on a python MVC framework. One restriction: must *not* need an application server, I.E. works thru Apache and is adaptable to a shared server. TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From evert.rol at gmail.com Sun Nov 14 21:57:28 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 14 Nov 2010 21:57:28 +0100 Subject: [Tutor] Recommend a MVC framework In-Reply-To: <20101114202624.GA1968@johnsons-web.com> References: <20101114202624.GA1968@johnsons-web.com> Message-ID: <0F013513-F67F-4DC2-AECE-ECA785DCCB38@gmail.com> > I've been web programming for 15 years now. 8 of it using python. > > Lately I have been 'studying' PHP via the CodeIgnitor Framework. > > Since python remains my first choice, but since I am also > impressed with the concept of CodeIgnitor, I would welcome > recommendations on a python MVC framework. Django is the default choice, ie, the most common one. Has lots of good documentation, and because of its popularity, lots of examples floating around on the web. Other ones include Pylons and TurboGears, but I have little to no experience with those. It'll also depend on your needs, but since you don't specify any, I'd suggest to look at Django first: http://www.djangoproject.com/ > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. Django can run be run through mod_wsgi (or mod_python if you really want). And other web servers than Apache will also work. Don't know what you mean with "shared server", but if you mean multiple accounts running their web apps through one Apache server, that can work (provided Apache is correctly configured). Cheers, Evert From kirotawa at gmail.com Sun Nov 14 21:46:09 2010 From: kirotawa at gmail.com (leo kirotawa) Date: Sun, 14 Nov 2010 17:46:09 -0300 Subject: [Tutor] Recommend a MVC framework In-Reply-To: <20101114202624.GA1968@johnsons-web.com> References: <20101114202624.GA1968@johnsons-web.com> Message-ID: take a look at web2py. [1] http://www.web2py.com/ On Sun, Nov 14, 2010 at 5:26 PM, Tim Johnson wrote: > I've been web programming for 15 years now. 8 of it using python. > > Lately I have been 'studying' PHP via the CodeIgnitor Framework. > > Since python remains my first choice, but since I am also > impressed with the concept of CodeIgnitor, I would welcome > recommendations on a python MVC framework. > > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. > TIA > -- > Tim > tim at johnsons-web.com or akwebsoft.com > http://www.akwebsoft.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Le?nidas S. Barbosa (Kirotawa) [DesenvolvedorWeb/CEFET/RN] [Ci?ncias da Computa??o/UFRN] [p?s-graduando em Intelig?ncia Computacional/Processamento Gr?fico /UFRN [Estudante de japon?s n?vel Intermedi?rio I - Japanese Student] [Desenvolvedor em python, PyGame] blog nerd: corecode.wordpress.com/ blog music: essenaomanja.blogspot.com blog tirinhas: elminiche.wordpress.com/ "Mais s?bio ? aquele que sabe que n?o sabe" (S?crates) ????????? ??????????????. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 14 23:06:39 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Nov 2010 22:06:39 -0000 Subject: [Tutor] Recommend a MVC framework References: <20101114202624.GA1968@johnsons-web.com> Message-ID: "Tim Johnson" wrote > Since python remains my first choice, but since I am also > impressed with the concept of CodeIgnitor, I would welcome > recommendations on a python MVC framework. Don;t know CodeIgnitor but almost every web framework is MVC based from Struts in Jave through Rails on Ruby to almost all the Python stalwarts - Django, TurboGears, Pylons(I think) etc... > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. Not quite sure how you defione your terms there. But all of the above can be used with Apache. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Sun Nov 14 23:14:46 2010 From: wprins at gmail.com (Walter Prins) Date: Sun, 14 Nov 2010 22:14:46 +0000 Subject: [Tutor] Recommend a MVC framework In-Reply-To: <20101114202624.GA1968@johnsons-web.com> References: <20101114202624.GA1968@johnsons-web.com> Message-ID: Additionally to what's already been said, you may also want to have a look at the Pyjamas project (which can work in conjunction with Django as a back-end), there's a short article about implementing an MVC architecture in Pyjamas here: http://pyjs.org/wiki/modelviewcontroller/ Also you may want to have a look at the Python implementation of PureMVC (which as the previous page mentions can be used in conjuntion with Pyjamas as well): http://trac.puremvc.org/PureMVC_Python/ Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdawn at live.ca Sun Nov 14 23:16:36 2010 From: sdawn at live.ca (Dawn Samson) Date: Sun, 14 Nov 2010 15:16:36 -0700 Subject: [Tutor] While Loops: Coin Flip Game Message-ID: Greetings, I'm a Python beginner and working my way through Michael Dawson's Python Programming for the Absolute Beginner. I'm stuck in a particular challenge that asks me to write a program that "flips a coin 100 times and then tells you the number of heads and tails." I've been trying to work on this challenge for a while now and can't get it to work (either it has 100 heads or 100 tails). I've been reworking this code many times and currently what I have does not do anything at all at IDLE. Please take a look at my code below: import random # set the coincoin = random.randrange(2)headsCount = 0tailsCount = 0count = 0 # the loopwhile count <= 100: coin if coin == 0: headsCount += 1 if coin == 1: tailsCount += 1 count += 1 print "The number of heads was", headsprint "The number of tails was", tails raw_input("\n\nPress the enter key to exit.") Thanks,S. Dawn Samson -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 14 23:21:33 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 14 Nov 2010 22:21:33 -0000 Subject: [Tutor] program hangs in while loop using wx.yield References: Message-ID: "Alex Hall" wrote > The problem is that I want to go until there is a winner. You are > right about just letting the mainloop of the gui handle input (I > forgot the gui is already looping and waiting for input) but I would > like to make the user pause while the computer goes, this way the > user > cannot just keep hammering out moves as fast as possible Thats fine so you simple stop accepting input while the computer goes. I'm sure your computer can keep up with aeven the fastest typist/mouse clicker. If you really want to add a delay simply add a short pause in your event handler - 1 second say. Or even better set a semaphore which blocks any input and then a timer to reset it after a given delay. This is all fairly satandard GUI practice none of which requires complex loops. You need to start thinking about a world controlled by the GUI firing events( or messages if you like) telling you what is happening which you catch and process. > be given to the user properly. Therefore, I have gotten rid of the > loop I sent originally, but I still have a loop which switches > between > the two players Is it two players or is it a player and a computer. If its the former you need a semaphore to block input from one player until the other has gone. In chess terms the values might be black and white and the semaphore called player. You then either need two input handlers, one for black and one for white which call a common utility fuction after checking the semaphor or a single function that somehow can identify the player. If its the latter then the computer should be faster than a hiuman so there should be little problem... > the other. If I fire (it is Battleship) and hit your ship,and I am > the > computer, then this loop will give you the information about where I > fired. You will check to see if it was a hit and, since it was, pass > back information about what was hit. You will also update the gui to > reflect the new status of the damaged ship. I'm confusing you and I, its safer to use explicit trerms when describing interactions. But the displaing of information and updating the GUI can all happen in a blink of an eye if its the computer playing. > this, I do not want you firing as fast as possible, and I want you > to > take in the results before you are allowed to fire. Why do you care if the human "takes in the results" - if they want to trust in randomness surely thats their problem. You as a computer can match them blast for blast... > while not player1.isWinner or not player2.isWinner: > if player1.grid.turnOver: > print("player2 is going") > player1.grid.speak("player 2 is going.") > player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did > player1.lock() #so p1 cannot interact with the gui > player2.takeTurn() #decides what to do and updates its Grid object > accordingly > player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just > output what p2 did after takeTurn() is over > elif player2.grid.turnOver: > print("player1 is going") > player1.enemyMove=player2.grid.cmd > player1.unlock() #p1 can now interact with the gui > player1.grid.speak("It is now your turn.") > player1.takeTurn() > #end if > #wx.Yield() > time.sleep(.1) > #end while Still looks way too complicated to me! > I am honestly not sure how all the control flows, but this loop is > gone so hopefully it will not be a problem. You need to think about the control flow vfery carefully - after all you the programmer are supposed to be in charge of your program! And if you ever have to debug it you will need to understand where the control is going next! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tim at johnsons-web.com Sun Nov 14 23:27:16 2010 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 14 Nov 2010 13:27:16 -0900 Subject: [Tutor] Recommend a MVC framework In-Reply-To: References: <20101114202624.GA1968@johnsons-web.com> Message-ID: <20101114222716.GC1968@johnsons-web.com> * Alan Gauld [101114 13:12]: > Not quite sure how you defione your terms there. > But all of the above can be used with Apache. Hi Alan. See my reply to Evert where I refer to situations where I would have neither SSH nor root access. thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From tim at johnsons-web.com Sun Nov 14 23:28:04 2010 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 14 Nov 2010 13:28:04 -0900 Subject: [Tutor] Recommend a MVC framework In-Reply-To: <0F013513-F67F-4DC2-AECE-ECA785DCCB38@gmail.com> References: <20101114202624.GA1968@johnsons-web.com> <0F013513-F67F-4DC2-AECE-ECA785DCCB38@gmail.com> Message-ID: <20101114222804.GD1968@johnsons-web.com> * Evert Rol [101114 12:12]: > Django can run be run through mod_wsgi (or mod_python if you > really want). And other web servers than Apache will also work. > Don't know what you mean with "shared server", but if you mean > multiple accounts running their web apps through one Apache > server, that can work (provided Apache is correctly configured). By "shared server", I mean a hosting situation where I would not be able to configure Apache. An example would be my own ISP's servers, which I avoid doing development work on *but* I just might have to. > It'll also depend on your needs, but since you don't specify any, > I'd suggest to look at Django first: http://www.djangoproject.com/ Actually, :) I *have* looked at django and I've considered it to have the greatest appeal. In fact, for most of my deployment environments I have SSH and root access. Django would be my first choice in that case, however, I would like to consider other cases as well, thus my question regarding "shared server". From http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ref=sr_1_2?s=books&ie=UTF8&qid=1289772638&sr=1-2 Can you comment on the following exerpt of the third review, where the reviewer says: """ .... one on deployment makes little mention of the fact that there's not really any good way to get Django running smoothly without root access to the server--something a lot of people do not have--and they actually expect their users to run TWO servers--one for Django and one for everything else, like image files. """ Thank you for the response. -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From jbiquez at icsmx.com Sun Nov 14 23:32:14 2010 From: jbiquez at icsmx.com (Jorge Biquez) Date: Sun, 14 Nov 2010 16:32:14 -0600 Subject: [Tutor] What was your strategy? Message-ID: <201011142240.oAEMeS8p054236@krusty.intranet.com.mx> Hello all. Quick question. I know some of you are with Python since started, some other maybe later. I was wondering if you can share what was the strategy you followed to master Python (Yes I know I have to work hard study and practice a lot). I mean did you use special books, special sites, a plan to learn each subject in a special way. I would like to know, if possible, comments specially from some of you who in the past had other languages, frameworks and platforms and left (almost) all of them and stayed with Python. Thanks in advance Jorge Biquez From evert.rol at gmail.com Sun Nov 14 23:36:32 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 14 Nov 2010 23:36:32 +0100 Subject: [Tutor] Recommend a MVC framework In-Reply-To: <20101114222515.GB1968@johnsons-web.com> References: <20101114202624.GA1968@johnsons-web.com> <0F013513-F67F-4DC2-AECE-ECA785DCCB38@gmail.com> <20101114222515.GB1968@johnsons-web.com> Message-ID: <53C571C5-D117-4A2A-92CA-5545EC7098B8@gmail.com> >> Django can run be run through mod_wsgi (or mod_python if you >> really want). And other web servers than Apache will also work. > >> Don't know what you mean with "shared server", but if you mean >> multiple accounts running their web apps through one Apache >> server, that can work (provided Apache is correctly configured). > By "shared server", I mean a hosting situation where I would not > be able to configure Apache. An example would be my own ISP's > servers, which I avoid doing development work on *but* I just > might have to. That will all depend on how the webserver is configured by the provider. Some will have a good setup, with mod_wsgi or mod_python already available, and allow lots of options configurable in .htaccess. Because of the popularity of PHP (some time ago, that was), a lot of webservers have mod_php configured by default for this. But there really is not difference (imho) between a webserver with mod_php or mod_wsgi. Trick is to tell a hosting provider that, or find one that allows that. fastcgi is one of the options for "alternative" Django deployments: http://docs.djangoproject.com/en/1.2/howto/deployment/fastcgi/ But I'd suggest to read through the various sections of http://docs.djangoproject.com/en/1.2/howto/deployment/ first. Or google around if you know what situation you're in: lots of examples out there for setups with limited (root) access. > From > http://www.amazon.com/Definitive-Guide-Django-Development-Second/dp/143021936X/ref=sr_1_2?s=books&ie=UTF8&qid=1289772638&sr=1-2 > Can you comment on the following exerpt of the third review, where > the reviewer says: > """ > .... > one on deployment makes little mention of the fact that there's > not really any good way to get Django running smoothly without > root access to the server--something a lot of people do not > have--and they actually expect their users to run TWO > servers--one for Django and one for everything else, like image > files. See above, and the Django folks only (strongly) suggest, not expect, to have two separate servers for Django & static stuff, but that's only for more heavily accessed websites. I'm running a website through fastcgi & using the same Apache to route both fastcgi and the static files (note that the static files don't go through Django/fastcgi though). Took a bit of figuring out how to set it up, but it now works excellent. See also the first comment on this comment ;-). Evert From hugo.yoshi at gmail.com Sun Nov 14 23:38:25 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 14 Nov 2010 23:38:25 +0100 Subject: [Tutor] While Loops: Coin Flip Game In-Reply-To: References: Message-ID: On Sun, Nov 14, 2010 at 11:16 PM, Dawn Samson wrote: > Greetings, > I'm a Python beginner and working my way through Michael Dawson's Python > Programming for the Absolute Beginner. I'm stuck in a particular challenge > that asks me to write a program that "flips a coin 100 times and then tells > you the number of heads and tails." I've been trying to work on this > challenge for a while now and can't get it to work (either it has 100 heads > or 100 tails). I've been reworking this code many times and currently what I > have does not do anything at all at IDLE. Please take a look at my code > below: When you, as you say it, "set the coin," you call the randrange function. This picks a random number between 0 and 1 and returns it. You then assign that number to the coin variable. So at this point, coin contains either 0 or 1. In the while loop, you have a line that simply says "coin." You probably think that this calls the function again, but it doesn't. What it actually does is nothing. You simply mention the variable to the interpreter, which retrieves its value (0 or 1). Since you don't do anything with that value, it is simply immediately discarded again. You need to change your code so that the coin isn't set only once, but every iteration of the loop. Hope that helps Hugo From tim at johnsons-web.com Sun Nov 14 23:46:55 2010 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 14 Nov 2010 13:46:55 -0900 Subject: [Tutor] Recommend a MVC framework In-Reply-To: <20101114202624.GA1968@johnsons-web.com> References: <20101114202624.GA1968@johnsons-web.com> Message-ID: <20101114224655.GE1968@johnsons-web.com> * Tim Johnson [101114 11:45]: > > One restriction: must *not* need an application server, I.E. works > thru Apache and is adaptable to a shared server. > thanks for all of who responded. I should clarify: I have been considering django as a first choice for most of the deployment environments I have access to, *but* am also looking for something as a fall-back that can be installed without SSH or root access. Looks like web2py may be the fall-back. thanks again. -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From steve at pearwood.info Sun Nov 14 23:48:31 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Nov 2010 09:48:31 +1100 Subject: [Tutor] python at midnight In-Reply-To: References: Message-ID: <4CE0673F.1050807@pearwood.info> ingo wrote: [...] > Questions, > Is there a date time library that accepts the 24:00? mxDateTime doesn't. I don't know of any. > Is there a way to set the limit 'from the outside' (subclassing???) or > a simple way around? Write a wrapper function: #Untested def datetime24(*args): try: return datetime.datetime(*args) except ValueError: args = list(args) if len(args) >= 4 and args[3] == 24: if ((not args[4:5] or args[4] == 0) and (not args[5:6] or args[5] == 0)): args[3] = 0 yesterday = datetime.datetime(*args) return yesterday + datetime.timedelta(1, 0, 0) raise This catches the error raised by the datetime object. If the hour is 24 and the minute and second arguments either don't exist, or are 0, it calculates the datetime from 0:00 instead of 24:00, then adds one day to it. Otherwise it re-raises the error. > How to get this functionality added to Python? Make a feature request on the Python bug tracker: http://bugs.python.org/ -- Steven From steve at pearwood.info Sun Nov 14 23:52:07 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Nov 2010 09:52:07 +1100 Subject: [Tutor] While Loops: Coin Flip Game In-Reply-To: References: Message-ID: <4CE06817.3030600@pearwood.info> Dawn Samson wrote: > I've been trying to work on this challenge for a while now and can't > get it to work (either it has 100 heads or 100 tails). Unfortunately your code has been mangled in the email, but I can guess your problem: you need to set coin = random.randrange(2) each time through the loop, not just once outside the loop. -- Steven From sdawn at live.ca Mon Nov 15 00:05:40 2010 From: sdawn at live.ca (Stephanie Dawn Samson) Date: Sun, 14 Nov 2010 16:05:40 -0700 Subject: [Tutor] While Loops: Coin Flip Game Message-ID: Thanks everyone! I should be using algorithms for even such programs at my level. The solution to reiterate the coin flip every time in the loop works. Thanks a lot! Dawn -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Mon Nov 15 00:09:58 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Sun, 14 Nov 2010 23:09:58 +0000 Subject: [Tutor] While Loops: Coin Flip Game In-Reply-To: References: Message-ID: <4CE06C46.1090207@gmail.com> On 14/11/10 22:16, Dawn Samson wrote: > Greetings, > > I'm a Python beginner and working my way through Michael Dawson's > Python Programming for the Absolute Beginner. I'm stuck in a > particular challenge that asks me to write a program that "flips a > coin 100 times and then tells you the number of heads and tails." I've > been trying to work on this challenge for a while now and can't get it > to work (either it has 100 heads or 100 tails). I've been reworking > this code many times and currently what I have does not do anything at > all at IDLE. Please take a look at my code below: > > import random > > # set the coin > coin = random.randrange(2) > headsCount = 0 > tailsCount = 0 > count = 0 > > # the loop > while count <= 100: > coin > if coin == 0: > headsCount += 1 > if coin == 1: > tailsCount += 1 > count += 1 > > print "The number of heads was", heads > print "The number of tails was", tails > > raw_input("\n\nPress the enter key to exit.") > > Thanks, > S. Dawn Samson You try to print two variables, "heads" and "tails" which don't exist. The other replies covered the other main problems. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Nov 15 00:13:07 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 15 Nov 2010 10:13:07 +1100 Subject: [Tutor] What was your strategy? In-Reply-To: <201011142240.oAEMeS8p054236@krusty.intranet.com.mx> References: <201011142240.oAEMeS8p054236@krusty.intranet.com.mx> Message-ID: <4CE06D03.8070601@pearwood.info> Jorge Biquez wrote: > I was wondering if you can share what was the strategy you followed to > master Python (Yes I know I have to work hard study and practice a lot). I started by working through the book "Learning Python" by Mark Lutz and David Ascher. I wrote lots and lots of little Python scripts and classes and functions, to get a feel for the language. I must have started a million different projects, and abandoned most of them due to time and distractions. I spent a *lot* of time on Usenet, comp.lang.python (also available on the python at python.org mailing list, I believe) reading people's questions and answering them, and generally having an opinion on nearly everything :) Any time somebody would ask a question that I thought I *could* handle, but didn't already know the answer, I would call up the interactive interpreter and try to solve the problem. I learned to *never* post code unless I'd run it myself, unless I clearly labeled it as untested or pseudo-code. Be prepared to get told You're Doing It Wrong a lot. This is a *good* thing -- you learn by making mistakes and being corrected. I read a LOT of idiomatic Python code by the masters: people like the timbot, the effbot, Raymond Hettinger, and many, many others. I read the Python Cookbook and studied their code. If they answered a question, I tried to understand how their answer was better than mine. Usually I learned something. Sometimes I thought I knew better. Most of the time that I thought I knew better, I learned that I didn't, and the rest of the time it was just a matter of personal taste. I spent a lot of time (and still do) looking up unfamiliar terms on Google. Wikipedia is your best friend. The Python Cookbook at ActiveState Python is your second best friend. The c2c wiki is *not* your friend, but you'll learn a lot from reading it. Since 90% of the discussions there are about Java, C or Lisp, what you'll mostly learn is how happy you are to be using Python instead. But the other 10% of the time will really stretch your brain. http://c2.com/cgi/wiki?WelcomeVisitors -- Steven From bermanrl at cfl.rr.com Sun Nov 14 23:47:04 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 14 Nov 2010 17:47:04 -0500 Subject: [Tutor] While Loops: Coin Flip Game In-Reply-To: References: Message-ID: <013901cb844d$dc500110$94f00330$@rr.com> From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Dawn Samson Sent: Sunday, November 14, 2010 5:17 PM To: tutor at python.org Subject: [Tutor] While Loops: Coin Flip Game >>>> Greetings, I'm a Python beginner and working my way through Michael Dawson's Python Programming for the Absolute Beginner import random # set the coin coin = random.randrange(2) headsCount = 0 tailsCount = 0 count = 0 # the loop while count <= 100: ?? ?coin ?? ?if coin == 0: ?? ? ? ?headsCount += 1 ?? ?if coin == 1: ?? ? ? ?tailsCount += 1 ?? ?count += 1 ?? ? print "The number of heads was", heads print "The number of tails was", tails raw_input("\n\nPress the enter key to exit.") Thanks, S. Dawn Samson >>>>> Hi, Think in terms of logical steps. You need to generate the results of a random coin toss for every toss of the coin. Therefore, if you are tossing 100 tosses, you need to generate 100 results based on a probability of zero or one. Since this is your homework assignment you write the code, but in terms of a logical frame work you would have something like the following. Tossknt = 1 Generate a random toss ; results being either one or 0. Further , assume 0 is tail; heads is one. If toss = 1 headcount = headcount + 1 Else tailcount = tailcount + 1 Tossknt = Tossknt + 1 If Tossknt < 100 Continue loop Else print ?nbr of heads tossed = ?, headcount Print ?nbr of tails tossed = ?, tailcount Obviously, this is not valid python code but it should give you enough information to solve your problem. Good luck, Robert -- I am using the free version of SPAMfighter. We are a community of 7 million users fighting spam. SPAMfighter has removed 53 of my spam emails to date. Get the free SPAMfighter here: http://www.spamfighter.com/len The Professional version does not have this message From mehgcap at gmail.com Mon Nov 15 01:12:42 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 14 Nov 2010 19:12:42 -0500 Subject: [Tutor] program hangs in while loop using wx.yield In-Reply-To: References: Message-ID: On 11/14/10, Alan Gauld wrote: > "Alex Hall" wrote > >> The problem is that I want to go until there is a winner. You are >> right about just letting the mainloop of the gui handle input (I >> forgot the gui is already looping and waiting for input) but I would >> like to make the user pause while the computer goes, this way the >> user >> cannot just keep hammering out moves as fast as possible > > Thats fine so you simple stop accepting input while the computer goes. > I'm sure your computer can keep up with aeven the fastest typist/mouse > clicker. If you really want to add a delay simply add a short pause in > your event handler - 1 second say. Or even better set a semaphore > which blocks any input and then a timer to reset it after a given > delay. > > This is all fairly satandard GUI practice none of which requires > complex > loops. You need to start thinking about a world controlled by the GUI > firing events( or messages if you like) telling you what is happening > which you catch and process. Is there a basic tutorial for this sort of thing? I think part of the problem is that both players have a Grid object. The human's grid includes a gui. For example, clicking a square will fire on that square. The computer has a grid as well, but (of course) with no gui element; its grid is simply an array holding its ships. All this to say that when the human fires, something happens to the gui but there is a lot of other updating going on behind the gui, in the human's grid object. When the computer "fires", its grid is updated as well, but not any gui, so message passing by the gui would not seem to apply. > >> be given to the user properly. Therefore, I have gotten rid of the >> loop I sent originally, but I still have a loop which switches >> between >> the two players > > Is it two players or is it a player and a computer. A human and a computer for now. I hope to one day add peer-to-peer support for two humans to play, but that was not working out at all so for now I am just trying to give myself some, even if it is digital, to play against. > If its the former you need a semaphore to block input from one > player until the other has gone. In chess terms the values might > be black and white and the semaphore called player. You then > either need two input handlers, one for black and one for white > which call a common utility fuction after checking the semaphor > or a single function that somehow can identify the player. > > If its the latter then the computer should be faster than a hiuman > so there should be little problem... Little problem for the computer, since its decision will be made in a fraction of a second. However, I need to wait for as long as the human takes to make a turn-ending move. Firing ends a turn, while moving the mouse or arrows does not. The computer does not have this problem, but I still need to know when the computer is done. > >> the other. If I fire (it is Battleship) and hit your ship,and I am >> the >> computer, then this loop will give you the information about where I >> fired. You will check to see if it was a hit and, since it was, pass >> back information about what was hit. You will also update the gui to >> reflect the new status of the damaged ship. > > I'm confusing you and I, its safer to use explicit trerms when > describing > interactions. But the displaing of information and updating the GUI > can > all happen in a blink of an eye if its the computer playing. You are right, that was confusing. What I am saying is that, each time a player goes (human or ai) a string gets updated. The opponent can then examine that string to see what happened, updating the gui (in the case of the human) accordingly and recording the information for consideration in future moves (in the case of the ai). > >> this, I do not want you firing as fast as possible, and I want you >> to >> take in the results before you are allowed to fire. > > Why do you care if the human "takes in the results" - if they want > to trust in randomness surely thats their problem. You as a computer > can match them blast for blast... Part of it is that I hope to eventually add sound, and the other part is that I have always found games that make a move instantly to be a bit too far from what I am used to. If it is easy to build in a delay, I would rather have it there. > >> while not player1.isWinner or not player2.isWinner: >> if player1.grid.turnOver: >> print("player2 is going") >> player1.grid.speak("player 2 is going.") >> player2.enemyMove=player1.grid.cmd #tell p2 what p1 just did >> player1.lock() #so p1 cannot interact with the gui >> player2.takeTurn() #decides what to do and updates its Grid object >> accordingly >> player1.grid.speak(helpers.interpret(player2.grid.cmd)) #just >> output what p2 did after takeTurn() is over >> elif player2.grid.turnOver: >> print("player1 is going") >> player1.enemyMove=player2.grid.cmd >> player1.unlock() #p1 can now interact with the gui >> player1.grid.speak("It is now your turn.") >> player1.takeTurn() >> #end if >> #wx.Yield() >> time.sleep(.1) >> #end while > > Still looks way too complicated to me! Me, too. > >> I am honestly not sure how all the control flows, but this loop is >> gone so hopefully it will not be a problem. > > You need to think about the control flow vfery carefully - after all > you the programmer are supposed to be in charge of your program! > And if you ever have to debug it you will need to understand > where the control is going next! Again: is there a basic tutorial that would explain how control works when dealing with a gui, especially one that is meant to last a long time but occasionally block input? > > HTH, > > -- > Alan Gauld > 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 > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Mon Nov 15 02:22:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Nov 2010 01:22:59 -0000 Subject: [Tutor] What was your strategy? References: <201011142240.oAEMeS8p054236@krusty.intranet.com.mx> Message-ID: "Jorge Biquez" wrote > I was wondering if you can share what was the strategy you followed > to master Python I started with Python 1.3 around early 1998 but switched to 1.5 very soon after. I started with the standard tutorial (I was already a pro programmer so it was easy to follow) then implemented some of my Perl and awk tools in Python for comparison's sake and just to gain some experience. I then bought a book by Guido which was adequate but not really well related to the programming things I do. I also bought the original Programming Python O'Reilly book and found it more helpful. Then around that time I was invited to review Grayson's Tkinter book - I'm not sure why, because I was still a Python newbie and only average on Tcl/Tk... I found Grayson's book more advanced than the stuff I'd been doing and it pushed me to explore new areas. I still refer to it regularly. Then I decided to write a tutorial on learning to program and chose Python as the preferred language. I also discovered the tutor list about the same time. The rest is history... or at least the list archive :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From paradox at pobox.com Mon Nov 15 02:49:41 2010 From: paradox at pobox.com (Thomas C. Hicks) Date: Mon, 15 Nov 2010 09:49:41 +0800 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: References: Message-ID: <20101115094941.54333711@midgel> On Sun, 14 Nov 2010 17:16:36 -0500 Dawn Samson wrote: > Greetings, > > I'm a Python beginner and working my way through Michael Dawson's > Python Programming for the Absolute Beginner. I'm stuck in a > particular challenge that asks me to write a program that "flips a > coin 100 times and then tells you the number of heads and tails." > I've been trying to work on this challenge for a while now and can't > get it to work (either it has 100 heads or 100 tails). I've been > reworking this code many times and currently what I have does not do > anything at all at IDLE. Please take a look at my code below: > > import random > > # set the coin > coin = random.randrange(2) > headsCount = 0 > tailsCount = 0 > count = 0 > > # the loop > while count <= 100: > coin > if coin == 0: > headsCount += 1 > if coin == 1: > tailsCount += 1 > count += 1 > > > print "The number of heads was", heads > print "The number of tails was", tails > > raw_input("\n\nPress the enter key to exit.") > > Thanks, > S. Dawn Samson From one beginner to another - it looks to me like you set the value of coin once then checked it 100 times. If you want to reset the value of coin maybe it (i.e. setting the value of coin, not just calling the value of coin) should be in the loop too? tom From wprins at gmail.com Mon Nov 15 02:59:43 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 15 Nov 2010 01:59:43 +0000 Subject: [Tutor] program hangs in while loop using wx.yield In-Reply-To: References: Message-ID: On 15 November 2010 00:12, Alex Hall wrote: > Again: is there a basic tutorial that would explain how control works > when dealing with a gui, especially one that is meant to last a long > time but occasionally block input? > Normally the way is for the GUI controls (e.g. widgets, grids, objects whatever you want to call them) to ignore messages (e.g. clicks or keyboard input or whatever). To achieve this one can either use properties/methods/behaviours already available on the widgets being used (e.g. Buttons have an "Enabled" property that allows you to control whether they're clickable or not), or you have to implementsuch behaviour yourself, using some flag/state variables in your application. As a tiny example, see here: http://pastebin.com/LqJkwpwA As you can see, each time one of the buttons are clicked, the click handler alters the buttons' enabled properties which ensures that only the other one will be clickable next. This example obviously sidestepped tracking "who's turn it is" explicitly by directly flipping the Enabled state on the 2 buttons. In your app I would suppose it'd be better to be explicit about it and have variables to store this type of information, which can then refer to in order to decide what to do inside your event handlers. HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From amonroe at columbus.rr.com Mon Nov 15 05:20:06 2010 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sun, 14 Nov 2010 23:20:06 -0500 Subject: [Tutor] Programs for Newbies? In-Reply-To: References: Message-ID: <6041071027.20101114232006@columbus.rr.com> > Any suggestions for a newbie to program while learning python? I am new to > programming and python. Port one of the old games from http://www.atariarchives.org/basicgames/ or similar antique books. Alan From ingoogni at gmail.com Mon Nov 15 08:25:40 2010 From: ingoogni at gmail.com (ingo) Date: Mon, 15 Nov 2010 08:25:40 +0100 Subject: [Tutor] python at midnight In-Reply-To: <4CE0673F.1050807@pearwood.info> References: <4CE0673F.1050807@pearwood.info> Message-ID: On Sun, Nov 14, 2010 at 11:48 PM, Steven D'Aprano wrote: > > Write a wrapper function: > Thanks Steve, with this in hand I think I can solve the main problems for now i. From alan.gauld at btinternet.com Mon Nov 15 09:20:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Nov 2010 08:20:56 -0000 Subject: [Tutor] program hangs in while loop using wx.yield References: Message-ID: "Alex Hall" wrote > Is there a basic tutorial for this sort of thing? There are a few books on the suvbject but I can't thik of any titles off the top of my head. And mostly they are written for C++ rather than Python. > fraction of a second. However, I need to wait for as long as the > human > takes to make a turn-ending move. Firing ends a turn, while moving > the > mouse or arrows does not. Thats OK you just wait till you get a Fire event. Presumably you have a dedicated "Fire" Button or somesuch? > The computer does not have this problem, but > I still need to know when the computer is done. What you really need is an indication on the GUI so that the player knows when the computer is done? All of the processing of the computers move will be part of the "Fire" button event handler. > You are right, that was confusing. What I am saying is that, each > time > a player goes (human or ai) a string gets updated. The opponent can > then examine that string to see what happened, updating the gui (in > the case of the human) accordingly and recording the information for > consideration in future moves (in the case of the ai). You might find it helpful to write down the system requirements as a set of "use cases". A use case is a dialog between user and system. So your description above would look something like: 1) user clicks cell on system 2) system updates display to indicate hit or miss 3) system displays target cell on GUI 4) system displays whether this is a hit or miss 5) continue at 1 In this example actions 2,3 and 4 can all be part of the same event handler. Or you could break it into two actions separated by a timer event. To prevent the user doing anything before the timer expires simply set a semaphore or disable the UI control. GUI design often uses a state machine, see the recent thread on state variables for more info. Keeping the integrity of the state machine is a large part of successful GUI design. In complex GUIS I often include a setState function (that gets called after every event) which simply sets the enabled/disabled properties for all the controls depending on the current state. This is usually a big table of states versus controls and I retrieve the two lists of enabled and disabled controls and iterate over them setting as appropriate... >> Why do you care if the human "takes in the results" - if they want >> to trust in randomness surely thats their problem. You as a >> computer >> can match them blast for blast... > Part of it is that I hope to eventually add sound, and the other > part > is that I have always found games that make a move instantly to be a > bit too far from what I am used to. If it is easy to build in a > delay, > I would rather have it there. Delays are easier as per my earlier message. Either just add a sleep(1) to your code or use a timer. I'd suggest the latter, its more work but it is more flexible and keeps the GUI responsive where it needs to be (menus, moving, resizeing, etc) In your case I'd do step 2 first then set a 1 second timer before doing steps 3 and 4. Disable the fire capability in step 2 and re-enable it after step 4. > Again: is there a basic tutorial that would explain how control > works > when dealing with a gui, especially one that is meant to last a long > time but occasionally block input? You probably can find one on GUI design or event driven programming but the best advice I can offer is to think about the dialog/use case approach. Every time the user does something you have to think about how the system will respond and map that to an event handler. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Mon Nov 15 16:16:30 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 15 Nov 2010 09:16:30 -0600 Subject: [Tutor] Threading and Sockets Message-ID: Hi, I'm working on creating a server/client bit of software using threading and sockets (it's a project so I can't use something like twisted), and I've run into a slight issue with my server. My server currently looks like this: class ClientThread(threading.Thread): def __init__(self, socketdata, server): threading.Thread.__init__(self) self.conn = socketdata[0] self.details = socketdata[1] self.server = server def run(self): ''' Method called when the Thread.start() method is called. ''' global CONNCOUNT CONNCOUNT -= 1 print("Getting data from {0}:{1}: ".format(self.details[0], self.details[1]), end='') data = self.conn.recv(1024) print(data) if data == 'quit': self.server.stop() self.conn.close() class Server(threading.Thread): def __init__(self, port=1500, max_connections=5): ''' Setup the server elements. ''' threading.Thread.__init__(self) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind(('localhost', 1500)) self.server.listen(5) self.keeprunning = True def run(self): global CONNCOUNT while self.keeprunning:#CONNCOUNT > 1: ClientThread(self.server.accept(), self).start() self.stop() def stop(self): ''' Stop the server. ''' print("Stopping server... maybe...") self.keeprunning = False # Close the socket connection self.server.close() print("Server stopped.") (CONNCOUNT is currently not used - I was using it to stop my server) My issue is that when I send 'quit' the server does (sort of) close, but (I think) the self.server.accept() is blocking, so until I try connecting a few more times, the server doesn't actually finish. So that's really my only question - how do I make my server completely stop when I'm done? Pointing me towards documentation would be perfectly fine, preferably with a hint about which function(s) I should look at. TIA Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Nov 15 16:44:51 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 15 Nov 2010 09:44:51 -0600 Subject: [Tutor] Threading and Sockets In-Reply-To: References: Message-ID: Well, I solved the issue myself I changed the server class to the following: class Server(threading.Thread): def __init__(self, port=1500, max_connections=5): ''' Setup the server elements. ''' threading.Thread.__init__(self) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind(('localhost', 1500)) self.server.listen(5) self.server.settimeout(5) self.keeprunning = True def run(self): global CONNCOUNT while self.keeprunning:#CONNCOUNT > 1: try: connection = self.server.accept() ClientThread(connection, self).start() except socket.timeout: # Just keep rolling pass self.stop() def stop(self): ''' Stop the server. ''' print("Stopping server... maybe...") self.keeprunning = False # Close the socket connection self.server.close() print("Server stopped.") With the timeout it will stop accepting a connection every 5 seconds, and then try again for another 5 seconds. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From scifiman4 at verizon.net Mon Nov 15 21:35:27 2010 From: scifiman4 at verizon.net (Matthew Denaburg) Date: Mon, 15 Nov 2010 15:35:27 -0500 Subject: [Tutor] Math: integers to a fractional power Message-ID: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> Hi, OK, so I have a question for you math people: I am trying to solve a quartic equation (Ax^4 + Bx^3 + Cx^2 + Dx + E) using Ferrari's Method, which I found on Wikipedia at this location. I'm using Python 3.1.2 (on Mac OS X 10.6, in case that matters). First, since I don't know Python very well, I was wondering if there is an easier way to do this, without having to install any modules. (I can't figure out how to put anything on my PYTHONPATH). If not there is not an easier way without installing a module, could someone recommend a module AND give me a link to detailed instructions for how to install it? I would PERFER to continue using Ferrari's Method, but am not opposed to trying something else. My only problem when using Ferrari's Method was this error: Traceback (most recent call last): File "Problem309.py", line 135, in print(main()) File "Problem309.py", line 127, in main math.pow(L1, 2)-math.pow(L2, 2)) File "Problem309.py", line 73, in sQuartic W = math.pow(alpha + 2 * y, 1/2) TypeError: can't convert complex to float Now, your first thought is probably that I have a negative number in the square root, or that I should be using math.sqrt. According to this method, I need to use cube roots as well, and I wanted to keep my code consistent. I also have checked, and the only variable that could be ending up as a complex number is the variable y. So, here is the code that assigns y: u = math.pow(Q, 2)/4 + math.pow(P, 3)/27 if u < 0: return None R = -(Q / 2) + math.pow(u, 1/2) U = R ** (1/3) y = -(5/6) * alpha + U if U == 0: y = y - Q ** (1/3) elif U != 0: y = y - P/(3*U) W = math.pow(alpha + 2 * y, (1/2)) The problem I am having is that, as far as I can tell, is that U is turning into a complex number, which is impossible! You can take the cube root of any number, positive or negative! So I tried in the Python Interpreter, and got this: >>> -27**(1/3) -3.0 >>> math.pow(-27, 1/3) Traceback (most recent call last): File "", line 1, in math.pow(-27, 1/3) ValueError: math domain error >>> Is there something going on here that I am unaware of? Please let me know!! Thanks so much! ---Matthew Denaburg -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Nov 15 22:30:37 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 15 Nov 2010 22:30:37 +0100 Subject: [Tutor] Math: integers to a fractional power In-Reply-To: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> References: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> Message-ID: <0B8F14A9-9B9B-4D80-9B6F-B56CE61D7339@gmail.com> > OK, so I have a question for you math people: I am trying to solve a quartic equation (Ax^4 + Bx^3 + Cx^2 + Dx + E) using Ferrari's Method, which I found on Wikipedia at this location. > > I'm using Python 3.1.2 (on Mac OS X 10.6, in case that matters). > > First, since I don't know Python very well, I was wondering if there is an easier way to do this, without having to install any modules. (I can't figure out how to put anything on my PYTHONPATH). > > If not there is not an easier way without installing a module, could someone recommend a module AND give me a link to detailed instructions for how to install it? > > I would PERFER to continue using Ferrari's Method, but am not opposed to trying something else. > > My only problem when using Ferrari's Method was this error: > > Traceback (most recent call last): > File "Problem309.py", line 135, in > print(main()) > File "Problem309.py", line 127, in main > math.pow(L1, 2)-math.pow(L2, 2)) > File "Problem309.py", line 73, in sQuartic > W = math.pow(alpha + 2 * y, 1/2) > TypeError: can't convert complex to float This may be more a result from the underlying C math library (also the exception you got below); I think the functions in that library are called when using functions from the math module, and the C library only works for non-complex numbers. You could have a look at the cmath module. However, you won't find a pow() function there. Instead, try using the built-in power operator: **, and use complex(): >>> complex(-27)**1/3. (-9+0j) >>> complex(-4)**(1/2.) (1.2246467991473532e-16+2j) Note the (classic) inaccuracy problem of floating points: the real part should simply be 0. (Also, create complex numbers with an imaginary part != 0 as: >>> complex(5, -2) (5-2j) ) Would that help you? Cheers, Evert > Now, your first thought is probably that I have a negative number in the square root, or that I should be using math.sqrt. According to this method, I need to use cube roots as well, and I wanted to keep my code consistent. I also have checked, and the only variable that could be ending up as a complex number is the variable y. So, here is the code that assigns y: > > u = math.pow(Q, 2)/4 + math.pow(P, 3)/27 > if u < 0: > return None > R = -(Q / 2) + math.pow(u, 1/2) > U = R ** (1/3) > y = -(5/6) * alpha + U > if U == 0: > y = y - Q ** (1/3) > elif U != 0: > y = y - P/(3*U) > W = math.pow(alpha + 2 * y, (1/2)) > > > The problem I am having is that, as far as I can tell, is that U is turning into a complex number, which is impossible! You can take the cube root of any number, positive or negative! > > So I tried in the Python Interpreter, and got this: > > >>> -27**(1/3) > -3.0 > >>> math.pow(-27, 1/3) > Traceback (most recent call last): > File "", line 1, in > math.pow(-27, 1/3) > ValueError: math domain error > > >>> > > Is there something going on here that I am unaware of? > > Please let me know!! Thanks so much! > > ---Matthew Denaburg > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Tue Nov 16 00:10:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 16 Nov 2010 10:10:32 +1100 Subject: [Tutor] Math: integers to a fractional power In-Reply-To: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> References: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> Message-ID: <4CE1BDE8.8080809@pearwood.info> Matthew Denaburg wrote: >>>> -27**(1/3) > -3.0 >>>> math.pow(-27, 1/3) > Traceback (most recent call last): > File "", line 1, in > math.pow(-27, 1/3) > ValueError: math domain error > > Is there something going on here that I am unaware of? Yes, various things. The precedence of the exponentiation operator ** is higher than that of the negation operator -, so -27**(1/3) is equivalent to: - (27 ** (1/3)) and there is no attempt to raise a negative number to a float. Thus: >>> -9**0.5 -3.0 Secondly, there are always N Nth-roots of a number: the familiar real root (or roots), and complex roots. For example: (-1)**2 = 1**2 = 1 so there are two square roots, +1 and -1. The same holds for higher powers, only the roots can be imaginary or complex. (Note: you shouldn't take "real" and "imaginary" in their plain English meanings -- imaginary numbers are just as "real" as real numbers, it's just a little harder to point to examples.) Python happens to return a complex root when using the ** operator: >>> (-27)**(1/3) (1.5000000000000002+2.5980762113533156j) Note the usual floating point issues: due to rounding, you don't always get the *exact* result: >>> ((-27)**(1/3))**3 (-26.999999999999993+1.0220990720455347e-14j) On the other hand, the pow() function refuses to perform exponentiation of a negative integer. I don't know why they have different behaviour -- possibly an accident that different people wrote the code for each, or possibly there is some deliberate reason for it. You might find the functions in the cmath (complex math) module useful for working with complex numbers. -- Steven From davea at ieee.org Tue Nov 16 02:11:42 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 15 Nov 2010 20:11:42 -0500 Subject: [Tutor] Math: integers to a fractional power In-Reply-To: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> References: <5F164F04-AE58-4A87-81B6-25580CDCD963@verizon.net> Message-ID: <4CE1DA4E.8050300@ieee.org> On 2:59 PM, Matthew Denaburg wrote: > Hi, > > OK, so I have a question for you math people: I am trying to solve a quartic equation (Ax^4 + Bx^3 + Cx^2 + Dx + E) using Ferrari's Method, which I found on Wikipedia at this location. > > I'm using Python 3.1.2 (on Mac OS X 10.6, in case that matters). > > First, since I don't know Python very well, I was wondering if there is an easier way to do this, without having to install any modules. (I can't figure out how to put anything on my PYTHONPATH). > > If not there is not an easier way without installing a module, could someone recommend a module AND give me a link to detailed instructions for how to install it? > > I would PERFER to continue using Ferrari's Method, but am not opposed to trying something else. > > My only problem when using Ferrari's Method was this error: > > Traceback (most recent call last): > File "Problem309.py", line 135, in > print(main()) > File "Problem309.py", line 127, in main > math.pow(L1, 2)-math.pow(L2, 2)) > File "Problem309.py", line 73, in sQuartic > W = math.pow(alpha + 2 * y, 1/2) > TypeError: can't convert complex to float > > Now, your first thought is probably that I have a negative number in the square root, or that I should be using math.sqrt. According to this method, I need to use cube roots as well, and I wanted to keep my code consistent. I also have checked, and the only variable that could be ending up as a complex number is the variable y. So, here is You don't have to guess. Once you come to that conclusion, check it. Put a print( y), or perhaps print (repr(y)) and check the value. > > > The problem I am having is that, as far as I can tell, is that U is turning into a complex number, which is impossible! You can take the cube root of any number, positive or negative! I don't know in particular, but if you were to raise a negative number to the .3333 power, the answer would be complex. Perhaps you're getting hit with some roundoff/quantization error. 1/3 cannot be exactlly represented, of course. I'd be curious if that's the situation here. If so, you could finesse the problem with the expression: sign * (abs(x) ** (1.0/3)) where sign is +1 or -1 representing the sign of x. DaveA From nithyakarpagam at gmail.com Tue Nov 16 05:08:47 2010 From: nithyakarpagam at gmail.com (Nithya Nisha) Date: Tue, 16 Nov 2010 09:38:47 +0530 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: <20101115094941.54333711@midgel> References: <20101115094941.54333711@midgel> Message-ID: Hi Tom, Your code is almost correct. Little mistake is there.The random number generate should be in while loop. > import random > > # set the coin > headsCount = 0 > tailsCount = 0 > count = 0 > > # the loop > while count < 100: #If you declare count = 0. The while loop condition should be less than 100.Else you will get 101 counts. > *coin = random.randrange(2)* > if coin == 0: > headsCount += 1 > else: #Becase We already declared randrange(2).So the coin value is 0 or 1.So we can use else condition. > tailsCount += 1 > count += 1 > > > print "The number of heads was", headsCount > print "The number of tails was", tailsCount > > raw_input("\n\nPress the enter key to exit.") Regards, Nithya _____________________________________________________________________________________________________________________________________________________________ * Your Description*: On Mon, Nov 15, 2010 at 7:19 AM, Thomas C. Hicks wrote: > On Sun, 14 Nov 2010 17:16:36 -0500 > Dawn Samson wrote: > > > Greetings, > > > > I'm a Python beginner and working my way through Michael Dawson's > > Python Programming for the Absolute Beginner. I'm stuck in a > > particular challenge that asks me to write a program that "flips a > > coin 100 times and then tells you the number of heads and tails." > > I've been trying to work on this challenge for a while now and can't > > get it to work (either it has 100 heads or 100 tails). I've been > > reworking this code many times and currently what I have does not do > > anything at all at IDLE. Please take a look at my code below: > > > > import random > > > > # set the coin > > coin = random.randrange(2) > > headsCount = 0 > > tailsCount = 0 > > count = 0 > > > > # the loop > > while count <= 100: > > coin > > if coin == 0: > > headsCount += 1 > > if coin == 1: > > tailsCount += 1 > > count += 1 > > > > > > print "The number of heads was", heads > > print "The number of tails was", tails > > > > raw_input("\n\nPress the enter key to exit.") > > > > Thanks, > > S. Dawn Samson > > >From one beginner to another - it looks to me like you set the value of > coin once then checked it 100 times. If you want to reset the value of > coin maybe it (i.e. setting the value of coin, not just calling > the value of coin) should be in the loop too? > > tom > _______________________________________________ > 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 petluke at gmail.com Tue Nov 16 05:22:05 2010 From: petluke at gmail.com (Luke Pettit) Date: Tue, 16 Nov 2010 15:22:05 +1100 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: References: <20101115094941.54333711@midgel> Message-ID: When I run this code (I'm also a noob) I get this result:- >>> [evaluate lines 1-22 from untitled-1.py] The number of heads was 73 The number of tails was 100 Press the enter key to exit. # Surely, if flipping a single coin 100 times your total number of heads and tails should add up to 100 # not 173 or am I missing the point? On 16 November 2010 15:08, Nithya Nisha wrote: > Hi Tom, > > Your code is almost correct. Little mistake is there.The random number > generate should be in while loop. > > > import random > > > > # set the coin > > > headsCount = 0 > > tailsCount = 0 > > count = 0 > > > > # the loop > > while count < 100: #If > you declare count = 0. The while loop condition should be less than > 100.Else you will get 101 counts. > > *coin = random.randrange(2)* > > if coin == 0: > > headsCount += 1 > > else: #Becase We > already declared randrange(2).So the coin value is 0 or 1.So we can use else > condition. > > tailsCount += 1 > > count += 1 > > > > > > print "The number of heads was", headsCount > > print "The number of tails was", tailsCount > > > > raw_input("\n\nPress the enter key to exit.") > > Regards, > Nithya > > > _____________________________________________________________________________________________________________________________________________________________ > * > Your Description*: > > On Mon, Nov 15, 2010 at 7:19 AM, Thomas C. Hicks wrote: > >> On Sun, 14 Nov 2010 17:16:36 -0500 >> Dawn Samson wrote: >> >> > Greetings, >> > >> > I'm a Python beginner and working my way through Michael Dawson's >> > Python Programming for the Absolute Beginner. I'm stuck in a >> > particular challenge that asks me to write a program that "flips a >> > coin 100 times and then tells you the number of heads and tails." >> > I've been trying to work on this challenge for a while now and can't >> > get it to work (either it has 100 heads or 100 tails). I've been >> > reworking this code many times and currently what I have does not do >> > anything at all at IDLE. Please take a look at my code below: >> > >> > import random >> > >> > # set the coin >> > coin = random.randrange(2) >> > headsCount = 0 >> > tailsCount = 0 >> > count = 0 >> > >> > # the loop >> > while count <= 100: >> > coin >> > if coin == 0: >> > headsCount += 1 >> > if coin == 1: >> > tailsCount += 1 >> > count += 1 >> > >> > >> > print "The number of heads was", heads >> > print "The number of tails was", tails >> > >> > raw_input("\n\nPress the enter key to exit.") >> > >> > Thanks, >> > S. Dawn Samson >> >> >From one beginner to another - it looks to me like you set the value of >> coin once then checked it 100 times. If you want to reset the value of >> coin maybe it (i.e. setting the value of coin, not just calling >> the value of coin) should be in the loop too? >> >> tom >> _______________________________________________ >> 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 > > -- Luke Pettit -------------- next part -------------- An HTML attachment was scrubbed... URL: From nithyakarpagam at gmail.com Tue Nov 16 05:41:35 2010 From: nithyakarpagam at gmail.com (Nithya Nisha) Date: Tue, 16 Nov 2010 10:11:35 +0530 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: <20101115094941.54333711@midgel> References: <20101115094941.54333711@midgel> Message-ID: Hi Tom, Your code is almost correct. Little mistake is there.The random number generate should be in while loop. > import random > > # set the coin > headsCount = 0 > tailsCount = 0 > count = 0 > > # the loop > while count < 100: #If you declare count = 0. The while loop condition should be less than 100.Else you will get 101 counts. > *coin = random.randrange(2)* > if coin == 0: > headsCount += 1 > else: #Becase We already declared randrange(2).So the coin value is 0 or 1.So we can use else condition. > tailsCount += 1 > count += 1 > > > print "The number of heads was", headsCount > print "The number of tails was", tailsCount > > raw_input("\n\nPress the enter key to exit.") Regards, Nithya __________________________________________________________________________________________________________________________________ *Your Description* On Mon, Nov 15, 2010 at 7:19 AM, Thomas C. Hicks wrote: > On Sun, 14 Nov 2010 17:16:36 -0500 > Dawn Samson wrote: > > > Greetings, > > > > I'm a Python beginner and working my way through Michael Dawson's > > Python Programming for the Absolute Beginner. I'm stuck in a > > particular challenge that asks me to write a program that "flips a > > coin 100 times and then tells you the number of heads and tails." > > I've been trying to work on this challenge for a while now and can't > > get it to work (either it has 100 heads or 100 tails). I've been > > reworking this code many times and currently what I have does not do > > anything at all at IDLE. Please take a look at my code below: > > > > import random > > > > # set the coin > > coin = random.randrange(2) > > headsCount = 0 > > tailsCount = 0 > > count = 0 > > > > # the loop > > while count <= 100: > > coin > > if coin == 0: > > headsCount += 1 > > if coin == 1: > > tailsCount += 1 > > count += 1 > > > > > > print "The number of heads was", heads > > print "The number of tails was", tails > > > > raw_input("\n\nPress the enter key to exit.") > > > > Thanks, > > S. Dawn Samson > > >From one beginner to another - it looks to me like you set the value of > coin once then checked it 100 times. If you want to reset the value of > coin maybe it (i.e. setting the value of coin, not just calling > the value of coin) should be in the loop too? > > tom > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- With Regards, Nithya S -------------- next part -------------- An HTML attachment was scrubbed... URL: From smiles at worksmail.net Tue Nov 16 07:26:09 2010 From: smiles at worksmail.net (C or L Smith) Date: Tue, 16 Nov 2010 12:11:09 +0545 Subject: [Tutor] Math: integers to a fractional power (Matthew Denaburg) References: Message-ID: <3277130F8A0E4095AC22127D15B49626@csmith> If you are interested in a symbolic solution or numerical solution without missing any of the possible roots (real or imaginary) you could check out sympy, a CAS that offers a quartic solution. It uses appropriate simplifications besides a general solution to the quartic. The code for this is in the polys/polyroots.py file; that code makes some calls to other routines in sympy so it's not totally self contained. It can be downloaded from sympy.org. It can be sandboxed at live.sympy.org (but that has an error in the quartic solution right now). It's a pretty quick install. Here it is in use: >>> from sympy import solve, Rational, var, nsimplify >>> var('x') # create a variable x >>> solve(x**4 + 3*x**3 - 2*x + x/3 + .7) # note the 0.7 float ... ... error message ending with ... CoercionFailed: can't convert 2.1 of type RR to ZZ So either use nsimplify to replace floats with rationals >>> ans = solve(nsimplify(x**4 + 3*x**3 - 2*x + x/3 + .7, rational=1)) >>> ans[0].n() -2.74495954970930 Or enter floats as Rationals from the start >>> ans = solve(x**4 + 3*x**3 - 2*x + x/3 + Rational(7, 10)) >>> ans[0].n() -2.74495954970930 You can use a symbol for the number that will take on a float >>> var('a') a >>> ans = solve(x**4 + 3*x**3 - 2*x + x/3 + a, x) # now indicate you want to solve for x Substitute 'a' with your desired float: >>> [w.subs(a, .7).n() for w in ans] # .n() means "give a numerical answer" [0.423047811447149 - 0.229393202547502*I, -2.74495954970930, 0.423047811447149 + 0.229393202547502*I, -1.10113607318500] The answer is there at index 1. Best regards, Chris From henri.heinonen at mbnet.fi Tue Nov 16 08:09:44 2010 From: henri.heinonen at mbnet.fi (Henri Heinonen) Date: Tue, 16 Nov 2010 09:09:44 +0200 Subject: [Tutor] I try to convert a MATLAB program to Python... Message-ID: Hi! Can you, please, try to help me with Python? I try to convert a MATLAB program to Python. Here are the MATLAB codes: http://pastebin.com/MbPZ8Z7X http://pastebin.com/dDnF5AF2 Here is my Python code: http://pastebin.com/jCPdLHx7 What is wrong with my Python code? The program doesn't produce quite the same lambdas as the MATLAB program does. Thanks for all the help! Henri. -------------- next part -------------- An HTML attachment was scrubbed... URL: From henri.heinonen at mbnet.fi Tue Nov 16 08:35:17 2010 From: henri.heinonen at mbnet.fi (Henri Heinonen) Date: Tue, 16 Nov 2010 09:35:17 +0200 Subject: [Tutor] I try to convert a MATLAB program to Python... In-Reply-To: References: Message-ID: These are the four (out of eight) first results I get with the MATLAB code: ---- >> nonhomog(0.2) nonhomog: using 300 grid points. BC1_disc_left = -4.8436e-12 BC1_disc_right = -1.1027e-13 BC2_disc_left = -1.1269e-11 BC2_disc_right = -1.8657e-13 lambda = 0.9976 V0 = 79.0637 nonhomog: using 300 grid points. BC1_disc_left = 8.5855e-12 BC1_disc_right = -1.4955e-13 BC2_disc_left = -9.4851e-12 BC2_disc_right = 3.7053e-12 lambda = 0.9969 V0 = 79.0637 nonhomog: using 300 grid points. BC1_disc_left = -4.2669e-12 BC1_disc_right = -3.8908e-15 BC2_disc_left = -1.0330e-10 BC2_disc_right = 8.6403e-13 lambda = 0.5464 V0 = 79.0606 nonhomog: using 300 grid points. BC1_disc_left = 2.9082e-12 BC1_disc_right = -5.5045e-15 BC2_disc_left = -8.5076e-13 BC2_disc_right = 3.7712e-13 lambda = -54.3440 V0 = 78.6880 ---- These are the four results I get with my Python code: ---- python nonhomog.py kappa = 15.7079632679 alpha = 0 nu = 0.2 nx_ = 300 BC1_disc_left = (nan+nanj) BC1_disc_right = (nan+nanj) BC2_disc_left = (nan+nanj) BC2_disc_right = (nan+nanj) lambda = -0.774244159818 nonhomog.py:81: DeprecationWarning: integer argument expected, got float xx = range(-kappa, h, kappa+1) kappa = 15.7079632679 alpha = 5.80527619798e-06 nu = 0.2 nx_ = 300 BC1_disc_left = (nan+nanj) BC1_disc_right = (nan+nanj) BC2_disc_left = (nan+nanj) BC2_disc_right = (nan+nanj) lambda = -0.774244180107 kappa = 15.7079632679 alpha = 0.000580527619798 nu = 0.2 nx_ = 300 BC1_disc_left = (nan+nanj) BC1_disc_right = (nan+nanj) BC2_disc_left = (nan+nanj) BC2_disc_right = (nan+nanj) lambda = -0.774246188696 kappa = 15.7079632679 alpha = 0.0580527619798 nu = 0.2 nx_ = 300 BC1_disc_left = (nan+nanj) BC1_disc_right = (nan+nanj) BC2_disc_left = (nan+nanj) BC2_disc_right = (nan+nanj) lambda = -0.774447043715 ---- Some questions: 1. For example, the sign of the lambdas are wrong not to mention that the values are not even near the corresponding MATLAB values. How to fix these? 2. Also, I get those annoying (nan+nanj) messages for BC1s and BC2s. What's wrong? 3. There is also this error message: "nonhomog.py:81: DeprecationWarning: integer argument expected, got float xx = range(-kappa, h, kappa+1)". How should I fix that? Thanks! Henri. 2010/11/16 Henri Heinonen > Hi! > > Can you, please, try to help me with Python? I try to convert a MATLAB > program to Python. > > Here are the MATLAB codes: > http://pastebin.com/MbPZ8Z7X > http://pastebin.com/dDnF5AF2 > > Here is my Python code: > http://pastebin.com/jCPdLHx7 > > What is wrong with my Python code? The program doesn't produce quite the > same lambdas as the MATLAB program does. > > Thanks for all the help! > > Henri. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Tue Nov 16 08:37:05 2010 From: carroll at tjc.com (Terry Carroll) Date: Mon, 15 Nov 2010 23:37:05 -0800 (PST) Subject: [Tutor] program hangs in while loop using wx.yield In-Reply-To: References: Message-ID: On Sun, 14 Nov 2010, Alex Hall wrote: > Is there a basic tutorial for this sort of thing? Chapter 3 ("Working in an event-driven environment") of the book "wxPython in Action" is a pretty good tutorial on event-driven GUI programming in wxPython. The book in general is pretty good; I no longer buy many computer books, but this one was worth it. If you don't want to buy it, if you're in the U.S., you can go to http://www.worldcat.org/oclc/67122432 and plug in your zip code to see if a library near you[1] has it. [1] or a library that has inter-library loan arrangements with a library near you. I'm currently reading "Essential SQLAlchemy," courtesy of the San Diego State University library. My local library (San Jose Public Library) borrowed it from SDSU and then lent it to me. It's kind of cool that one library will send a book 400 miles to another, just because I'm too cheap to buy a copy and asked for it. Apologies to anyone at SDSU who's learning SQLAlchemy and wondering why they can't find this book in their library. From davea at ieee.org Tue Nov 16 08:55:09 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 16 Nov 2010 02:55:09 -0500 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: References: <20101115094941.54333711@midgel> Message-ID: <4CE238DD.50705@ieee.org> > When I run this code (I'm also a noob) I get this result:- > >>>> [evaluate lines 1-22 from untitled-1.py] > The number of heads was 73 > The number of tails was 100 > > Press the enter key to exit. > > # Surely, if flipping a single coin 100 times your total number of heads and > tails should add up to 100 > # not 173 or am I missing the point? > > No, you're missing an indentation. If you check the code you're running, I think you'll find that you didn't unindent the line incrementing count. Of course, it's less error prone to simply use for count in xrange(100): instead of while count < 100: and you wouldn't need to increment count. DaveA From nithyakarpagam at gmail.com Tue Nov 16 09:10:31 2010 From: nithyakarpagam at gmail.com (Nithya Nisha) Date: Tue, 16 Nov 2010 13:40:31 +0530 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: <4CE238DD.50705@ieee.org> References: <20101115094941.54333711@midgel> <4CE238DD.50705@ieee.org> Message-ID: Hi there, This is the Code. Please check it.It is working fine. >>>import random >>>headsCount = 0 >>>tailsCount = 0 >>>count = 1 >>> >>>while count <= 100: >>> coin = random.randrange(2) >>> if coin == 0: >>> headsCount += 1 >>> else: >>> tailsCount += 1 >>> count += 1 >>> >>>print "The number of heads was", headsCount >>>print "The number of tails was", tailsCount >>> >>>raw_input("\n\nPress the enter key to exit.") ________________________________________________________________________________________________________________ * Your Description *: On Tue, Nov 16, 2010 at 1:25 PM, Dave Angel wrote: > When I run this code (I'm also a noob) I get this result:- >> >> [evaluate lines 1-22 from untitled-1.py] >>>>> >>>> The number of heads was 73 >> The number of tails was 100 >> >> Press the enter key to exit. >> >> # Surely, if flipping a single coin 100 times your total number of heads >> and >> tails should add up to 100 >> # not 173 or am I missing the point? >> >> >> No, you're missing an indentation. If you check the code you're running, > I think you'll find that you didn't unindent the line incrementing count. > > Of course, it's less error prone to simply use > for count in xrange(100): > > instead of while count < 100: > > and you wouldn't need to increment count. > > DaveA > > -- With Regards, Nithya S -------------- next part -------------- An HTML attachment was scrubbed... URL: From petluke at gmail.com Tue Nov 16 09:21:58 2010 From: petluke at gmail.com (Luke Pettit) Date: Tue, 16 Nov 2010 19:21:58 +1100 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: References: <20101115094941.54333711@midgel> <4CE238DD.50705@ieee.org> Message-ID: Arrr thats better Nithya it works fine now. I had it working fine before it was just coming up with that strange result of 73 and 100 when I copied the code into wing to check it out in order to understand it. Wing picked up the spacing and I had already corrected that Dave as I was simply looking at Nithya code. On 16 November 2010 19:10, Nithya Nisha wrote: > Hi there, > > This is the Code. Please check it.It is working fine. > > >>>import random > >>>headsCount = 0 > >>>tailsCount = 0 > >>>count = 1 > >>> > >>>while count <= 100: > >>> coin = random.randrange(2) > >>> if coin == 0: > >>> headsCount += 1 > >>> else: > >>> tailsCount += 1 > >>> count += 1 > >>> > >>>print "The number of heads was", headsCount > >>>print "The number of tails was", tailsCount > >>> > >>>raw_input("\n\nPress the enter key to exit.") > > > ________________________________________________________________________________________________________________ > * > Your Description *: > > On Tue, Nov 16, 2010 at 1:25 PM, Dave Angel wrote: > >> When I run this code (I'm also a noob) I get this result:- >>> >>> [evaluate lines 1-22 from untitled-1.py] >>>>>> >>>>> The number of heads was 73 >>> The number of tails was 100 >>> >>> Press the enter key to exit. >>> >>> # Surely, if flipping a single coin 100 times your total number of heads >>> and >>> tails should add up to 100 >>> # not 173 or am I missing the point? >>> >>> >>> No, you're missing an indentation. If you check the code you're >> running, I think you'll find that you didn't unindent the line incrementing >> count. >> >> Of course, it's less error prone to simply use >> for count in xrange(100): >> >> instead of while count < 100: >> >> and you wouldn't need to increment count. >> >> DaveA >> >> > > > -- > With Regards, > Nithya S > > -- Luke Pettit -------------- next part -------------- An HTML attachment was scrubbed... URL: From roberto03 at gmail.com Tue Nov 16 11:49:04 2010 From: roberto03 at gmail.com (roberto) Date: Tue, 16 Nov 2010 11:49:04 +0100 Subject: [Tutor] new turtle module In-Reply-To: References: Message-ID: On Fri, Oct 8, 2010 at 1:11 AM, Alan Gauld wrote: > > "roberto" wrote > >> is it correct to overwrite the turtle.py and turtle.pyc files > > I'd overwrite the .py file but get Python to generate a new .pyc for you > just to ensure compatibility. > > just type import turtle at the >>> prompt. > thanks it works -- roberto From nithyakarpagam at gmail.com Tue Nov 16 13:41:10 2010 From: nithyakarpagam at gmail.com (Nithya Nisha) Date: Tue, 16 Nov 2010 18:11:10 +0530 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: References: <20101115094941.54333711@midgel> <4CE238DD.50705@ieee.org> Message-ID: Thankyou..!!! Regards, Nithya On Tue, Nov 16, 2010 at 1:51 PM, Luke Pettit wrote: > Arrr thats better Nithya it works fine now. I had it working fine before > it was just coming up with that strange result of 73 and 100 > when I copied the code into wing to check it out in order to understand it. > Wing picked up the spacing and I had already corrected > that Dave as I was simply looking at Nithya code. > > > On 16 November 2010 19:10, Nithya Nisha wrote: > >> Hi there, >> >> This is the Code. Please check it.It is working fine. >> >> >>>import random >> >>>headsCount = 0 >> >>>tailsCount = 0 >> >>>count = 1 >> >>> >> >>>while count <= 100: >> >>> coin = random.randrange(2) >> >>> if coin == 0: >> >>> headsCount += 1 >> >>> else: >> >>> tailsCount += 1 >> >>> count += 1 >> >>> >> >>>print "The number of heads was", headsCount >> >>>print "The number of tails was", tailsCount >> >>> >> >>>raw_input("\n\nPress the enter key to exit.") >> >> >> ________________________________________________________________________________________________________________ >> * >> Your Description *: >> >> On Tue, Nov 16, 2010 at 1:25 PM, Dave Angel wrote: >> >>> When I run this code (I'm also a noob) I get this result:- >>>> >>>> [evaluate lines 1-22 from untitled-1.py] >>>>>>> >>>>>> The number of heads was 73 >>>> The number of tails was 100 >>>> >>>> Press the enter key to exit. >>>> >>>> # Surely, if flipping a single coin 100 times your total number of heads >>>> and >>>> tails should add up to 100 >>>> # not 173 or am I missing the point? >>>> >>>> >>>> No, you're missing an indentation. If you check the code you're >>> running, I think you'll find that you didn't unindent the line incrementing >>> count. >>> >>> Of course, it's less error prone to simply use >>> for count in xrange(100): >>> >>> instead of while count < 100: >>> >>> and you wouldn't need to increment count. >>> >>> DaveA >>> >>> >> >> >> -- >> With Regards, >> Nithya S >> >> > > > -- > Luke Pettit > -------------- next part -------------- An HTML attachment was scrubbed... URL: From patty at cruzio.com Tue Nov 16 19:08:28 2010 From: patty at cruzio.com (Patty) Date: Tue, 16 Nov 2010 10:08:28 -0800 Subject: [Tutor] program hangs in while loop using wx.yield References: Message-ID: <8A80413D6F784D5FBBB0572FEFD9776F@mycomputer> Hi Terry - I am an alumni of UCSC (University of California, Santa Cruz) and live really close so I can request books throughout the UC system just like you describe and there is no limit - or maybe an extremely high limit - to the number of books I can check out from McHenry Library. It is so worth paying alumni dues! There is no way they would transport books to the public library to make it easier for people though - not with the way the city and the university feel about each other :} And discounts on courses through the University Extension program. That is how I found out about - and took - the online Python for Programmers course. Though I wasn't really happy with it and went on to listen to the Google website video - that guy was very clear and helpful I forgot his name. And then I went through Alan Gauld's tutorial which also helped. By coincidence I am still working on my own function where I want to display a picture and some text and have a timer so that it stays on screen for a specific amount of time and then I go on to close that out and redraw the screen. I am working with the Tkinter documentation and trying to understand. I tried a couple tests just adding a few lines to my own program that didn't accomplish exactly what I want, so planning to type in very simple examples from the doc, observe that and then go back to my own code. If I just can't figure out how to do this with Tkinter and the Python Imaging Library, is 'wxPython' the additional software I would want to install and try with? Is its purpose to make GUI event programming easier (that would mean the defaults provided are difficult, right? So I shouldn't feel bad about being confused?) If so, can someone explain these additional software packages out there? I mean are they coming from some third companies? And why? If the software is free. I'm not understanding the history or business part of these Python modules and libraries. Isn't there one organization who is discussing or approving standards for this language? Regards, Patty ----- Original Message ----- From: "Terry Carroll" To: Sent: Monday, November 15, 2010 11:37 PM Subject: Re: [Tutor] program hangs in while loop using wx.yield > On Sun, 14 Nov 2010, Alex Hall wrote: > >> Is there a basic tutorial for this sort of thing? > > Chapter 3 ("Working in an event-driven environment") of the book "wxPython > in Action" is a pretty good tutorial on event-driven GUI programming in > wxPython. The book in general is pretty good; I no longer buy many > computer books, but this one was worth it. > > If you don't want to buy it, if you're in the U.S., you can go to > http://www.worldcat.org/oclc/67122432 and plug in your zip code to see if > a library near you[1] has it. > > [1] or a library that has inter-library loan arrangements with a library > near you. I'm currently reading "Essential SQLAlchemy," courtesy of the > San Diego State University library. My local library (San Jose Public > Library) borrowed it from SDSU and then lent it to me. It's kind of cool > that one library will send a book 400 miles to another, just because I'm > too cheap to buy a copy and asked for it. > > Apologies to anyone at SDSU who's learning SQLAlchemy and wondering why > they can't find this book in their library. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From carroll at tjc.com Tue Nov 16 19:38:19 2010 From: carroll at tjc.com (Terry Carroll) Date: Tue, 16 Nov 2010 10:38:19 -0800 (PST) Subject: [Tutor] wxPython, Tkinter (was: program hangs in while loop using wx.yield In-Reply-To: <8A80413D6F784D5FBBB0572FEFD9776F@mycomputer> References: <8A80413D6F784D5FBBB0572FEFD9776F@mycomputer> Message-ID: On Tue, 16 Nov 2010, Patty wrote: > Hi Terry - I am an alumni of UCSC (University of California, Santa Cruz) > and live really close so I can request books throughout the UC system > just like you describe and there is no limit - or maybe an extremely > high limit - to the number of books I can check out from McHenry > Library. It is so worth paying alumni dues! There is no way they would > transport books to the public library to make it easier for people > though - not with the way the city and the university feel about each > other :} You might be surprised. I would't have expected to get a book from San Diego State University sent to the San Jose Public Library, but it did. I just entered teh request, and a few hours later, I had anote saying it was on the way. The system finds the copy and obtains it. It's not on a one-to-one basis, i.e., as if SJPL had an arrangement with SDSU; it's more of the libraries deciding to patricipate in the pool. > If I just can't figure out how to do this with Tkinter and the Python Imaging > Library, is 'wxPython' the additional software I would want to install and > try with? wxPython is an alternative to Tkinter. The advantage of Tkinter is that it comes as part of standard Python. You know that it will be installed on any reasonably current Python installation. If you write a program using Tkinter and send it to me, you can be sure that I can run it as long as I have Python installed (at least as far as the GUI is concerned; other things such as PIL might still be an issue). wxPython is an API over the cross-platform wxWidgets GUI. I think it provides a cleaner and more native look compared to Tkinter. For what my opinion is work (and that's not much -- I'm pretty inexperienced at GUI stuff), I find it at least as easy to use as Tkinter, but I recall a learning curve when I started. I don't use Tkinter any more, preferring wxPython, but opinions will vary. Here's a comparison of the two; it's hosted on a wxPython site, so it's undoubtedly slanted toward wxPython: http://wiki.wxpython.org/Choosing%20wxPython%20over%20Tkinter Another couple: http://www.llaisdy.com/static/tech/python/calc.html http://ojs.pythonpapers.org/index.php/tpp/article/viewArticle/61 However, if you would like an example of using Tkinter with PIL, I would be happy to provide you with a very rough program I wrote several years ago for my own use (when I still used Tkinter). It loads an image that was taken with a digital camera; reads the date the photo was taken from the image's EXIF data; adds a timestamp to the photo, and saves it. It's very rough; I have the habit of writing something only to the point where it's good enough for me, and then stop development on it. But you might find it helpful of a straightforward program that uses both. It's from about 2006 or so, and I am by no means a GUI programming expert and was even less so then, so my techniques may be suspect; but I'd be happy to send it to you for what it's worth. From wprins at gmail.com Tue Nov 16 20:29:15 2010 From: wprins at gmail.com (Walter Prins) Date: Tue, 16 Nov 2010 19:29:15 +0000 Subject: [Tutor] program hangs in while loop using wx.yield In-Reply-To: <8A80413D6F784D5FBBB0572FEFD9776F@mycomputer> References: <8A80413D6F784D5FBBB0572FEFD9776F@mycomputer> Message-ID: Not wanting to hijack Terry's conversation, but for what it's worth: On 16 November 2010 18:08, Patty wrote: > If I just can't figure out how to do this with Tkinter and the Python > Imaging Library, is 'wxPython' the additional software I would want to > install and try with? Is its purpose to make GUI event programming easier > (that would mean the defaults provided are difficult, right? So I shouldn't > feel bad about being confused?) If so, can someone explain these additional > software packages out there? I mean are they coming from some third > companies? And why? If the software is free. I'm not understanding the > history or business part of these Python modules and libraries. Isn't there > one organization who is discussing or approving standards for this language? > wxPython is a set of Python wrappers for the wxWidgets GUI component set. wxWidgets in turn is a set of C++ GUI wrapper controls that wraps the native GUI controls (e.g. edit boxes, memo boxes, drop downs, buttons, radio buttons, checkboxes, menu's and so on) on various platforms. Hence it thus provides a common set of classes/components/controls and effectively a common API for writing GUI based applications in a cross platform fashion, e.g. that target multiple platforms (e.g. Mac, Windows, Unix, Linux etc.) So, by using wxPython you can write applications knowing that your app should work pretty much unmodified on any system where wxWidgets is available/installed. wxWidgets as well as wxPython is open source, so the source is freely available and managed/supported by their respective development teams. For more see: http://www.wxwidgets.org/about/ http://www.wxpython.org/what.php You can download and install wxPython for Windows here (make sure to get the one corresponding to the version of Python that you have installed.): http://www.wxpython.org/download.php#stable You should also install the demo application and documentation. The demo application will give you an idea of what you can do and how to do it. As an aside, there are other similar (competing) libraries that one might use, e.g. GTK or QT for example (or for that matter TK), which needless to say also have Python wrappers. Which to use is largely a matter of context and taste, but suffice it to say wx is not a bad choice. It's however quite large, so don't expect it to all sink in overnight. (I certainly am no wx expert, I just know enough to be dangerous ;) ) As for Event driven programming, it takes a little getting used to if you're only used to normal "straight line" programs at this point, GUI programming adds its own set up of detail and complexity on top of the event-driven programming model (not least that it usually demands a relatively solid understanding of OO concepts), so don't feel bad if you're feeling confused. (You might want to read up/google "Event driven programming" and do some research and come back with more questions after you've tried a few things yourself.) That's my ?0.01 worth anyway, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdawn at live.ca Tue Nov 16 21:36:34 2010 From: sdawn at live.ca (Stephanie Dawn Samson) Date: Tue, 16 Nov 2010 13:36:34 -0700 Subject: [Tutor] While Loops: Coin Flip Game :p: Message-ID: Greetings, As a thread starter, I thought I should write the rewritten code I got that others helped me get to, since this thread is still going on. # Coin Flips# The program flips a coin 100 times and then# tells you the number of heads and tailsimport random print "\a"print "\tWelcome to 'Coin Flipper!'"print "\nI will flip a coin 100 times and then tell you"print "the number of heads and tails!\n" # set the coinheadsCount = 0tailsCount = 0count = 1 while count <= 100: coin = random.randrange(2) if coin == 0: headsCount += 1 else: tailsCount += 1 count += 1 print "The number of heads was", headsCountprint "The number of tails was", tailsCount raw_input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 16 23:36:47 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Nov 2010 22:36:47 -0000 Subject: [Tutor] program hangs in while loop using wx.yield References: <8A80413D6F784D5FBBB0572FEFD9776F@mycomputer> Message-ID: "Patty" wrote > then I went through Alan Gauld's tutorial which also helped. Glad to hear it :-) > If I just can't figure out how to do this with Tkinter and the > Python I can send some basic code if that would help... > Imaging Library, is 'wxPython' the additional software I would want > to install and try with? Is its purpose to make GUI event > programming easier No, in fact it is similar in concept to Tkinter but works in a style more like most other GUI toolkits. It is also far more powerful with more widgets and more complex styling tools and support for printing(as in paper). Tkinter is catching up on the native look department through the new ttk widgets but wxWidgets are nativbe from the ground up so they will probably always look slightly more "natural". But for your application wxPython and Tkinter should wind up looking pretty much the same both in terms of code and end result,. > feel bad about being confused?) If so, can someone explain these > additional software packages out there? I mean are they coming from > some third companies? And why? If the software is free. I'm not > understanding the history or business part of these Python modules > and libraries. Open source works like this: Somebody finds they need somethjing built so they build it. Then they think, maybe other people could use this, so they announce its availability (usually after polishing it a bit, adding some comments etc) Other people start using it, they ask for extra features, or they add some themselves and send it to the author. Gradually a core team of developers forms and they start publishing regular updates and bug fixes. It is all very organic and apparently disorganised but it works most of the time. Code that isn't very good but serves a need gradually gets improved - or eventually rewritten from scratch - and code that is not really needed tends to just wither and die from lack of support. Some projects grow into huge undertakings like GNU and Linux and OpenOffice etc. These might be sponsored by large (or small) companies providing their paid staff to contribute to the project because they find it critical to their business (so they want to ensure it stays viable) or they see strategic advantage - eg Sun's support for OpenmOffice as an alternative to MS Office... Most of Python and its modules come from such a background. > one organization who is discussing or approving standards for this > language? There is a community which is loosely organised and a process for submitting changes etc. How it works varies from project to project. You can see it all in action if you visit SourceForge the home of many OpenSource projects both large and small. But there is nothing like the formalised standards surrounding languages like C or COBOL or Java. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 16 23:46:35 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Nov 2010 22:46:35 -0000 Subject: [Tutor] While Loops: Coin Flip Game :p: References: Message-ID: "Stephanie Dawn Samson" wrote > thought I should write the rewritten code I got that others helped > me get to By applying a couple of other ideas that have been suggested you get something shorter and arguably slightly clearer: # Coin Flips # The program flips a coin 100 times and then # tells you the number of heads and tails import random print """ Welcome to 'Coin Flipper!' I will flip a coin 100 times and then tell you the number of heads and tails! """ headsCount = 0 for count in range(100): if random.randrange(2): # returns 1/0 => true/False headsCount += 1 print "The number of heads was", headsCount print "The number of tails was", 100-headsCount raw_input("\n\nPress the enter key to exit.") And you could replace the whole for loop with a generator expression if you really wanted to, but I suspect that is getting into advanced territory for you at this stage... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Wed Nov 17 05:00:22 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 16 Nov 2010 23:00:22 -0500 Subject: [Tutor] While Loops: Coin Flip Game :p: In-Reply-To: References: Message-ID: <4CE35356.6060400@gmail.com> Just for the heck of it: heads = sum(random.randrange(2) for i in range(100)) -- Bob Gailer 919-636-4239 Chapel Hill NC From ingoogni at gmail.com Wed Nov 17 13:11:36 2010 From: ingoogni at gmail.com (ingo) Date: Wed, 17 Nov 2010 13:11:36 +0100 Subject: [Tutor] python at midnight In-Reply-To: <4CE0673F.1050807@pearwood.info> References: <4CE0673F.1050807@pearwood.info> Message-ID: On Sun, Nov 14, 2010 at 11:48 PM, Steven D'Aprano wrote: >> How to get this functionality added to Python? > > Make a feature request on the Python bug tracker: > > http://bugs.python.org/ done: http://bugs.python.org/issue10427 i. From hanlie.pretorius at gmail.com Wed Nov 17 14:59:19 2010 From: hanlie.pretorius at gmail.com (Hanlie Pretorius) Date: Wed, 17 Nov 2010 15:59:19 +0200 Subject: [Tutor] Accessing columns of a CSV file Message-ID: Hi, I'm reading a CSV file and I want to test the contents of its second column before I write it to an output file: >>> import csv >>> time_list=['00:00', '03:00', '06:00','09:00','12:00','15:00','18:00','21:00'] >>> readfile='C8R004_flow.csv' >>> in_text=open(readfile,'rb') >>> cr=csv.reader(in_text) >>> cr <_csv.reader object at 0x7f4dfc3b2360> >>> for row in cr: ... print row ['2005/01/31', '21:00:00', '26.508'] ['2005/01/31', '21:12:00', '26.508'] ['2005/01/31', '21:24:00', '26.508'] ['2005/01/31', '21:36:00', '26.508'] ['2005/01/31', '21:48:00', '26.508'] ['2005/01/31', '22:00:00', '26.508'] ['2005/01/31', '22:12:00', '26.508'] ['2005/01/31', '22:24:00', '26.508'] ['2005/01/31', '22:36:00', '26.508'] ['2005/01/31', '22:48:00', '26.508'] ['2005/01/31', '23:00:00', '26.508'] ['2005/01/31', '23:12:00', '26.508'] ['2005/01/31', '23:24:00', '26.508'] ['2005/01/31', '23:36:00', '26.508'] ['2005/01/31', '23:48:00', '26.508'] >>> I would like to test the values in the second column to see if they're in the list I named time_list and, if so, write the whole row to an output file. The problem is that I don't know how to access the second column of values. I tried the direct route: >>> for row in cr: ... print cr[1] ... >>> and I've tried to convert the csv.reader object into a list: [code] >>> file_rows=[] >>> for row in cr: ... file_rows.append(row) ... >>> file_rows [] [/code] which clearly doesn't work. Can someone perhaps suggest a method to access the value in the second column of each row so that I can test it against the time_list? Thanks Hanlie From adam.jtm30 at gmail.com Wed Nov 17 15:05:59 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 17 Nov 2010 14:05:59 +0000 Subject: [Tutor] Accessing columns of a CSV file In-Reply-To: References: Message-ID: <4CE3E147.3000402@gmail.com> On 17/11/10 13:59, Hanlie Pretorius wrote: > Hi, > > I'm reading a CSV file and I want to test the contents of its second > column before I write it to an output file: > > >>>> import csv >>>> time_list=['00:00', '03:00', '06:00','09:00','12:00','15:00','18:00','21:00'] >>>> readfile='C8R004_flow.csv' >>>> in_text=open(readfile,'rb') >>>> cr=csv.reader(in_text) >>>> cr >>>> > <_csv.reader object at 0x7f4dfc3b2360> > >>>> for row in cr: >>>> > ... print row > ['2005/01/31', '21:00:00', '26.508'] > ['2005/01/31', '21:12:00', '26.508'] > ['2005/01/31', '21:24:00', '26.508'] > ['2005/01/31', '21:36:00', '26.508'] > ['2005/01/31', '21:48:00', '26.508'] > ['2005/01/31', '22:00:00', '26.508'] > ['2005/01/31', '22:12:00', '26.508'] > ['2005/01/31', '22:24:00', '26.508'] > ['2005/01/31', '22:36:00', '26.508'] > ['2005/01/31', '22:48:00', '26.508'] > ['2005/01/31', '23:00:00', '26.508'] > ['2005/01/31', '23:12:00', '26.508'] > ['2005/01/31', '23:24:00', '26.508'] > ['2005/01/31', '23:36:00', '26.508'] > ['2005/01/31', '23:48:00', '26.508'] > >>>> > I would like to test the values in the second column to see if they're > in the list I named time_list and, if so, write the whole row to an > output file. > > The problem is that I don't know how to access the second column of > values. I tried the direct route: > >>>> for row in cr: >>>> > ... print cr[1] > ... > You need to print the 2nd item of row not of the entire file ie "print row[1]" not "print cr[1]". HTH. Adam. From venefyxatu+python at gmail.com Wed Nov 17 15:48:55 2010 From: venefyxatu+python at gmail.com (Erik H.) Date: Wed, 17 Nov 2010 15:48:55 +0100 Subject: [Tutor] Accessing columns of a CSV file In-Reply-To: References: Message-ID: Also notice that in time_list you use %H:%M format, while in your rows the format is %H:%M:%S. Simple string comparison won't work, unless you add those seconds to your time_list. Regards, Erik On Wed, Nov 17, 2010 at 2:59 PM, Hanlie Pretorius wrote: > Hi, > > I'm reading a CSV file and I want to test the contents of its second > column before I write it to an output file: > >>>> import csv >>>> time_list=['00:00', '03:00', '06:00','09:00','12:00','15:00','18:00','21:00'] >>>> readfile='C8R004_flow.csv' >>>> in_text=open(readfile,'rb') >>>> cr=csv.reader(in_text) >>>> cr > <_csv.reader object at 0x7f4dfc3b2360> >>>> for row in cr: > ... ? ? print row > ['2005/01/31', '21:00:00', '26.508'] > ['2005/01/31', '21:12:00', '26.508'] > ['2005/01/31', '21:24:00', '26.508'] > ['2005/01/31', '21:36:00', '26.508'] > ['2005/01/31', '21:48:00', '26.508'] > ['2005/01/31', '22:00:00', '26.508'] > ['2005/01/31', '22:12:00', '26.508'] > ['2005/01/31', '22:24:00', '26.508'] > ['2005/01/31', '22:36:00', '26.508'] > ['2005/01/31', '22:48:00', '26.508'] > ['2005/01/31', '23:00:00', '26.508'] > ['2005/01/31', '23:12:00', '26.508'] > ['2005/01/31', '23:24:00', '26.508'] > ['2005/01/31', '23:36:00', '26.508'] > ['2005/01/31', '23:48:00', '26.508'] >>>> > > I would like to test the values in the second column to see if they're > in the list I named time_list and, if so, write the whole row to an > output file. > > The problem is that I don't know how to access the second column of > values. I tried the direct route: >>>> for row in cr: > ... ? ? print cr[1] > ... >>>> > > and I've tried to convert the csv.reader object into a list: > > [code] >>>> file_rows=[] >>>> for row in cr: > ... ? ? file_rows.append(row) > ... >>>> file_rows > [] > [/code] > > which clearly doesn't work. > > Can someone perhaps suggest a method to access the value in the second > column of each row so that I can test it against the time_list? > > Thanks > Hanlie > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rdmoores at gmail.com Wed Nov 17 17:34:17 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 17 Nov 2010 08:34:17 -0800 Subject: [Tutor] Need help with script for finding pairs of amicable numbers In-Reply-To: References: Message-ID: I got no response to my post that began this thread 8 days ago. I followed that with a new thread, "List comprehension question" that continued for 60+ posts, and from which I learned a lot -- about optimizing a function (and the importance of timing the various candidates for improvement). The function has been radically changed and speeded up more than 10x. I didn't mention what it was for, but now here it is in my script to find Amicable Pairs (ta daa!). See . I've used it to find the first 195 pairs, or all pairs (n, m), n < m where 1 <= n <= 55,000,000. The list is at . Now, I have no reason at all to care about Amicable Pairs, but I'm interested in learning how to make the search for them more efficient. When I had found all pairs up through n = 34,000,000, I thought I'd found one way that would find APs faster (by one-third) by eliminating all odd n's that didn't end in '5' (40% of all n's). In fact, up to n = 34 million, there are no APs whose n is both odd and whose last digit is not '5'. So I asked on if it is true for all APs: . As you can see, I should have gone another million out, because that's where the counterexample (34765731, 36939357) appears. And it remains the only counterexample up through n = 55 million. So, Tutors, what can I do to make the search for APs more efficient? C Smith has pointed out that if I installed sympy, I could do >>> from sympy import divisors >>> list(divisors(256)) [1, 2, 4, 8, 16, 32, 64, 128, 256] and the sum of the proper divisors of 256 would be just sum(divisors(n)) - n. However, when I did install sympy, and tried Smith's idea, the result was a major slowdown on my system, for some unknown reason. But that's fine, because I wouldn't learn much from sympy anyway, other than that it performs magic. I think what I want are ways to eliminate (filter out?) some of the n's (as in my idea of the odd n's that don't end in '5'). Anyone? Dick Moores From ohmerj1 at mymail.nku.edu Thu Nov 18 00:44:51 2010 From: ohmerj1 at mymail.nku.edu (Joe Ohmer) Date: Wed, 17 Nov 2010 23:44:51 +0000 Subject: [Tutor] Assistance with Psuedocode Message-ID: <87D55F6DCE9F684B926527A3D2EF39A6161F894E@SN1PRD0202MB041.namprd02.prod.outlook.com> Hello, The following code works well but I don't understand why the mysteryEffect code block changes the picture. Doesn?t 64*(r/64) just equal r? (Same with g and b.) So this function should not change the picture at all. But it does! If anyone can explain how and why this actually changes the picture I would appreciate it greatly. #Creates, duplicates and shows the pic def main(): pic1= makePicture( pickAFile() ) pic2= duplicatePicture( pic1) fadeDownFromBlack( pic1 ) show( pic1 ) mysteryEffect( pic2 ) show( pic2 ) #Does a 50% fade of the upper half of the picture def fadeDownFromBlack( pic1 ): w=getWidth(pic1) h=getHeight(pic1) for y in range(0,h/2): for x in range(0,w): px= getPixel( pic1, x, y ) setRed(px,y*(2.0/h)*getRed(px)) setGreen(px,y*(2.0/h)*getGreen(px)) setBlue(px,y*(2.0/h)*getBlue(px)) repaint( pic1 ) #Adds a rainbow effect to the picture def mysteryEffect( pic2 ): for px in getPixels( pic2 ): r= getRed ( px ) g= getGreen( px ) b= getBlue( px ) setRed( px, 64*(r/64)) setGreen( px, 64*(g/64)) setBlue( px, 64*(b/64)) repaint( pic2 ) Thanks, Joe -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 18 01:49:36 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Nov 2010 00:49:36 -0000 Subject: [Tutor] Assistance with Psuedocode References: <87D55F6DCE9F684B926527A3D2EF39A6161F894E@SN1PRD0202MB041.namprd02.prod.outlook.com> Message-ID: "Joe Ohmer" wrote > The following code works well but I don't understand why > the mysteryEffect code block changes the picture. > Doesn?t 64*(r/64) just equal r? That dependfs on which version of Python you use. In earlier versions '/' meant integer division so (1/64) * 64 => 0 * 64 (120/64) * 64 => 1 * 64 (128/64) * 64 => 2 * 64 (130/64) * 64 => 2 * 64 So only in the case of exact multiples of 64 does it do what you expect. However, if you have a recent version of Python (2.6? onwards) '/' means floating point division so now you get the result you expect (subject to rounding error) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From adam.jtm30 at gmail.com Thu Nov 18 01:55:28 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 18 Nov 2010 00:55:28 +0000 Subject: [Tutor] Assistance with Psuedocode In-Reply-To: References: <87D55F6DCE9F684B926527A3D2EF39A6161F894E@SN1PRD0202MB041.namprd02.prod.outlook.com> Message-ID: <4CE47980.1080808@gmail.com> On 18/11/10 00:49, Alan Gauld wrote: > > "Joe Ohmer" wrote > >> The following code works well but I don't understand why >> the mysteryEffect code block changes the picture. >> Doesn?t 64*(r/64) just equal r? > > That dependfs on which version of Python you use. > In earlier versions '/' meant integer division so > > (1/64) * 64 => 0 * 64 > (120/64) * 64 => 1 * 64 > (128/64) * 64 => 2 * 64 > (130/64) * 64 => 2 * 64 > > So only in the case of exact multiples of 64 does it do > what you expect. However, if you have a recent version > of Python (2.6? onwards) '/' means floating point division > so now you get the result you expect (subject to rounding > error) > > HTH, > Roughly what I was about to say. 2.6 doesn't do floating point division as standard. I think you can import that behaviour. From davea at ieee.org Thu Nov 18 03:22:02 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 17 Nov 2010 21:22:02 -0500 Subject: [Tutor] Assistance with Psuedocode In-Reply-To: <87D55F6DCE9F684B926527A3D2EF39A6161F894E@SN1PRD0202MB041.namprd02.prod.outlook.com> References: <87D55F6DCE9F684B926527A3D2EF39A6161F894E@SN1PRD0202MB041.namprd02.prod.outlook.com> Message-ID: <4CE48DCA.5060809@ieee.org> On 2:59 PM, Joe Ohmer wrote: > Hello, > > The following code works well but I don't understand why the mysteryEffect code block changes the picture. > Doesn?t 64*(r/64) just equal r? (Same with g and b.) So this function should not change the picture at all. But it does! If anyone can explain how and why this actually changes the picture I would appreciate it greatly. > > > > #Adds a rainbow effect to the picture > def mysteryEffect( pic2 ): > for px in getPixels( pic2 ): > r= getRed ( px ) > g= getGreen( px ) > b= getBlue( px ) > setRed( px, 64*(r/64)) > setGreen( px, 64*(g/64)) > setBlue( px, 64*(b/64)) > repaint( pic2 ) > > Thanks, > Joe > You didn't specify the python version. But I'd guess you're using 2.x (as opposed to 3.x), where dividing integers gives an integer by default. To quickly check, try print 25/9 and if you get 2, you'll see what I mean. When you then multiply 2 by 9, you get 18. DaveA From srinidhi.rx at gmail.com Thu Nov 18 07:35:56 2010 From: srinidhi.rx at gmail.com (Srinidhi Rao) Date: Thu, 18 Nov 2010 12:05:56 +0530 Subject: [Tutor] Python Books...* Message-ID: Hello Pythoners', I am a beginner here want to explore python, thinking this is the best place to start with, I request you experts to help me become one... To Start with which is the best book to get a hang of what python is and also provide some distinction between the Python 2.6 and 3.x... If this question is relevant can any one suggest which book to refer for the DataStructures(preferably in C) to have some backdrop. Kindly help me find a kindle(literary) :) Thanks and Regards. || SRX || -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 18 10:09:01 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Nov 2010 09:09:01 -0000 Subject: [Tutor] Python Books...* References: Message-ID: "Srinidhi Rao" wrote > I am a beginner here want to explore python, Hi, are you a beginner to programming or just to Python? There are many good books for those converting from other languages, there are not so many for those starting from scratch. > To Start with which is the best book to get a hang of what python is > and > also provide some distinction between the Python 2.6 and 3.x... Most books deal with one otr the other, I don't know of any that compare the two. My online tutorlial is availavble for both and by comparing versions you would get some idea. But the best way is to read the Python v3 "Whats New" pages... > If this question is relevant can any one suggest which book to refer > for the > DataStructures(preferably in C) to have some backdrop. I'm not sure what you are looking for here. Python and C data structures are very different. Python works at a much higher level, abstract concept and C works at a low level, close to memory. Finally, do you explicitly want dead tree books or Kindle type e-books or are you OK with web based resources? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kaushalshriyan at gmail.com Thu Nov 18 10:34:43 2010 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 18 Nov 2010 15:04:43 +0530 Subject: [Tutor] Python Books...* In-Reply-To: References: Message-ID: On Thu, Nov 18, 2010 at 2:39 PM, Alan Gauld wrote: > > "Srinidhi Rao" wrote > >> I am a beginner here want to explore python, > > Hi, are you a beginner to programming or just to Python? > There are many good books for those converting from other languages, > there are not so many for those starting from scratch. > >> To Start with which is the best book to get a hang of what python is and >> also provide some distinction between the Python 2.6 and 3.x... > > Most books deal with one otr the other, I don't know of any that > compare the two. My online tutorlial is availavble for both and by > comparing versions you would get some idea. But the best way > is to read the Python v3 "Whats New" pages... > >> If this question is relevant can any one suggest which book to refer for >> the >> DataStructures(preferably in C) to have some backdrop. > > I'm not sure what you are looking for here. Python and C data > structures are very different. Python works at a much higher level, > abstract concept and C works at a low level, close to memory. > > Finally, do you explicitly want dead tree books or Kindle type e-books > or are you OK with web based resources? Hi Alan > Finally, do you explicitly want dead tree books or Kindle type e-books > or are you OK with web based resources? What exactly is dead tree book. sounds interesting Thanks Kaushal From alan.gauld at btinternet.com Thu Nov 18 10:46:42 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 18 Nov 2010 09:46:42 +0000 (GMT) Subject: [Tutor] Python Books...* In-Reply-To: References: Message-ID: <236914.24450.qm@web86707.mail.ird.yahoo.com> > > Finally, do you explicitly want dead tree books or Kindle type e-books > > or are you OK with web based resources? > > What exactly is dead tree book. sounds interesting Paper is made from dead trees... :-) Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From onyxtic at gmail.com Thu Nov 18 10:53:23 2010 From: onyxtic at gmail.com (Evans Anyokwu) Date: Thu, 18 Nov 2010 09:53:23 +0000 Subject: [Tutor] Python Books...* In-Reply-To: References: Message-ID: On Thu, Nov 18, 2010 at 9:34 AM, Kaushal Shriyan wrote: > On Thu, Nov 18, 2010 at 2:39 PM, Alan Gauld > wrote: > > > > "Srinidhi Rao" wrote > > > >> I am a beginner here want to explore python, > > > > Hi, are you a beginner to programming or just to Python? > > There are many good books for those converting from other languages, > > there are not so many for those starting from scratch. > > > >> To Start with which is the best book to get a hang of what python is and > >> also provide some distinction between the Python 2.6 and 3.x... > > > > Most books deal with one otr the other, I don't know of any that > > compare the two. My online tutorlial is availavble for both and by > > comparing versions you would get some idea. But the best way > > is to read the Python v3 "Whats New" pages... > > > >> If this question is relevant can any one suggest which book to refer for > >> the > >> DataStructures(preferably in C) to have some backdrop. > > > > I'm not sure what you are looking for here. Python and C data > > structures are very different. Python works at a much higher level, > > abstract concept and C works at a low level, close to memory. > > > > Finally, do you explicitly want dead tree books or Kindle type e-books > > or are you OK with web based resources? > > Hi Alan > > > Finally, do you explicitly want dead tree books or Kindle type e-books > > or are you OK with web based resources? > > What exactly is dead tree book. sounds interesting > > Thanks > > Kaushal Kaushal, dead tree book is the normal (printed) physical book you buy from a bookshop. -- Evans -------------- next part -------------- An HTML attachment was scrubbed... URL: From kaushalshriyan at gmail.com Thu Nov 18 11:00:03 2010 From: kaushalshriyan at gmail.com (Kaushal Shriyan) Date: Thu, 18 Nov 2010 15:30:03 +0530 Subject: [Tutor] Python Books...* In-Reply-To: References: Message-ID: On Thu, Nov 18, 2010 at 3:23 PM, Evans Anyokwu wrote: > > > On Thu, Nov 18, 2010 at 9:34 AM, Kaushal Shriyan > wrote: >> >> On Thu, Nov 18, 2010 at 2:39 PM, Alan Gauld >> wrote: >> > >> > "Srinidhi Rao" wrote >> > >> >> I am a beginner here want to explore python, >> > >> > Hi, are you a beginner to programming or just to Python? >> > There are many good books for those converting from other languages, >> > there are not so many for those starting from scratch. >> > >> >> To Start with which is the best book to get a hang of what python is >> >> and >> >> also provide some distinction between the Python 2.6 and 3.x... >> > >> > Most books deal with one otr the other, I don't know of any that >> > compare the two. My online tutorlial is availavble for both and by >> > comparing versions you would get some idea. But the best way >> > is to read the Python v3 "Whats New" pages... >> > >> >> If this question is relevant can any one suggest which book to refer >> >> for >> >> the >> >> DataStructures(preferably in C) to have some backdrop. >> > >> > I'm not sure what you are looking for here. Python and C data >> > structures are very different. Python works at a much higher level, >> > abstract concept and C works at a low level, close to memory. >> > >> > Finally, do you explicitly want dead tree books or Kindle type e-books >> > or are you OK with web based resources? >> >> Hi Alan >> >> > Finally, do you explicitly want dead tree books or Kindle type e-books >> > or are you OK with web based resources? >> >> What exactly is dead tree book. sounds interesting >> >> Thanks >> >> Kaushal > > > Kaushal, dead tree book is the normal (printed) physical book you buy from a > bookshop. > > -- > Evans > Thanks Evans,Alan, I learnt a new thing today :-) From srinidhi.rx at gmail.com Thu Nov 18 15:31:59 2010 From: srinidhi.rx at gmail.com (Srinidhi Rao) Date: Thu, 18 Nov 2010 20:01:59 +0530 Subject: [Tutor] Paper Book Message-ID: Hi, Thanks for the reply guys, I would prefer a Paper Book as I don't have a kindle(amazon) and also the PDF is not so suitable out here.. (the power cuts hamper continuity :( ) @Alan, Nice website for a beginner. I glanced through your webpage and thanks for the link. I too have an Electronics background, I am only new to Python and of course OOPs... can you suggest any good books(paper) on Python. Thanks and Regards, || SRX || -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Thu Nov 18 16:39:17 2010 From: knacktus at googlemail.com (Knacktus) Date: Thu, 18 Nov 2010 16:39:17 +0100 Subject: [Tutor] Paper Book In-Reply-To: References: Message-ID: <4CE548A5.9080309@googlemail.com> Am 18.11.2010 15:31, schrieb Srinidhi Rao: > Hi, > > Thanks for the reply guys, I would prefer a Paper Book as I don't have a > kindle(amazon) and also the PDF is not so suitable out here.. (the power > cuts hamper continuity :( ) > > @Alan, > Nice website for a beginner. I glanced through your webpage and thanks > for the link. > I too have an Electronics background, I am only new to Python and of > course OOPs... can you suggest any good books(paper) on Python. > > Thanks and Regards, > || SRX || > My first book was "Learning Python" from Mark Lutz. Today, I think it's a bit too long. (OK, now I have learned most of the stuff in the book). It's certainly not the wrong choice for a beginner book. And now I'm a convinced Python fan. So it must have somehow worked. "Programming in Python 3" from Mark Summerfield is also nice. I've bought it recently and like it. But can't comment on how it feels reading it as a complete novice. The best book in my opinion, however *not* a beginner book, is from David Beazley: Python Essential Reference. As the name tells it's a reference, but with a lot of good recommendations and right to the point. That might be a good choice as a second book. Or you could read it in parallel to your beginner book - look up the topics you covered in the reference book. There's another good one (also for beginners): Dive into Python. There's a free edition on the web: http://diveintopython.org/ If you like it you can also by a "dead tree" version. (I've learned a new expression today, too ;-)) HTH, Jan > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From engstrom.gary at gmail.com Thu Nov 18 22:13:50 2010 From: engstrom.gary at gmail.com (gary engstrom) Date: Thu, 18 Nov 2010 16:13:50 -0500 Subject: [Tutor] new to python Message-ID: Dear Python Tutor, Being new to python I was wondering if there is a way to import exel data into pyrhon matrix/arrays so that I have some data to work with. I know R uses Rcmdr as an easy interface for excel data, which helps keep the reader engaged while learning the language. Thanks G -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Nov 18 23:27:52 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 19 Nov 2010 09:27:52 +1100 Subject: [Tutor] new to python In-Reply-To: References: Message-ID: <4CE5A868.30308@pearwood.info> gary engstrom wrote: > Dear Python Tutor, > > Being new to python I was wondering if there is a way to import exel data > into pyrhon matrix/arrays so that I have some data to work with. I know R > uses Rcmdr as an easy interface > for excel data, which helps keep the reader engaged while learning the > language. Python doesn't directly support Excel binary formats such as xls, but it does support the interchange CSV format. See the csv module: http://docs.python.org/library/csv.html http://effbot.org/librarybook/csv.htm Also, if you write your data to a tab-delimited file, you can just read the file line by line, splitting on tabs. Finally, if you must deal with Excel binary formats, there is at least one third-party library that might help. Google for "python excel" for links. -- Steven From wprins at gmail.com Thu Nov 18 23:51:30 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 18 Nov 2010 22:51:30 +0000 Subject: [Tutor] new to python In-Reply-To: References: Message-ID: On 18 November 2010 21:13, gary engstrom wrote: > Being new to python I was wondering if there is a way to import exel data > into pyrhon matrix/arrays so that I have some data to work with. I know R > uses Rcmdr as an easy interface > for excel data, which helps keep the reader engaged while learning the > language. > > If you want to read/write an Excel format files, have a look at the "xlwt" and the "xlrt" Python modules (probably what Steven was aluding to). See http://www.python-excel.org/ These modules works quite well for reading/generating Excel files (with expectable limitations) from any platform that Python's available on (e.g. including non-Windows) and thus does not require Excel to be available on the machine you're producing the file on. If however you are running on Windows and have Excel installed, you could also consider driving the real Excel via COM automation, which will guarantee you get desired results including formatting, charts etc when generating sheets, and will ensure you have full access to all the functionality Excel exposes via its COM object model. If your requirements is simple enough though then Steven's suggestion to use CSV is probably preferable, e.g. export the data to CSV and then import with the "csv" module in Python. (The KISS principle applies here as elsewhere in programming: "Keep It Small & Simple") HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel at joelschwartz.com Fri Nov 19 01:20:44 2010 From: joel at joelschwartz.com (Joel Schwartz) Date: Thu, 18 Nov 2010 16:20:44 -0800 Subject: [Tutor] new to python In-Reply-To: References: Message-ID: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> Walter, For those of us who are new to writing code that makes various software packages interact with each other, can you say more about what "COM object model" means in this context and where one can learn how to use it to make Python interact with Excel and with Windows software in general. I've seen term "COM" before and I know it has something to do with how Windows programs interact with each other, but that's about it. Can you suggest some resources for learning more? Thanks, Joel _____ From: tutor-bounces+joel=joelschwartz.com at python.org [mailto:tutor-bounces+joel=joelschwartz.com at python.org] On Behalf Of Walter Prins Sent: Thursday, November 18, 2010 2:51 PM To: gary engstrom Cc: Tutor at python.org Subject: Re: [Tutor] new to python On 18 November 2010 21:13, gary engstrom wrote: Being new to python I was wondering if there is a way to import exel data into pyrhon matrix/arrays so that I have some data to work with. I know R uses Rcmdr as an easy interface for excel data, which helps keep the reader engaged while learning the language. If you want to read/write an Excel format files, have a look at the "xlwt" and the "xlrt" Python modules (probably what Steven was aluding to). See http://www.python-excel.org/ These modules works quite well for reading/generating Excel files (with expectable limitations) from any platform that Python's available on (e.g. including non-Windows) and thus does not require Excel to be available on the machine you're producing the file on. If however you are running on Windows and have Excel installed, you could also consider driving the real Excel via COM automation, which will guarantee you get desired results including formatting, charts etc when generating sheets, and will ensure you have full access to all the functionality Excel exposes via its COM object model. If your requirements is simple enough though then Steven's suggestion to use CSV is probably preferable, e.g. export the data to CSV and then import with the "csv" module in Python. (The KISS principle applies here as elsewhere in programming: "Keep It Small & Simple") HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 19 01:54:06 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Nov 2010 00:54:06 -0000 Subject: [Tutor] new to python References: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> Message-ID: "Joel Schwartz" wrote > packages interact with each other, can you say more about what "COM > object > model" means in this context and where one can learn how to use it > to make > Python interact with Excel and with Windows software in general. COM = Common Object Model It is a Microsoft standard to expose application Objects so that programs can interact with each other by calling those objects methods. Because it is a binary standard it will work with any programming language with a COM binding. Typically an office application will expose a Document object that you can open, read, close etc.Excel includes operations to select tabs, columns, rows, cells etc. There have been numerous incarnations of COM over the years, you may have also heard of OLE, ActiveX, DCOM, COM+ etc. There is a load of info on the Microsoft Developers web site. You can access COM via the Pythonwin library in the windows extensions package and Marrk Hammond's book Python Programming on Win32 provides extensive descriptions. Personally I prefer to interact with COM via VBScript as the Python route is (only slightly) more clunky. IMHO HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Fri Nov 19 01:57:19 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 18 Nov 2010 16:57:19 -0800 Subject: [Tutor] new to python In-Reply-To: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> References: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> Message-ID: On 11/18/2010 4:20 PM Joel Schwartz said... > Walter, > > For those of us who are new to writing code that makes various software > packages interact with each other, can you say more about what "COM object > model" means in this context and where one can learn how to use it to make > Python interact with Excel and with Windows software in general. I've seen > term "COM" before and I know it has something to do with how Windows > programs interact with each other, but that's about it. Can you suggest some > resources for learning more? This looks like one appropriate starting point... http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartServerCom.html Emile From alan.gauld at btinternet.com Fri Nov 19 09:10:28 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Nov 2010 08:10:28 -0000 Subject: [Tutor] new to python References: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> Message-ID: "Alan Gauld" wrote > COM = Common Object Model Oops, sorry. That should be COMPONENT Object Model... Alan G. From wprins at gmail.com Fri Nov 19 14:52:16 2010 From: wprins at gmail.com (Walter Prins) Date: Fri, 19 Nov 2010 13:52:16 +0000 Subject: [Tutor] new to python In-Reply-To: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> References: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> Message-ID: On 19 November 2010 00:20, Joel Schwartz wrote: > For those of us who are new to writing code that makes various software > packages interact with each other, can you say more about what "COM object > model" means in this context and where one can learn how to use it to make > Python interact with Excel and with Windows software in general. I've seen > term "COM" before and I know it has something to do with how Windows > programs interact with each other, but that's about it. Can you suggest some > resources for learning more? > Sure, I'll just add to what Alan and Emile's already said. The first thing (that's perhaps obvious but I'll just mention it explicitly) about COM is that it was one of the earlier attempts at solving the programming language and application interoperability problem. E.g, how do we write code so that other languages can easily consume our functionality, and vice versa? DDE was an early attempt by Microsoft at a solution, and COM was an attempt by Microsoft's at a more comprehensive and general answer to this. It basically defines a set of standards and API's that effectively can serve as a language-agnostic bridge between different programming languages, if those languages are "COM enabled" by their supporting and complying with COM's requirements. An important extension or evolution of COM to networks was called DCOM (or "Distributed Component Object Model".) As the name aludes, it extends COM so that it can operate accross a network. In other words, have a program on one computer instantiate a component or object (possibly implemented in another language) on another computer, and work with this object as if it's a local object part of the lcoal program. Depending on how well a language supports and is integrated with COM/DCOM this may and should for the most part even look like a local native object in the language being programmed in. DCOM eventually was further evolved into and eventually included under the moniker of COM itself, and a set of extensions to DCOM that solved/addressed a bunch of additional problems/concerns (like security and object pooling, that you would have to deal with yourself when using only COM/DCOM that typically occurs in the context of distributed applications) was then called COM+. (For more see http://ur.ly/v1Xy and http://ur.ly/v8Ii) Anyway, suffice it to say, COM and friends introduces its own set of downsides and issues (suffice it to say I've lost a not insignificant amount of blood fighting with obscure DCOM security issues in the past), which eventually was at least one of the reasons for Microsoft eventually coming up with the .Net framework. (.Net then, is at one level another attempt at solving the language interoperability problem in a more seamless and elegant way. WSDL and web services standards were another, targetting the program interoperability accross the web/internet at large, COM/DCOM originally targetted local area networks and doesn't work very well or easily accross the internet.) As for resources, there's a seemingly decent presentation on Python and COM and friends here: http://ur.ly/voQt Also there's Activestate's documentation that's appropriate: http://docs.activestate.com/activepython/2.5/pywin32/html/com/win32com/HTML/GeneratedSupport.html http://docs.activestate.com/activepython/2.5/pywin32/html/com/win32com/HTML/QuickStartClientCom.html The package that enables Python to interoperate with COM applications/languages (as well as making available much of the Windows Win32 API's as well as the "PythonWin" application) is called "pywin32" and is available here: http://sourceforge.net/projects/pywin32/ While the Python package "win32com" which is included in pywin32 (which enables Python to interoperate with COM applications/languages) provides a number of ways of querying and accessing COM interfaces with few obvious differences between them (provided you know the interface), it is usually more convenient when experimenting to know what methods and properties are really available for a given interface as well as being more efficient to use so called "early-binding" when accessing COM objects. This is where the "makepy" utility comes in. By selecting a particular type library and building the Python wrappers using this tool in advance, more information becomes available since you and Python can then refer to the generated Python wrappers for casual investigation of object interfaces. All of this is also covered above in the ActiveState documentation as well as here: http://oreilly.com/catalog/pythonwin32/chapter/ch12.html Hopefully that clarifies things a bit. I would suggest you try install the pywin32 package, then have a go at playing around with Excel perhaps interactively at first, and then with the tools and examples as outlined in some of the links I've posted. (As an aside, obviously I've commented mostly only on using Python as a COM client, it is also possible to write COM servers in Python, e.g. making your Python program available to other COM enabled programs and languages. Emile's post is relevant to this topic. ) HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wangoloj at yahoo.com Fri Nov 19 14:55:47 2010 From: wangoloj at yahoo.com (Wangolo Joel) Date: Fri, 19 Nov 2010 13:55:47 +0000 (GMT) Subject: [Tutor] Tutor Digest, Vol 81, Issue 73 In-Reply-To: Message-ID: <634147.43883.qm@web29713.mail.ird.yahoo.com> ?I NO LONGER WANT YOUR TUTORIALS; SORRY FOR THIS:: -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Nov 19 15:21:52 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Nov 2010 01:21:52 +1100 Subject: [Tutor] Tutor Digest, Vol 81, Issue 73 In-Reply-To: <634147.43883.qm@web29713.mail.ird.yahoo.com> References: <634147.43883.qm@web29713.mail.ird.yahoo.com> Message-ID: <4CE68800.8000705@pearwood.info> Wangolo Joel wrote: > I NO LONGER WANT YOUR TUTORIALS; > SORRY FOR THIS:: There's no need to SHOUT -- we're not deaf. You subscribed yourself to the mailing list, you can unsubscribe yourself too. Just follow the instructions shown in EVERY email: > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Steven From joel at joelschwartz.com Fri Nov 19 17:36:51 2010 From: joel at joelschwartz.com (Joel Schwartz) Date: Fri, 19 Nov 2010 08:36:51 -0800 Subject: [Tutor] new to python In-Reply-To: References: <3C0DF512EFA844F3A245EB8A34FA74E3@JoelDesktop> Message-ID: <9D773582EE824658BB0FCFD3641A1D9E@JoelDesktop> Great information. Thanks to everyone who replied. Joel _____ From: Walter Prins [mailto:wprins at gmail.com] Sent: Friday, November 19, 2010 5:52 AM To: Joel Schwartz Cc: Tutor at python.org Subject: Re: [Tutor] new to python On 19 November 2010 00:20, Joel Schwartz wrote: For those of us who are new to writing code that makes various software packages interact with each other, can you say more about what "COM object model" means in this context and where one can learn how to use it to make Python interact with Excel and with Windows software in general. I've seen term "COM" before and I know it has something to do with how Windows programs interact with each other, but that's about it. Can you suggest some resources for learning more? Sure, I'll just add to what Alan and Emile's already said. The first thing (that's perhaps obvious but I'll just mention it explicitly) about COM is that it was one of the earlier attempts at solving the programming language and application interoperability problem. E.g, how do we write code so that other languages can easily consume our functionality, and vice versa? DDE was an early attempt by Microsoft at a solution, and COM was an attempt by Microsoft's at a more comprehensive and general answer to this. It basically defines a set of standards and API's that effectively can serve as a language-agnostic bridge between different programming languages, if those languages are "COM enabled" by their supporting and complying with COM's requirements. An important extension or evolution of COM to networks was called DCOM (or "Distributed Component Object Model".) As the name aludes, it extends COM so that it can operate accross a network. In other words, have a program on one computer instantiate a component or object (possibly implemented in another language) on another computer, and work with this object as if it's a local object part of the lcoal program. Depending on how well a language supports and is integrated with COM/DCOM this may and should for the most part even look like a local native object in the language being programmed in. DCOM eventually was further evolved into and eventually included under the moniker of COM itself, and a set of extensions to DCOM that solved/addressed a bunch of additional problems/concerns (like security and object pooling, that you would have to deal with yourself when using only COM/DCOM that typically occurs in the context of distributed applications) was then called COM+. (For more see http://ur.ly/v1Xy and http://ur.ly/v8Ii) Anyway, suffice it to say, COM and friends introduces its own set of downsides and issues (suffice it to say I've lost a not insignificant amount of blood fighting with obscure DCOM security issues in the past), which eventually was at least one of the reasons for Microsoft eventually coming up with the .Net framework. (.Net then, is at one level another attempt at solving the language interoperability problem in a more seamless and elegant way. WSDL and web services standards were another, targetting the program interoperability accross the web/internet at large, COM/DCOM originally targetted local area networks and doesn't work very well or easily accross the internet.) As for resources, there's a seemingly decent presentation on Python and COM and friends here: http://ur.ly/voQt Also there's Activestate's documentation that's appropriate: http://docs.activestate.com/activepython/2.5/pywin32/html/com/win32com/HTML/ GeneratedSupport.html http://docs.activestate.com/activepython/2.5/pywin32/html/com/win32com/HTML/ QuickStartClientCom.html The package that enables Python to interoperate with COM applications/languages (as well as making available much of the Windows Win32 API's as well as the "PythonWin" application) is called "pywin32" and is available here: http://sourceforge.net/projects/pywin32/ While the Python package "win32com" which is included in pywin32 (which enables Python to interoperate with COM applications/languages) provides a number of ways of querying and accessing COM interfaces with few obvious differences between them (provided you know the interface), it is usually more convenient when experimenting to know what methods and properties are really available for a given interface as well as being more efficient to use so called "early-binding" when accessing COM objects. This is where the "makepy" utility comes in. By selecting a particular type library and building the Python wrappers using this tool in advance, more information becomes available since you and Python can then refer to the generated Python wrappers for casual investigation of object interfaces. All of this is also covered above in the ActiveState documentation as well as here: http://oreilly.com/catalog/pythonwin32/chapter/ch12.html Hopefully that clarifies things a bit. I would suggest you try install the pywin32 package, then have a go at playing around with Excel perhaps interactively at first, and then with the tools and examples as outlined in some of the links I've posted. (As an aside, obviously I've commented mostly only on using Python as a COM client, it is also possible to write COM servers in Python, e.g. making your Python program available to other COM enabled programs and languages. Emile's post is relevant to this topic. ) HTH, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Sat Nov 20 07:48:06 2010 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sat, 20 Nov 2010 06:48:06 +0000 Subject: [Tutor] JOB AD PROJECT Message-ID: <1779837667-1290235688-cardhu_decombobulator_blackberry.rim.net-452882653-@b3.c12.bise7.blackberry> Hi, I have done some extensive reading on python. i want to design a classifieds site for jobs. The service is meant to send people who register an sms with available jobs that fit their criteria/cv. But the main idea is that people come and register for quick jobs(like www.freelancer.com) and put up their criteria,age,location,qualifications....and when a company or employer posts a job,the people that fall into the category that was specified get sms and email alerts as to the availability of the job. I am taking this as my first project and would appreciate any help. I am looking in the direction of python, maybe django. Kindly help. Thanks. Sent from my BlackBerry wireless device from MTN From josep.m.fontana at gmail.com Sat Nov 20 09:28:28 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sat, 20 Nov 2010 09:28:28 +0100 Subject: [Tutor] Simple counter to determine frequencies of words in a document Message-ID: Hi, I'm trying to do something that should be very simple. I want to generate a list of the words that appear in a document according to their frequencies. So, the list generated by the script should be something like this: the : 3 book: 2 was : 2 read: 1 by: 1 [...] This would be obtained from a document that contained, for example, the following text: "The book was read by an unknown person before the librarian found that the book was missing." The code I started writing to achieve this result can be seen below. You will see that first I'm trying to create a dictionary that contains the word as the key with the frequency as its value. Later on I will transform the dictionary into a text file with the desired formatting. The problem is that, in the first test I ran, the output file that should contain the dictionary is empty. I'm afraid that this is the consequence of a very basic misunderstanding of how Python works. I've tried to piece this together from other scripts but obviously the program is not doing what it is supposed to do. I know the function should work so the problem is obviously in how I call the function. That is, how I'm trying to write the stuff (a dictionary) that the function returns into the output file. The relevant part of the code is so short that I'm sure it will take seconds for most people in the list to spot the problem but I've spent quite a lot of time changing things around and I cannot get it to work as desired. Can anybody tell me what's wrong so that I can say "duh" to myself once again? --------------------------- def countWords(a_list): words = {} for i in range(len(a_list)): item = a_list[i] count = a_list.count(item) words[item] = count return sorted(words.items(), key=lambda item: item[1], reverse=True) with open('output.txt', 'a') as token_freqs: with open('input.txt', 'r') as out_tokens: token_list = countWords(out_tokens.read()) token_freqs.write(token_list) ---------------------- Thanks in advance. Josep M. From alan.gauld at btinternet.com Sat Nov 20 09:57:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Nov 2010 08:57:19 -0000 Subject: [Tutor] Simple counter to determine frequencies of words in adocument References: Message-ID: "Josep M. Fontana" wrote > The code I started writing to achieve this result can be seen below. > You will see that first I'm trying to create a dictionary that > contains the word as the key with the frequency as its value. Later > on > I will transform the dictionary into a text file with the desired > formatting. Thats the right approach... > things around and I cannot get it to work as desired. Can anybody > tell > me what's wrong so that I can say "duh" to myself once again? I'll give some comments > --------------------------- > def countWords(a_list): > words = {} > for i in range(len(a_list)): > item = a_list[i] > count = a_list.count(item) > words[item] = count > return sorted(words.items(), key=lambda item: item[1], > reverse=True) The loop is a bit clunky. it would be clearer just to iterate over a_list: for item in a_list: words[item] = a_list.count(item) And the return value is a list of tuples, which when you write it will be a single long line containing the string representation. Is tat what you want? > with open('output.txt', 'a') as token_freqs: > with open('input.txt', 'r') as out_tokens: > token_list = countWords(out_tokens.read()) > token_freqs.write(token_list) read returns a single string. Using a for loop on a string will get you the characters in the string not the words. Also you probably want to use 'w' mode for your output file to create a new one each time, otherwise the file will keep getting bigger everytime you run the code. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Nov 20 10:00:52 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Nov 2010 09:00:52 -0000 Subject: [Tutor] JOB AD PROJECT References: <1779837667-1290235688-cardhu_decombobulator_blackberry.rim.net-452882653-@b3.c12.bise7.blackberry> Message-ID: wrote > I have done some extensive reading on python. > i want to design a classifieds site for jobs. Have you done any extensive programming yet? Reading alone will be of limited benefit and jumping into a faurly complex web project before you have the basics mastered will be a painful experience. I'm assuming you have at least some experience of web programming in other languages for you to take such a bold step? > I am taking this as my first project and would appreciate any help. > I am looking in the direction of python, maybe django. The choice of tools is fine, but its a big task for a first ever Python project! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Sat Nov 20 10:49:58 2010 From: __peter__ at web.de (Peter Otten) Date: Sat, 20 Nov 2010 10:49:58 +0100 Subject: [Tutor] Simple counter to determine frequencies of words in adocument References: Message-ID: Alan Gauld wrote: > The loop is a bit clunky. it would be clearer just to iterate over > a_list: > > for item in a_list: > words[item] = a_list.count(item) This is a very inefficient approach because you repeat counting the number of occurrences of a word that appears N times N times: >>> words = {} >>> a_list = "in the garden on the bank behind the tree".split() >>> for word in a_list: ... print "counting", word ... words[word] = a_list.count(word) ... counting in counting the # <-- 1 counting garden counting on counting the # <-- 2 counting bank counting behind counting the # <-- 3 counting tree >>> words {'on': 1, 'garden': 1, 'tree': 1, 'behind': 1, 'in': 1, 'the': 3, 'bank': 1} To avoid the duplicate effort you can check if the word was already counted: >>> words2 = {} >>> for word in a_list: ... if word not in words2: ... print "counting", word ... words2[word] = a_list.count(word) ... counting in counting the counting garden counting on counting bank counting behind counting tree >>> words == words2 True Inside the count() method you are still implicitly iterating over the entire list once for every distinct word. I would instead prefer counting manually while iterating over the list once. This has the advantage that it will even work if you don't keep the whole sequence of words in a list in memory (e. g. if you read them from a file one line at a time): >>> words3 = {} >>> for word in a_list: ... if word in words3: ... words3[word] += 1 ... else: ... words3[word] = 1 ... >>> words3 == words True Finally there's collections.defaultdict or, in Python 2.7, collections.Counter when you are more interested in the result than the way to achieve it. Peter From steve at pearwood.info Sat Nov 20 12:10:58 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Nov 2010 22:10:58 +1100 Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: References: Message-ID: <4CE7ACC2.60909@pearwood.info> Josep M. Fontana wrote: > def countWords(a_list): > words = {} > for i in range(len(a_list)): > item = a_list[i] > count = a_list.count(item) > words[item] = count > return sorted(words.items(), key=lambda item: item[1], reverse=True) > with open('output.txt', 'a') as token_freqs: > with open('input.txt', 'r') as out_tokens: > token_list = countWords(out_tokens.read()) > token_freqs.write(token_list) When you run that code, are you SURE that it merely results in the output file being blank? When I run it, I get an obvious error: Traceback (most recent call last): File "", line 4, in TypeError: argument 1 must be string or read-only character buffer, not list Don't you get this error too? The first problem is that file.write() doesn't take a list as argument, it requires a string. You feed is a list of (word, frequency) pairs. You need to decide how you want to format the output. The second problem is that you don't actually generate word frequencies, you generate letter frequencies. When you read a file, you get a string, not a list of words. A string is equivalent to a list of letters: >>> for item in "hello": ... print(item) ... h e l l o Your countWords function itself is reasonable, apart from some stylistic issues, and some inefficiencies which are unnoticeable for small numbers of words, but will become extremely costly for large lists of words. Ignoring that, here's my suggested code: you might like to look at the difference between what I have written, and what you have, and see if you can tell why I've written what I have. def countWords(wordlist): word_table = {} for word in wordlist: count = wordlist.count(word) word_table[word] = count return sorted( word_table.items(), key=lambda item: item[1], reverse=True ) def getWords(filename): with open(filename, 'r') as f: words = f.read().split() return words def writeTable(filename, table): with open(filename, 'w') as f: for word, count in table: f.write("%s %s\n" % (word, count)) words = getWords('input.txt') table = countWords(words) writeTable('output.txt', table) For bonus points, you might want to think about why countWords will be so inefficient for large word lists, although you probably won't see any problems until you're dealing with thousands or tens of thousands of words. -- Steven From kbailey at howlermonkey.net Sat Nov 20 20:03:11 2010 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Sat, 20 Nov 2010 14:03:11 -0500 Subject: [Tutor] code quest Message-ID: <4CE81B6F.3080400@howlermonkey.net> OK, I need to create or find a function that will return a list of DIRECTORIES (only) which are under 'the current directory'. Anyone got some clue on this? Please advise. -- end Very Truly yours, - Kirk Bailey, Largo Florida kniht +-----+ | BOX | +-----+ think From emile at fenx.com Sat Nov 20 20:11:12 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 20 Nov 2010 11:11:12 -0800 Subject: [Tutor] code quest In-Reply-To: <4CE81B6F.3080400@howlermonkey.net> References: <4CE81B6F.3080400@howlermonkey.net> Message-ID: On 11/20/2010 11:03 AM Kirk Bailey said... > OK, I need to create or find a function that will return a list of > DIRECTORIES (only) which are under 'the current directory'. Anyone got > some clue on this? Please advise. > Use os.walk Emile Help on function walk in module os: walk(top, topdown=True, onerror=None, followlinks=False) Directory tree generator. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), yields a 3-tuple dirpath, dirnames, filenames dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists are just names, with no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). From josep.m.fontana at gmail.com Sat Nov 20 20:48:44 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sat, 20 Nov 2010 20:48:44 +0100 Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: <4CE7ACC2.60909@pearwood.info> References: <4CE7ACC2.60909@pearwood.info> Message-ID: Thanks Alan, Peter and Steve, Instead of answering each one of you independently let me try to use my response to Steve's message as the basis for an answer to all of you. It turns out that matters of efficiency appear to be VERY important in this case. The example in my message was a very short string but the file that I'm trying to process is pretty big (20MB of text). I'm writing to you as my computer is about to burst in flames. I'm exaggerating a little bit because I'm checking the temperature and things so far seem to be under control but I ran the script that I made up following your recommendations (see below) on the real file for which I wanted to get word frequencies and it has been running for over half an hour without having generated the output file yet. I'm using a pretty powerful computer (core i7 with 8GB of RAM) so I'm a little surprised (and a bit worried as well) that the process hasn't finished yet. I tested the script before with a much smaller file and the output was as desired. When I look at the current processes running on my computer, I see the Python process taking 100% of the CPU. Since my computer has a multi-core processor, I'm assuming this process is using only one of the cores because another monitor tells me that the CPU usage is under 20%. This doesn't make much sense to me. I bought a computer with a powerful CPU precisely to do these kinds of things as fast as possible. How can it be that Python is only using such a small amount of processing power? But I digress, I will start another thread to ask about this because I'm curious to know whether this can be changed in any way. Now, however, I'm more interested in getting the right answer to my original question. OK, I'll start with Steve's answer first. > When you run that code, are you SURE that it merely results in the output > file being blank? When I run it, I get an obvious error: > > Traceback (most recent call last): > ?File "", line 4, in > TypeError: argument 1 must be string or read-only character buffer, not list > > Don't you get this error too? Nope. I was surprised myself, but I did not get any errors. But I suspect that this is because I don't have my IDE well configured. Although (see below) I do get many other error messages, I didn't get any in this case. See, I'm not only a newbie in Python but a newbie with IDEs as well. I'm using Eclipse (probably I should have started with something smaller and simpler) and I see the following error message: -------------------- Pylint: Executing command line:' /Applications/eclipse/Eclipse.app/Contents/MacOS --include-ids=y /Volumes/DATA/Documents/workspace/GCA/src/prova.py 'Pylint: The stdout of the command line is: Pylint: The stderr of the command line is: /usr/bin/python: can't find '__main__.py' in '/Applications/eclipse/Eclipse.app/Contents/MacOS' ----------------- Anyway, I tried the different alternatives all of you suggested with a small test file and everything worked perfectly. With the big file, however, none of the alternatives seems to work. Well, I don't know whether they work or not because the process takes so long that I have had to kill it out of desperation. The process I talk about at the beginning of this message is the one involving Peter's alternative. I think I'm going to kill it as well because now it has been running for 45 minutes and this seems way too long. So, here is how I wrote the code. You'll see that there are two different functions that do the same thing: countWords(wordlist) and countWords2(wordlist). countWords2 is adapted from Peter Otten's suggestion. This was the one that according to him would be more efficient. However, none of the versions (including Alan's as well) work when the file being processed is a large file. def countWords(wordlist): word_table = {} for word in wordlist: count = wordlist.count(word) word_table[word] = count def countWords2(wordlist): #as proposed by Peter Otten word_table = {} for word in wordlist: if word in word_table: word_table[word] += 1 else: word_table[word] = 1 count = wordlist.count(word) word_table[word] = count return sorted( word_table.items(), key=lambda item: item[1], reverse=True ) def getWords(filename): with open(filename, 'r') as f: words = f.read().split() return words def writeTable(filename, table): with open(filename, 'w') as f: for word, count in table: f.write("%s\t%s\n" % (word, count)) words = getWords('tokens_short.txt') table = countWords(words) # or table = countWords2(words) writeTable('output.txt', table) > For bonus points, you might want to think about why countWords will be so > inefficient for large word lists, although you probably won't see any > problems until you're dealing with thousands or tens of thousands of words. Well, now it will be clear to you that I AM seeing big problems because the files I need to process contain tens of thousands of words. The reason it is inefficient, I'm guessing, is because you have to repeat the counting of how many times a word appears in the list every time you encounter the same word in the loop. This is more or less what Peter said of the solution proposed by Alan, right? However, even with countWords2, which is supposed to overcome this problem, it feels as if I've entered an infinite loop. Josep M. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From georgextwu at yahoo.com Sat Nov 20 20:06:38 2010 From: georgextwu at yahoo.com (george wu) Date: Sat, 20 Nov 2010 11:06:38 -0800 (PST) Subject: [Tutor] List help Message-ID: <442464.76353.qm@web33808.mail.mud.yahoo.com> x=0 y=0 w=raw_input("Input: ") w=list(w) for x in range(len(w)): a=w[x] t=0 print a if a==2 or a==4 or a==6 or a==8 or a==10: t=a/2 print "hi" When I run this program, it doesn't print "hi". Can you please tell me why? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 20 23:41:38 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Nov 2010 22:41:38 -0000 Subject: [Tutor] code quest References: <4CE81B6F.3080400@howlermonkey.net> Message-ID: "Kirk Bailey" wrote > OK, I need to create or find a function that will return a list of > DIRECTORIES (only) which are under 'the current directory'. Anyone > got some clue on this? Please advise. You can use os.walk() to get a list of directories and files and then just throw away the files... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Nov 20 23:37:24 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 20 Nov 2010 22:37:24 +0000 (GMT) Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: References: <4CE7ACC2.60909@pearwood.info> Message-ID: <562869.51569.qm@web86705.mail.ird.yahoo.com> If the file is big use Peter's method, but 45 minutes still seems very long so it may be theres a hidden bug in there somehwew. However... > When I look at the current processes running on my computer, I see the > Python process taking 100% of the CPU. Since my computer has a > multi-core processor, I'm assuming this process is using only one of > the cores because another monitor tells me that the CPU usage is under > 20%. This doesn't make much sense to me. Its perfectly normal. The computer asssigns Python to one core and uses the other cores to run other tasks. Thats why its called muylti-tasking. There are tricks to spread the Python load over multiple cores but that is rarely necessaryy, and I don't think we need it here. > any in this case. See, I'm not only a newbie in Python but a newbie > with IDEs as well. I'm using Eclipse (probably I should have started > with something smaller and simpler) and I see the following error > message: Don;t run your code inside the IDE except for testing. IDEs are Development Environments, they are not ideal for executing production code. Run your file from the Terminal command prompt directly. > def countWords2(wordlist): #as proposed by Peter Otten > word_table = {} > for word in wordlist: > if word in word_table: > word_table[word] += 1 > else: > word_table[word] = 1 OK to here... > count = wordlist.count(word) > word_table[word] = count But you don;t need these lines, they are calling count for every word which causes Python to reread the string for every word. You are counting the occurences as you go in this approach with the += 1 line And in fact the assignment to word_table here is overwriting the incremental counter and negating the value of the optimisation! > return sorted( > word_table.items(), key=lambda item: item[1], reverse=True > ) > words = getWords('tokens_short.txt') > table = countWords(words) # or table = countWords2(words) > writeTable('output.txt', table) It would be worth utting some print statements between these functions just to monitor progress. Something like print " reading file..." print " counting words..." print "writing file..." That way you can see which function is running slowly, although it is almost certainly the counting. But as a general debugging tip its worth remembering. A few (and I mean a few, dont go mad!) print statements can narrow things down very quickly. > every time you encounter the same word in the loop. This is more or > less what Peter said of the solution proposed by Alan, right? Correct, but you have replicated that i Peters optimised version. HTH, Alan G. From martin at linux-ip.net Sun Nov 21 00:01:04 2010 From: martin at linux-ip.net (Martin A. Brown) Date: Sun, 21 Nov 2010 00:01:04 +0100 Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: References: <4CE7ACC2.60909@pearwood.info> Message-ID: Good evening, : It turns out that matters of efficiency appear to be VERY : important in this case. The example in my message was a very : short string but the file that I'm trying to process is pretty : big (20MB of text). Efficiency is best addressed first and foremost, not by hardware, but by choosing the correct data structure and algorithm for processing the data. You have more than enough hardware to deal with this problem, and appear to be wrestling still with why this apparently simple problem is An earlier responder (Peter Otten) pointed out to you that efficiency was one issue: you repeat counting the number of occurrences of a word that appears N times N times And another (Steven D'Aprano) pointed out that your countWords will be inefficient, but probably tolerable for data sets under about 10000 words. : frequencies and it has been running for over half an hour without : having generated the output file yet. I'm using a pretty powerful : computer (core i7 with 8GB of RAM) so I'm a little surprised (and : a bit worried as well) that the process hasn't finished yet. I : tested the script before with a much smaller file and the output : was as desired. [your comment, snipped in here, out of order] : However, even with countWords2, which is supposed to overcome this : problem, it feels as if I've entered an infinite loop. You have a 20MB file and 8GB of RAM, and it has taken half an hour? You have entered an infinite loop (or some other horrible thing). First, I would say that you don't have to worry too much about efficiency, for your first draft, just work on correctness of result. My machine is not as snappy as yours and finishes the job in the sloppiest way in well under 1 second. However, once you have solved the problem and feel good about the correctness, then learning how to process files/data efficiently would be a step in the direction of processing the same problem on a 20GB or 20TB file. : When I look at the current processes running on my computer, I : see the Python process taking 100% of the CPU. Since my computer : has a multi-core processor, I'm assuming this process is using : only one of the cores because another monitor tells me that the : CPU usage is under 20%. Correct. : This doesn't make much sense to me. I bought a computer with a : powerful CPU precisely to do these kinds of things as fast as : possible. How can it be that Python is only using such a small : amount of processing power? This is far afield from the question of word count, but may be useful someday. The beauty of a multiple processors is that you can run independent processes simultaneously (I'm not talking about multitasking). Using most languages(*), a single process will only use one of your available processors. Obviously, this was once a significant limitation, and so we came up with the idea of threads as a way to take advantage of multiple processors inside a single process. Python supports threads. An application must be written to take advantage of threading. I do not think I would recommend that for you until you have eked out as much performance as you can using a process based model. Here are the very first links I can find which delve into the topic, though there's much more there: http://docs.python.org/library/threading.html http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/ http://www.dabeaz.com/python/GIL.pdf OK, on to your code. : def countWords(wordlist): : word_table = {} : for word in wordlist: : count = wordlist.count(word) : print "word_table[%s] = %s" % (word,word_table.get(word,'')) : word_table[word] = count Problem 1: You aren't returning anything from this function. Add: return word_table Problem 2: You are doing more work than you need. Peter Otten pointed out how. To see what he was observing, try this riff on your function: def countWords(wordlist): word_table = dict() for word in wordlist: count = wordlist.count(word) print "word_table[%s] = %s\n" % (word,word_table.get(word,'')) word_table[word] = count return word_table What you should see is evidence that the second and third times that you iterate over the word 'the', you are updating an entry in the 'word_table' dictionary that already exists with the correct value. : def countWords2(wordlist): #as proposed by Peter Otten : word_table = {} : for word in wordlist: : if word in word_table: : word_table[word] += 1 : else: : word_table[word] = 1 : count = wordlist.count(word) : word_table[word] = count : return sorted( : word_table.items(), key=lambda item: item[1], reverse=True : ) In the above, countWords2, why not omit these lines: : count = wordlist.count(word) : word_table[word] = count And, try the function again. Let try a (bit of a labored) analogy of your problem. To approximate your algorithm. I have a clear tube with gumballs of a variety of colors. I open up one end of the tube, and mark where I'm starting. I pull out a gumball, and discover it's red. I mark down on my chalkboard that I have 1 red gumball. I count all of the red gumballs I can see in the clear tube. I mark down that I have 5 red gumballs. I put that gumball back in the other end of the tube. I take the second gumball from the tube and discover it's green. I mark down that I have 1 green gumball. I count all of the green gumballs I can see in the clear tube. I mark down that I have 1 green gumball. I put that gumball back in the other end of the tube. I pull out a gumball, and discover it's red. I mark down on my chalkboard that I have 1 red gumball. I count all of the red gumballs I can see in the clear tube. I mark down that I have 5 red gumballs. I put that gumball back in the other end of the tube. ... Do you see the duplicated effort? I would also suggest re-reading both the mail from Peter Otten and Steven D'Aprano. You appear to be much closer than earlier, but both of them are pointing out something that you don't appear to quite have grasped yet. As a side note, you may find it useful to simply play with some lists and dictionaries in the python interpreter: >>> words = 'in the garden on the bank behind the tree'.split() >>> words ['in', 'the', 'garden', 'on', 'the', 'bank', 'behind', 'the', 'tree'] >>> word_table = dict() >>> w = words[0] >>> word_table[w] = words.count(w) >>> word_table {'in': 1} >>> w = words[1] >>> word_table[w] = words.count(w) >>> word_table {'the': 3, 'in': 1} Once you gain familiarity with the lists and dicts, you can try out collections, as suggested by Peter Otten. Enjoy and good luck! -Martin * Somebody will be certain to point out a language or languages that provide some sort of facility to abstract the use of multiple processors without the explicit use of threads. -- Martin A. Brown http://linux-ip.net/ From emile at fenx.com Sun Nov 21 00:37:35 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 20 Nov 2010 15:37:35 -0800 Subject: [Tutor] List help In-Reply-To: <442464.76353.qm@web33808.mail.mud.yahoo.com> References: <442464.76353.qm@web33808.mail.mud.yahoo.com> Message-ID: On 11/20/2010 11:06 AM george wu said... > x=0 > y=0 > w=raw_input("Input: ") > w=list(w) > for x in range(len(w)): > a=w[x] > t=0 > print a > if a==2 or a==4 or a==6 or a==8 or a==10: > t=a/2 > print "hi" > > When I run this program, it doesn't print "hi". Can you please tell me why? > When you're comparing a to 2,4,6,8,10 a is a string representing the nth position of the input value w as iterated over with x. Specifically, a=w[x] which is the list of the input value. >>> list("hello") ['h', 'e', 'l', 'l', 'o'] >>> list("1234") ['1', '2', '3', '4'] You then compare a string to the numbers 2,4,6,8,10 making the test line: if a=="2" or a=="4 or a=="6" or a=="8": should make it print hi. Note I dropped the 10 as a single charter string would never match. All this is likely beside the point -- what were you trying to have happen? Emile From alan.gauld at btinternet.com Sun Nov 21 00:46:39 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Nov 2010 23:46:39 -0000 Subject: [Tutor] Simple counter to determine frequencies of words in a document References: <4CE7ACC2.60909@pearwood.info> Message-ID: "Martin A. Brown" wrote > * Somebody will be certain to point out a language or languages > that provide some sort of facility to abstract the use of > multiple processors without the explicit use of threads. ISTR Occam did that? Occam being the purpose designed language for the transputer, one of the first multiprocessor hardware architectures :-) Alan G. From ajarncolin at gmail.com Sun Nov 21 00:50:19 2010 From: ajarncolin at gmail.com (col speed) Date: Sun, 21 Nov 2010 06:50:19 +0700 Subject: [Tutor] Simple counter to determine frequencies of words in a document Message-ID: --> snip >However, even with countWords2, which is supposed to overcome this >problem, it feels as if I've entered an infinite loop. >Josep M. Just my twopenneth, I'm a noob and I'm not going to try such a big file on my old machine, but: 1. Maybe create a *set* from the wordlist, loop through that, so you call "count" on wordlist only once. OR 2. Use collections.defaultdict(int) and loop through wordlist and do dic[word] += 1 Maybe, possibly. Regards Colin -- if not ErrorMessage: check_all() >>>check_all.__doc__ " noErrorMessage != correctAnswer" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 21 01:49:36 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Nov 2010 00:49:36 -0000 Subject: [Tutor] Simple counter to determine frequencies of words in adocument References: Message-ID: "col speed" wrote > Just my twopenneth, I'm a noob and I'm not going to try such a big > file on > my old machine, but: > > 1. Maybe create a *set* from the wordlist, loop through that, so you > call > "count" on wordlist only once. OR This would be an improvement but still involves traversing the entire list N times where N is the number of unique words. > 2. Use collections.defaultdict(int) and loop through wordlist and do > dic[word] += 1 This is what his second version is supposed to do and is the best solution since it only involves a single trasverse of the file. Alan G. From delegbede at dudupay.com Sun Nov 21 04:34:29 2010 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sun, 21 Nov 2010 03:34:29 +0000 Subject: [Tutor] JOB AD PROJECT In-Reply-To: References: <1779837667-1290235688-cardhu_decombobulator_blackberry.rim.net-452882653-@b3.c12.bise7.blackberry> Message-ID: <1990780381-1290310472-cardhu_decombobulator_blackberry.rim.net-1588452058-@b3.c12.bise7.blackberry> Hi People, I am afraid only Alan has said something to me. Is it that solution would never come or u guys are waiting to gimme the best? Please help. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: "Alan Gauld" Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sat, 20 Nov 2010 09:00:52 To: Subject: Re: [Tutor] JOB AD PROJECT wrote > I have done some extensive reading on python. > i want to design a classifieds site for jobs. Have you done any extensive programming yet? Reading alone will be of limited benefit and jumping into a faurly complex web project before you have the basics mastered will be a painful experience. I'm assuming you have at least some experience of web programming in other languages for you to take such a bold step? > I am taking this as my first project and would appreciate any help. > I am looking in the direction of python, maybe django. The choice of tools is fine, but its a big task for a first ever Python project! HTH, -- Alan Gauld 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 mhw at doctors.net.uk Sun Nov 21 10:03:25 2010 From: mhw at doctors.net.uk (mhw at doctors.net.uk) Date: Sun, 21 Nov 2010 09:03:25 +0000 Subject: [Tutor] JOB AD PROJECT In-Reply-To: <1990780381-1290310472-cardhu_decombobulator_blackberry.rim.net-1588452058-@b3.c12.bise7.blackberry> References: <1779837667-1290235688-cardhu_decombobulator_blackberry.rim.net-452882653-@b3.c12.bise7.blackberry><1990780381-1290310472-cardhu_decombobulator_blackberry.rim.net-1588452058-@b3.c12.bise7.blackberry> Message-ID: <209592742-1290330336-cardhu_decombobulator_blackberry.rim.net-230455004-@b26.c3.bise7.blackberry> (Apologies for TP-ing) I'd second Alan's comments about not taking this as a first piece of work. Otherwise, Django seems a good choice - reasonably simple to get started, and well documented. This is the Python tutor list, so sort of assumes you are doing it in Python. This list tends to work best with "how do I do X?", or even better "I've written X, but it doesn't work/ doesn't work well enough" If you are going to use Django, then you should join their mailing list. HTH, Matt Sent from my BlackBerry? wireless device -----Original Message----- From: delegbede at dudupay.com Sender: tutor-bounces+mhw=doctors.net.uk at python.org Date: Sun, 21 Nov 2010 03:34:29 To: Reply-To: delegbede at dudupay.com Subject: Re: [Tutor] JOB AD PROJECT Hi People, I am afraid only Alan has said something to me. Is it that solution would never come or u guys are waiting to gimme the best? Please help. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: "Alan Gauld" Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sat, 20 Nov 2010 09:00:52 To: Subject: Re: [Tutor] JOB AD PROJECT wrote > I have done some extensive reading on python. > i want to design a classifieds site for jobs. Have you done any extensive programming yet? Reading alone will be of limited benefit and jumping into a faurly complex web project before you have the basics mastered will be a painful experience. I'm assuming you have at least some experience of web programming in other languages for you to take such a bold step? > I am taking this as my first project and would appreciate any help. > I am looking in the direction of python, maybe django. The choice of tools is fine, but its a big task for a first ever Python project! HTH, -- Alan Gauld 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 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Nov 21 10:10:12 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Nov 2010 09:10:12 -0000 Subject: [Tutor] JOB AD PROJECT References: <1779837667-1290235688-cardhu_decombobulator_blackberry.rim.net-452882653-@b3.c12.bise7.blackberry> <1990780381-1290310472-cardhu_decombobulator_blackberry.rim.net-1588452058-@b3.c12.bise7.blackberry> Message-ID: wrote > I am afraid only Alan has said something to me. > Is it that solution would never come or u guys > are waiting to gimme the best? I think we are waiting for a specific question. I said that your technology choice was OK for the project. What else do you want to know. You say you've done a lot of reading - but you don't say what? The python tutorial? Any other tutorials? The Python cookbook? You mention Django - have you read the introductory tutorial material there? You haven't really asked us anything much yet. Alan G. From knacktus at googlemail.com Sun Nov 21 10:10:52 2010 From: knacktus at googlemail.com (Knacktus) Date: Sun, 21 Nov 2010 10:10:52 +0100 Subject: [Tutor] JOB AD PROJECT In-Reply-To: <1990780381-1290310472-cardhu_decombobulator_blackberry.rim.net-1588452058-@b3.c12.bise7.blackberry> References: <1779837667-1290235688-cardhu_decombobulator_blackberry.rim.net-452882653-@b3.c12.bise7.blackberry> <1990780381-1290310472-cardhu_decombobulator_blackberry.rim.net-1588452058-@b3.c12.bise7.blackberry> Message-ID: <4CE8E21C.4000307@googlemail.com> Am 21.11.2010 04:34, schrieb delegbede at dudupay.com: > Hi People, > I am afraid only Alan has said something to me. Is it that solution would never come or u guys are waiting to gimme the best? > I agree with what Alan wrote. Your project sounds like real challenge even for experienced developers. Even for a team of experienced developers. You need both deep knowlegde of certain areas and broad knowledge of programming, databases and networking/communication. Of course you don't get the knowlegde if you don't start to develope a system. But if you start with too much and too complex things the risk is that you get stuck. There's a saying: "You've got so much in your mouth that you can't chew anymore." (And you realise it only when it has happened ;-)) To avoid that risk of suddenly being buried in complexitiy and not knowing what to do and where to move next, I'd recommend to follow a step by step learning path: With your project in mind, plan 3-5 smaller projects. Each project has one of the key technologies for your final project as focus. For example: 1) Create a Django site where users can register and unregister. 2 or 3 simple web forms. Nothing more. You'll learn all the database stuff and Django basics. 2) Build a system that handles SMS communication. 3) Build some a nice html+JS websites. ... ... Then you can tackle the last and most challenging task, which is to design your overall system: Infrastructure, layers and your business-logic modules/classes. Go in small steps! That will also keep your motivation up as you get feedback after each step. HTH, Jan > Please help. > Sent from my BlackBerry wireless device from MTN > > -----Original Message----- > From: "Alan Gauld" > Sender: tutor-bounces+delegbede=dudupay.com at python.org > Date: Sat, 20 Nov 2010 09:00:52 > To: > Subject: Re: [Tutor] JOB AD PROJECT > > > wrote > >> I have done some extensive reading on python. >> i want to design a classifieds site for jobs. > > Have you done any extensive programming yet? > Reading alone will be of limited benefit and jumping into > a faurly complex web project before you have the basics > mastered will be a painful experience. > > I'm assuming you have at least some experience of > web programming in other languages for you to take > such a bold step? > > >> I am taking this as my first project and would appreciate any help. >> I am looking in the direction of python, maybe django. > > The choice of tools is fine, but its a big task for a first > ever Python project! > > HTH, > > From cbeg at gmx.de Sun Nov 21 14:12:47 2010 From: cbeg at gmx.de (Chris Begert) Date: Sun, 21 Nov 2010 14:12:47 +0100 Subject: [Tutor] lists, arrays and saving data Message-ID: <20101121131247.220910@gmx.net> Hi Gurus I just wrote my first little python program; so yes I'm very new to all this. The goal in the end is to have a program that shows how the sun moves from the point of view of a given location (i.e. solar paths added to some sort of stereographic diagram). My very first program calculates the height (altitude) and direction of the sun (Azimuth) at a specific location during a specific time. So here's my question (I'm sure its obvious for most of you): How do I store a years worth of data of angles in an array / list / whatever is most useful when using Python? Thanks in advance for your answers. Cheers Chris BTW,Here's what I wrote: ## http://answers.google.com/answers/threadview/id/782886.html ## Das Programm berechnet die H?he und Richtung der Sonne zu einer bestimmten Zeit f?r einen bestimmten Ort ## Die Formeln sind vor der obigen webseite und sollten gepr?ft werden. ## Ist die Equation of Time genauer? from datetime import date import datetime import math ## geht das einfacher? from math import sin from math import cos from math import degrees from math import radians from math import acos ## Input - sp?ter ein drop-down men? print("Please specify your location") long = float(input("Longitude in degrees: ")) lati = float(input("Latitude in degrees: ")) ## Das wird sp?ter mal ne range basierend auf dem Ort month = int(input("Month: ")) day = int(input("Day: ")) hour = float(input("Hour: ")) minutes = float(input("Minutes: ")) ## Berechnung der Nummer des Tages time = hour + minutes/60 Nd = datetime.datetime(2010,month,day).timetuple().tm_yday ## this is the fractional year gdeg = (360/365.25)*(Nd + time/24) g = math.radians(gdeg) ## SOLAR DECLINATION ## Follows the calculation of the declination of the sun, again you an use a table or a formula ##"Table of the Declination of the Sun": http://www.wsanford.com/~wsanford/exo/sundials/DEC_Sun.html ## Or use the following formula: D = 0.396372-22.91327*math.cos(g)+4.02543*math.sin(g)-0.387205*math.cos(2*g)+0.051967*math.sin(2*g)-0.154527*math.cos(3*g) + 0.084798*math.sin(3*g) ##Now calculate the TIME CORRECTION for solar angle: TC = 0.004297+0.107029*math.cos(g)-1.837877*sin(g)-0.837378*cos(2*g)-2.340475*sin(2*g) ## Now we can calculate the Solar Hour Angle (SHA) SHA = (time-12)*15 + long + TC if SHA > 180: SHA = SHA - 360 elif SHA< -180: SHA = SHA + 360 else: SHA = SHA print(SHA) ##Now we can calculate the Sun Zenith Angle (SZA): cosSZA = sin(radians(lati))*sin(radians(D))+cos(radians(lati))*cos(radians(D))*cos(radians(SHA)) SZA = degrees(acos(cosSZA)) altitude = 90 - SZA ##To finish we will calculate the Azimuth Angle (AZ): cosAZ = (sin(radians(D)) - sin(radians(lati)) * cos(radians(SZA))) / (cos(radians(lati))*sin(radians(SZA))) AZ = degrees(acos(cosAZ)) print("Altitude: ", altitude) print("Azimuth: ",AZ) -- GMX DSL Doppel-Flat ab 19,99 €/mtl.! Jetzt auch mit gratis Notebook-Flat! http://portal.gmx.net/de/go/dsl From josep.m.fontana at gmail.com Sun Nov 21 17:15:28 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sun, 21 Nov 2010 17:15:28 +0100 Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: References: <4CE7ACC2.60909@pearwood.info> Message-ID: Martin, Alan, col speed and everybody that helped: I think I'm going to stop because I'm repeating myself but it is difficult for me not to be profuse in my thanks because you guys really go beyond the call of duty. I love this list. The responses in this list most of the times don't just address the problem at hand but are also useful in a more general sense and help people become better programmers. So, thanks for all the good advice as well as helping me solve the particular problem I had. Let me address some particular points you've made: On Sun, Nov 21, 2010 at 12:01 AM, Martin A. Brown wrote: > ?: It turns out that matters of efficiency appear to be VERY > ?: important in this case. The example in my message was a very > Efficiency is best addressed first and foremost, not by hardware, > but by choosing the correct data structure and algorithm for > processing the data. ?You have more than enough hardware to deal > with this problem, Yes indeed. Now that I fixed the code following your advice and Alan's, it took a few seconds for the script to run and yield the desired results. Big sigh of relief: my investment in a powerful computer was not in vain. > This is far afield from the question of word count, but may be > useful someday. > > The beauty of a multiple processors is that you can run independent > processes simultaneously (I'm not talking about multitasking). > ?http://docs.python.org/library/threading.html > ?http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/ > ?http://www.dabeaz.com/python/GIL.pdf VERY useful information, thanks! > OK, on to your code. > > ?: def countWords(wordlist): > ?: ? ? word_table = {} > ?: ? ? for word in wordlist: > ?: ? ? ? ? count = wordlist.count(word) > ?: ? ? ? ? print "word_table[%s] = %s" % (word,word_table.get(word,'')) > ?: ? ? ? ? word_table[word] = count > > Problem 1: ?You aren't returning anything from this function. > ?Add: > ? ? ? return word_table Sorry, since I had a lot of comments on my code (I'm learning and I want to document profusely everything I do so that I don't have to reinvent the wheel every time I try to do something) and before posting it here I did a lot of deleting. Unintentionally I deleted the following line (suggested in Steve's original message) that contained the return: return sorted(word_table.items(), key=lambda item: item[1], reverse=True) Even adding this, though, the process was taking too long and I had to kill it. When I fixed my mistake in Peter Otten's code (see below) everything worked like a charm. By the way, I know what a lambda function is and I read about the key parameter in sorted() but I don't understand very well what "key=lambda item: item[1]" does. It has to do with taking the value '1' as term for comparison, I guess, since this returns an ordered list according to the number of times a word appears in the text going from the most frequent to the less frequent and reverse=True is what changes the order in which is sorted. What I don't understand is the syntax of "item : item[1]". > ?: def countWords2(wordlist): #as proposed by Peter Otten > ?: ? ? word_table = {} > ?: ? ? for word in wordlist: > ?: ? ? ? ? if word in word_table: > ?: ? ? ? ? ? ? word_table[word] += 1 > ?: ? ? ? ? else: > ?: ? ? ? ? ? ? word_table[word] = 1 > ?: ? ? ? ? count = wordlist.count(word) > ?: ? ? ? ? word_table[word] = count > ?: ? ? return sorted( > ?: ? ? ? ? ? ? ? ? ? word_table.items(), key=lambda item: item[1], reverse=True > ?: ? ? ? ? ? ? ? ? ? ) > > In the above, countWords2, why not omit these lines: > > ?: ? ? ? ? count = wordlist.count(word) > ?: ? ? ? ? word_table[word] = count Sorry this was my mistake and it is what was responsible for the script hanging. This is the problem with cutting and pasting code and not revising what you copied. I took Steve's code as the basis and tried to modify it with Peter's code but then I forgot to delete these two lines that were in Steve's code. Since it worked with the test I did with the light file, I didn't even worry to check it. Live and learn. > Let try a (bit of a labored) analogy of your problem. ?To > approximate your algorithm. > > ?I have a clear tube with gumballs of a variety of colors. > ?I open up one end of the tube, and mark where I'm starting. This is what I said at the beginning. This little analogy was pedagogically very sound. Thanks! I really appreciate (and I hope others will do as well) your time. > Once you gain familiarity with the lists and dicts, you can try out > collections, as suggested by Peter Otten. The problem is that I'm using version 2.6.1. I have a Mac and I am using a package called NLTK to process natural language. I tried to install newer versions of Python on the Mac but the result was a mess. The modules of NLTK worked well with the default Python installation but not with the newer versions I installed. They recommend not to delete the default version of Python in the Mac because it might be used by the system or some applications. So I had to go back to the Python version that comes installed by default in the Mac. Josep M. From python at bdurham.com Sun Nov 21 19:06:37 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 21 Nov 2010 13:06:37 -0500 Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: References: <4CE7ACC2.60909@pearwood.info> Message-ID: <1290362797.21571.1406426967@webmail.messagingengine.com> > it is difficult for me not to be profuse in my thanks because you guys really go beyond the call of duty. I love this list. The responses in this list most of the times don't just address the problem at hand but are also useful in a more general sense and help people become better programmers. So, thanks for all the good advice as well as helping me solve the particular problem I had. Not the OP, but a big +1 from me! Malcolm From alan.gauld at btinternet.com Sun Nov 21 19:19:25 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Nov 2010 18:19:25 -0000 Subject: [Tutor] Simple counter to determine frequencies of words in adocument References: <4CE7ACC2.60909@pearwood.info> Message-ID: "Josep M. Fontana" wrote > : return sorted( > : word_table.items(), key=lambda item: item[1], reverse=True > : ) > By the way, I know what a lambda function is and I read about the > key > parameter in sorted() but I don't understand very well what > "key=lambda item: item[1]" does. ... > ....What I don't understand is the syntax of "item : item[1]". OK, So you know that a lambda is an anonymous function and g = lambda x: f(x) can be rewritten as: def g(x): return f(x) So in your case you could have done: def getSecond(item): return item[1] return sorted( word_table.items(), key=getSecond, reverse=True) So reverse engineering that we get lambda item: item[1] item is the parameter of the anonymous function. and item[1] is the return value. (The colon separates parameter from return value) > > Once you gain familiarity with the lists and dicts, you can try > > out > > collections, as suggested by Peter Otten. > > The problem is that I'm using version 2.6.1. I have a Mac and I am > using a package called NLTK to process natural language. Thats no problem. 2.6 is a recent version of Puython, I see no reason to change Python version for now. You can run other python versions on the Mac alongside your default install but for now you have no good reason to do so. Keep life simple :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Sun Nov 21 19:25:33 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 21 Nov 2010 10:25:33 -0800 Subject: [Tutor] lists, arrays and saving data In-Reply-To: <20101121131247.220910@gmx.net> References: <20101121131247.220910@gmx.net> Message-ID: On 11/21/2010 5:12 AM Chris Begert said... > Hi Gurus > > I just wrote my first little python program; so yes I'm very new to all this. > > The goal in the end is to have a program that shows how the sun moves from the point of view of a given location (i.e. solar paths added to some sort of stereographic diagram). > > My very first program calculates the height (altitude) and direction of the sun (Azimuth) at a specific location during a specific time. > > So here's my question (I'm sure its obvious for most of you): > > How do I store a years worth of data of angles in an array / list / whatever is most useful when using Python? > > I would look at moving the calculation part into a function that accepts as input the location, date and time parameters and returns the results. Then you could write a loop to build the list for the locations and date ranges of interest. Your choice for data persistence would depend in part on how the data is to be used and how much there is. Take a look at the options python comes with at http://docs.python.org/py3k/library/persistence.html but for small data sets building the data on the fly may be sufficient as creating a full year of data at ten minute intervals takes thee seconds on my PC. Below is how I refactored things. Emile ----- import datetime, time from math import sin from math import cos from math import degrees from math import radians from math import acos def getLocation(): print("Please specify your location") long = float(input("Longitude in degrees: ")) lati = float(input("Latitude in degrees: ")) return long,lati def getAltAZ (long,lati,month,day,hour,minutes): time = hour + minutes/60 Nd = datetime.datetime(2010,month,day).timetuple().tm_yday gdeg = (360/365.25)*(Nd + time/24) g = radians(gdeg) D = 0.396372-22.91327*cos(g)+4.02543*sin(g)-0.387205*cos(2*g)+0.051967*sin(2*g)-0.154527*cos(3*g) + 0.084798*sin(3*g) TC = 0.004297+0.107029*cos(g)-1.837877*sin(g)-0.837378*cos(2*g)-2.340475*sin(2*g) SHA = (time-12)*15 + long + TC if SHA > 180: SHA = SHA - 360 elif SHA< -180: SHA = SHA + 360 cosSZA = sin(radians(lati))*sin(radians(D))+cos(radians(lati))*cos(radians(D))*cos(radians(SHA)) SZA = degrees(acos(cosSZA)) altitude = 90 - SZA cosAZ = (sin(radians(D)) - sin(radians(lati)) * cos(radians(SZA))) / (cos(radians(lati))*sin(radians(SZA))) AZ = degrees(acos(cosAZ)) return altitude,AZ def prepFullYear(long,lati, interval=10): return [getAltAZ(long,lati,*time.localtime(t+ii)[1:5]) for ii in range(0,60*24*365,interval)] if __name__ == '__main__': t = time.time() fy = prepFullYear(100,30) print (time.time()-t) From emile at fenx.com Sun Nov 21 19:35:07 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 21 Nov 2010 10:35:07 -0800 Subject: [Tutor] Simple counter to determine frequencies of words in a document In-Reply-To: References: <4CE7ACC2.60909@pearwood.info> Message-ID: On 11/21/2010 8:15 AM Josep M. Fontana said... > return sorted(word_table.items(), key=lambda item: item[1], reverse=True) > What I don't understand is the syntax of "item : item[1]". Key defines a lambda function that accepts as a single passed parameter named item and returns the element in position [1] thereof. HTH, Emile From alan.gauld at btinternet.com Sun Nov 21 19:35:15 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Nov 2010 18:35:15 -0000 Subject: [Tutor] lists, arrays and saving data References: <20101121131247.220910@gmx.net> Message-ID: "Chris Begert" wrote > How do I store a years worth of data of angles in an > array / list / whatever is most useful when using Python? The choice of data structure usually depends on how you plan on accessing/using it. So we can't advise until we know more about what you plan on doing with it! The good news it that in Python its usuially easy to switch between the various options if you think you got it wrong! Having said that my guess is that a list of tuples will be your best starting point. Put all the values for a given time into a tuple (or maybe a dictionary). Then store the list of timed values in a list (or another dictionary(keyed by time) ) > from datetime import date > import datetime > import math > > ## geht das einfacher? > from math import sin > from math import cos > from math import degrees > from math import radians > from math import acos from math import sin,cos,degrees,radians,acos is easier to type :-) > ## Input - sp?ter ein drop-down men? > print("Please specify your location") > long = float(input("Longitude in degrees: ")) > lati = float(input("Latitude in degrees: ")) If you put this in a function which returns the values you need it will be easier to convert to a GUI(or web page) later. > month = int(input("Month: ")) > day = int(input("Day: ")) > hour = float(input("Hour: ")) > minutes = float(input("Minutes: ")) Are you sure you want to allow floating point hours and minutes? > time = hour + minutes/60 See above comment - what if hours is 1.5 and minutes is 37.3? Is time sensible? > Nd = datetime.datetime(2010,month,day).timetuple().tm_yday > gdeg = (360/365.25)*(Nd + time/24) > g = math.radians(gdeg) you imported radians so you don't need the math prefix > D = > 0.396372-22.91327*math.cos(g)+4.02543*math.sin(g)-0.387205*math.cos(2*g)+0.051967*math.sin(2*g)-0.154527*math.cos(3*g) > + 0.084798*math.sin(3*g) > Fopr long calculations you might find it easioer to read/antain if you put a set of parent around the outside then separate your main terms into lines, like this: > D = ( 0.396372-22.91327*math.cos(g) + 4.02543*math.sin(g)-0.387205*math.cos(2*g) + 0.051967*math.sin(2*g)-0.154527*math.cos(3*g) + 0.084798*math.sin(3*g) ) Using symbols for the constants would help too, especially if there are some standard names you can use, like alpha etc? > ##Now calculate the TIME CORRECTION for solar angle: > TC = > 0.004297+0.107029*math.cos(g)-1.837877*sin(g)-0.837378*cos(2*g)-2.340475*sin(2*g) > > > ## Now we can calculate the Solar Hour Angle (SHA) > SHA = (time-12)*15 + long + TC > if SHA > 180: > SHA = SHA - 360 > elif SHA< -180: > SHA = SHA + 360 > else: > SHA = SHA > print(SHA) > > > ##Now we can calculate the Sun Zenith Angle (SZA): > cosSZA = > sin(radians(lati))*sin(radians(D))+cos(radians(lati))*cos(radians(D))*cos(radians(SHA)) > SZA = degrees(acos(cosSZA)) > altitude = 90 - SZA > > > ##To finish we will calculate the Azimuth Angle (AZ): > cosAZ = (sin(radians(D)) - sin(radians(lati)) * cos(radians(SZA))) / > (cos(radians(lati))*sin(radians(SZA))) > AZ = degrees(acos(cosAZ)) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kb1pkl at aim.com Sun Nov 21 19:34:57 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 21 Nov 2010 13:34:57 -0500 Subject: [Tutor] lists, arrays and saving data In-Reply-To: <20101121131247.220910@gmx.net> References: <20101121131247.220910@gmx.net> Message-ID: <4CE96651.70402@aim.com> On 11/21/2010 8:12 AM, Chris Begert wrote: > Hi Gurus > > I just wrote my first little python program; so yes I'm very new to all this. > > The goal in the end is to have a program that shows how the sun moves from the point of view of a given location (i.e. solar paths added to some sort of stereographic diagram). > > My very first program calculates the height (altitude) and direction of the sun (Azimuth) at a specific location during a specific time. > > So here's my question (I'm sure its obvious for most of you): > > How do I store a years worth of data of angles in an array / list / whatever is most useful when using Python? > > Well now. You can store altitude and AZ in a tuple, and append that tuple to a list called, for example, data. data.append((altitude, AZ)), where data = list(). You will probably want to wrap all that calculation into a function that takes 6 arguments: longitude, latitude, month, day, hour, and minutes, instead of taking that input by hand. That way you can put everything into a nice for loop (in theory). From robert.sjoblom at gmail.com Mon Nov 22 00:29:36 2010 From: robert.sjoblom at gmail.com (=?ISO-8859-1?Q?Robert_Sj=F6blom?=) Date: Mon, 22 Nov 2010 00:29:36 +0100 Subject: [Tutor] Help regarding lists, dictionaries and tuples Message-ID: Hi. I'm new at programming and, as some others on this list, am going through Python Programming for the Absolute Beginner. In the current chapter (dealing with lists and dictionaries), one of the challenges is to: >Write a Character Creator program for a role-playing game. The player should be given a pool of 30 points to spend on four attributes: Strength, Health, Wisdom, and Dexterity. The >player should be able to spend points from the pool on any attribute and should also be able to take points from an attribute and put them back into the pool. I don't want a direct answer on how to proceed, but a question that arose during my thinking of the problem was whether dictionaries can have integral data in them, like so: attributes = {"Strength" : 28, "Health" : 12} or if they have to be: attributes = {"Strength" : "28", "Health" : "12"} Ok, I'm clearly thinking in circles here. I used the interpreter to figure out that both are fine but the first example has integers, whereas the second has strings. Good to know. What I'm wondering then, instead, is whether there's a good way to sum up the value of integral data in a dictionary? I suppose I could solve the challenge by setting up 4 different variables and going at it that way, but since the challenge is listed in a chapter dealing with Lists and Dictionaries (and tuples), I figure there should be some way to solve it with those tools. In a somewhat related note: the book gives quite hard challenges, the coin flip challenge discussed here a few days ago, for example, comes before the reader learns about for loops. Thanks in advance, and best regards, Robert S. From hugo.yoshi at gmail.com Mon Nov 22 00:42:21 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 22 Nov 2010 00:42:21 +0100 Subject: [Tutor] Help regarding lists, dictionaries and tuples In-Reply-To: References: Message-ID: On Mon, Nov 22, 2010 at 12:29 AM, Robert Sj?blom wrote: > Hi. I'm new at programming and, as some others on this list, am going > through Python Programming for the Absolute Beginner. In the current > chapter (dealing with lists and dictionaries), one of the challenges > is to: >>Write a Character Creator program for a role-playing game. The player should be given a pool of 30 points to spend on four attributes: Strength, Health, Wisdom, and Dexterity. The >player should be able to spend points from the pool on any attribute and should also be able to take points from an attribute and put them back into the pool. > > I don't want a direct answer on how to proceed, but a question that > arose during my thinking of the problem was whether dictionaries can > have integral data in them, like so: > attributes = {"Strength" : 28, "Health" : 12} > or if they have to be: > attributes = {"Strength" : "28", "Health" : "12"} > > Ok, I'm clearly thinking in circles here. I used the interpreter to > figure out that both are fine but the first example has integers, > whereas the second has strings. Good to know. What I'm wondering then, > instead, is whether there's a good way to sum up the value of integral > data in a dictionary? > I will point you toward two things. First, the dict class has a method called values(). Read the documentation on that, go into your interpreter, make some dictionaries, and call the values() method, see what comes up. The second thing is the sum() method. Again, read the documentation on it and experiment with it a little. Those two should suffice to answer your question. I always encourage people to play around with their problems in the interactive interpreter, discovering what works and what doesn't for yourself is often a great way to learn. Combine that with http://docs.python.org and you've got some very powerful learning tools Hugo From robert.sjoblom at gmail.com Mon Nov 22 01:48:45 2010 From: robert.sjoblom at gmail.com (=?ISO-8859-1?Q?Robert_Sj=F6blom?=) Date: Mon, 22 Nov 2010 01:48:45 +0100 Subject: [Tutor] Help regarding lists, dictionaries and tuples In-Reply-To: References: Message-ID: [Snip] >> I don't want a direct answer on how to proceed, but a question that >> arose during my thinking of the problem was whether dictionaries can >> have integral data in them, like so: >> attributes = {"Strength" : 28, "Health" : 12} >> or if they have to be: >> attributes = {"Strength" : "28", "Health" : "12"} >> >> Ok, I'm clearly thinking in circles here. I used the interpreter to >> figure out that both are fine but the first example has integers, >> whereas the second has strings. Good to know. What I'm wondering then, >> instead, is whether there's a good way to sum up the value of integral >> data in a dictionary? >> > > I will point you toward two things. First, the dict class has a method > called values(). Read the documentation on that, go into your > interpreter, make some dictionaries, and call the values() method, see > what comes up. > > The second thing is the sum() method. Again, read the documentation on > it and experiment with it a little. Those two should suffice to answer > your question. They did indeed! I did run across values() before sending the message, but didn't quite get it to work properly -- reading up on it, I figured out that I've been calling the method completely wrong. > I always encourage people to play around with their problems in the > interactive interpreter, discovering what works and what doesn't for > yourself is often a great way to learn. Combine that with > http://docs.python.org and you've got some very powerful learning > tools Yeah, using the interpreter is very helpful, I've found. I find that even if I've studied something in the documentation, I need to use the interpreter to figure out how it actually works. Maybe that will get better in time, but for now it's a very useful tool in trial-and-error. I had to try out values() and sum() before I could understand them fully. Thanks again, much appreciated. best regards, Robert S. From bgailer at gmail.com Mon Nov 22 06:15:08 2010 From: bgailer at gmail.com (bob gailer) Date: Mon, 22 Nov 2010 00:15:08 -0500 Subject: [Tutor] Help regarding lists, dictionaries and tuples In-Reply-To: References: Message-ID: <4CE9FC5C.8010009@gmail.com> On 11/21/2010 6:29 PM, Robert Sj?blom wrote: > Hi. I'm new at programming and, as some others on this list, am going > through Python Programming for the Absolute Beginner. In the current > chapter (dealing with lists and dictionaries), one of the challenges > is to: >> Write a Character Creator program for a role-playing game. The player should be given a pool of 30 points to spend on four attributes: Strength, Health, Wisdom, and Dexterity. The>player should be able to spend points from the pool on any attribute and should also be able to take points from an attribute and put them back into the pool. > I don't want a direct answer on how to proceed, but a question that > arose during my thinking of the problem was whether dictionaries can > have integral data in them, like so: > attributes = {"Strength" : 28, "Health" : 12} > or if they have to be: > attributes = {"Strength" : "28", "Health" : "12"} > > Ok, I'm clearly thinking in circles here. I used the interpreter to > figure out that both are fine but the first example has integers, > whereas the second has strings. Good to know. What I'm wondering then, > instead, is whether there's a good way to sum up the value of integral > data in a dictionary? Why would you want to sum them? You start with 30 points in the pool, then allocate them to the attributes. The sum will still be 30. > I suppose I could solve the challenge by setting up 4 different > variables and going at it that way, but since the challenge is listed > in a chapter dealing with Lists and Dictionaries (and tuples), I > figure there should be some way to solve it with those tools. > -- Bob Gailer 919-636-4239 Chapel Hill NC From no.dr at gmx.de Mon Nov 22 08:28:09 2010 From: no.dr at gmx.de (Joachim Roop) Date: Mon, 22 Nov 2010 08:28:09 +0100 Subject: [Tutor] telnetlib - character hex00 missing Message-ID: <20101122072809.230700@gmx.net> Even though my non-python telnet-server on the other side is sending #00-bytes, they are not recognized by python's telnetlib (characters #01-#FF seem to work fine though). My C++ implementation has no problems with this. I have to use Python 3.1 on Windows. I'm guessing this a known bug. What is the workaround? :( # Receiver tn = telnetlib.Telnet() tn.open(ip, port) while 1: response = (tn.read_until(b"\r",20))[1:-1] if response.find(bytes.fromhex("00")) > -1: print ("There are hex00 characters") else: print ("No hex00 characters found") tn.close -- Neu: GMX De-Mail - Einfach wie E-Mail, sicher wie ein Brief! Jetzt De-Mail-Adresse reservieren: http://portal.gmx.net/de/go/demail From josep.m.fontana at gmail.com Mon Nov 22 09:56:27 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Mon, 22 Nov 2010 09:56:27 +0100 Subject: [Tutor] Lambda function, was: Simple counter to determine frequencies of words in adocument Message-ID: Thanks Alan and Emile, >> By the way, I know what a lambda function is and I read about the key >> parameter in sorted() but I don't understand very well what >> "key=lambda item: item[1]" does. ... >> ....What I don't understand is the syntax of "item : item[1]". > ... Alan says: > So reverse engineering that we get > > lambda item: item[1] > > item is the parameter of the anonymous function. > and item[1] is the return value. (The colon separates parameter > from return value) Emile says: >Key defines a lambda function that accepts as a single passed parameter named item and >returns the element in position [1] thereof. OK, the explanation is very clear. I guess what confuses me here is the use of the term 'item' and here I'm going to reveal my greenness in Python and programming in general. So, I know the term 'item' is used in general to refer to the different elements that are part of a collection. Thus an item in a dictionary would be a dictionary "entry" of the type {x:y}, an item in a list would be any of the elements that can be a member of a list (a digit, a string, another list, etc.). In this case, an item would be a tuple of the form (word, x) and so item[1] refers to x. Since the key parameter indicates which term is supposed to be used for comparison in the sorting, in this case the result will be that the sorting will be done according to the digits in that position. So, that much is clear. What I don't understand is the nature of the term 'item'. Is it a variable? Is it some kind of built-in "term" (it cannot be a built-in data type since it refers to elements of different data types)? I checked the Python books I have and did some googling and the only uses I find of 'item' are generic uses where it is clear that 'item' refers generically to members of some collection but it does not look like it is some built-in name in Python. I mean, since the first time 'item' is mentioned is within the lambda function, how does Python know that item[1] refers to the second position of the tuple? If it is a variable, where is it defined? I see how you get to that conclusion through human reasoning but I'm trying to understand how Python does it. Does python know because the only thing that word_table.items() contains is a list of tuples and therefore X[1] can only refer to the second position in the tuple in this particular context? Would this work if instead of item[1] the code said foobar[1]? Understanding the inner workings of Python (or programming languages in general) can help me (and anybody) become better at this. Do you see what I mean? Josep M. From alan.gauld at btinternet.com Mon Nov 22 10:07:06 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Nov 2010 09:07:06 -0000 Subject: [Tutor] telnetlib - character hex00 missing References: <20101122072809.230700@gmx.net> Message-ID: "Joachim Roop" wrote > Even though my non-python telnet-server on the other side is > sending #00-bytes, they are not recognized by python's telnetlib > (characters #01-#FF seem to work fine though). > My C++ implementation has no problems with this. > I have to use Python 3.1 on Windows. > > I'm guessing this a known bug. What is the workaround? :( Telnetlib has been around for at least 10 years so I'd expect a bug that serious to have been fixed long ago! I suspect something else is at fault. > # Receiver > tn = telnetlib.Telnet() > tn.open(ip, port) > > while 1: Aside: Python idiom nowadays prefers "while True:" to "while 1:" > response = (tn.read_until(b"\r",20))[1:-1] It might be worth breaking this line down and printing the results data = tn.read_until(b"\r",20) # did telnet even read the 00? response = data[1:-1] # did we strip it correctly? > if response.find(bytes.fromhex("00")) > -1: > print ("There are hex00 characters") > else: > print ("No hex00 characters found") > > tn.close Others may have more info, but I'll be surprised if telnetlib can't read a '00'. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From josep.m.fontana at gmail.com Mon Nov 22 10:13:13 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Mon, 22 Nov 2010 10:13:13 +0100 Subject: [Tutor] IDEs Message-ID: Alan gave me this piece of advice in his response to another message I sent to the list. Since the topic is a bit different from the one in the original message, I think it is better to start a different thread. > Don;t run your code inside the IDE except for testing. IDEs are > Development Environments, they are not ideal for executing production > code. Run your file from the Terminal command prompt directly. I thought the code was not run inside the IDE but it was run by Python independently, that is, the IDE just provides an interface. When I run code from within Eclipse (the IDE I'm starting to use) I can see a Python process in my process monitor. The process for Eclipse is consuming very little CPU. So, what is the advantage of running the file from Terminal? I can see only disadvantages: a) it is slower since I have to type $python filename.py (ok, this takes very little time but clicking a button or typing a key shortcut to execute the code takes less time) b) with the terminal I don't get the debugging benefits that an IDE provides (I must say though that I still haven't really taken advantage of the benefits that Eclipse provides since the code I'm writing so far is pretty simple). JM From alan.gauld at btinternet.com Mon Nov 22 10:20:25 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 22 Nov 2010 09:20:25 +0000 (GMT) Subject: [Tutor] Lambda function, was: Simple counter to determine frequencies of words in adocument In-Reply-To: References: Message-ID: <41083.43755.qm@web86706.mail.ird.yahoo.com> > What I don't understand is the nature of the term 'item'. Is it a > variable? Yes, its just a descriptive name. You could have used x just as easily, Python doesn't know, nor care. It is just like in defining any normal function def f(x): return x is exactly the same as: def f(data): return data data is just a different name for the input parameter. > refers generically to members of some collection but it does not look > like it is some built-in name in Python. Correct, the name 'item' has been used to be descriptive of what kind of thing the lambda is processing. In this case an item from the collection to be sorted. > I mean, since the first time 'item' is mentioned is within the lambda > function, how does Python know that item[1] refers to the second > position of the tuple? If it is a variable, where is it defined? When you specify a parameter you create a variable. def f(data): return data creates a local variable called data within my function f. > to understand how Python does it. Does python know because the only > thing that word_table.items() contains is a list of tuples No, it knows because you defined the variable 'item' before the colon lambda item : item[1] So Python looks at the name(s) before the colon and uses them within the expression following the colon. You can have multiple names (or none) before the colon, try: >>> f = lambda : 6 # no parameters >>> f() 6 >>> g = lambda a,b : a+b # two parameters >>> g(2,3) 5 >>> cube = lambda sillyName: sillyName**3 >>> cube(3) 27 > this particular context? Would this work if instead of item[1] the > code said foobar[1]? only if you specified foobar before the colon! > Understanding the inner workings of Python (or programming languages > in general) can help me (and anybody) become better at this. Do you > see what I mean? Absolutely true. You may like to track down a (library?) copy of Wesley Chun's book Core Python. It does a very good job of explaining to beginners what Python is up to internally. In my opinion its the best book for those beginners who like to "peer under the hood". HTH, Alan G. Author of the Learn to Program site http://www.alan-g.me.uk/ From steve at pearwood.info Mon Nov 22 10:27:46 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Nov 2010 20:27:46 +1100 Subject: [Tutor] telnetlib - character hex00 missing In-Reply-To: <20101122072809.230700@gmx.net> References: <20101122072809.230700@gmx.net> Message-ID: <4CEA3792.3000409@pearwood.info> Joachim Roop wrote: > Even though my non-python telnet-server on the other side is sending #00-bytes, they are not recognized by python's telnetlib (characters #01-#FF seem to work fine though). > My C++ implementation has no problems with this. I have to use Python 3.1 on Windows. > > I'm guessing this a known bug. What is the workaround? :( Don't guess, search. http://bugs.python.org/ > # Receiver > tn = telnetlib.Telnet() > tn.open(ip, port) > > while 1: > response = (tn.read_until(b"\r",20))[1:-1] Is there a reason that you throw away the first and last byte being read? My wild guess is that the NULL is either the first byte, or most likely the last, and then you throw it away. > if response.find(bytes.fromhex("00")) > -1: It might be simpler to use a byte literal instead of calling a function to generate a NULL. if response.find(b'\x00') > -1: > print ("There are hex00 characters") > else: > print ("No hex00 characters found") > > tn.close Hope this helps. -- Steven From marc.tompkins at gmail.com Mon Nov 22 11:12:04 2010 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 22 Nov 2010 02:12:04 -0800 Subject: [Tutor] IDEs In-Reply-To: References: Message-ID: On Mon, Nov 22, 2010 at 1:13 AM, Josep M. Fontana wrote: > Alan gave me this piece of advice in his response to another message I > sent to the list. Since the topic is a bit different from the one in > the original message, I think it is better to start a different > thread. > > > Don;t run your code inside the IDE except for testing. IDEs are > > Development Environments, they are not ideal for executing production > > code. Run your file from the Terminal command prompt directly. > > The issue is that phrase "production code". If you're just noodling around, "production" can mean printing "Hello World." If, on the other hand, you're writing Python code to solve real-world problems and the end goal is for users to install and run your applications on their own machines... then testing/running inside the IDE is an issue, because the environment is so different from anything you'll find "in the wild." The most egregious case is trying to run GUI code from inside of IDLE (the basic IDE that ships with Python.) Nothing works properly, and IDLE introduces all sorts of weirdness, but people keep doing it. Testing outside the IDE doesn't have to be a big deal. You don't have to type "$python filename.py" every time; you could keep a terminal window open so you can just up-arrow through the command history, or (what I usually do) create a shortcut to my file on the desktop. Just make sure you've saved your changes - you generally don't have to close the IDE. > I thought the code was not run inside the IDE but it was run by Python > independently, that is, the IDE just provides an interface. > The IDE spawns an instance of Python as a child process; it inherits the IDE's environment. That can lead to surprising behavior if you don't know what's been set in the IDE'S environment. b) with the terminal I don't get the debugging benefits that an IDE > provides (I must say though that I still haven't really taken > advantage of the benefits that Eclipse provides since the code I'm > writing so far is pretty simple). > Nobody is saying that you shouldn't debug in the IDE! Just that the IDE is not the best place to run finished code, nor is IDE-based debugging the last step in testing code that's intended to run on other people's machines. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Nov 22 11:19:30 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Nov 2010 21:19:30 +1100 Subject: [Tutor] IDEs In-Reply-To: References: Message-ID: <4CEA43B2.2030907@pearwood.info> Josep M. Fontana wrote: >> Don;t run your code inside the IDE except for testing. IDEs are >> Development Environments, they are not ideal for executing production >> code. Run your file from the Terminal command prompt directly. > > I thought the code was not run inside the IDE but it was run by Python > independently, that is, the IDE just provides an interface. > When I run code from within Eclipse (the IDE I'm starting to use) I > can see a Python process in my process monitor. The process for > Eclipse is consuming very little CPU. I don't know about Eclipse specifically, but I understand that IDEs can often mess with the Python environment. E.g. they might change settings, add wrappers around functions to change the behaviour, install import hooks, change stdin and stdout, etc. Personally, I don't think IDEs are necessary under Linux (although Windows users might find them more useful, due to the otherwise poor development tools available). I haven't used an IDE since THINK Pascal and Hypercard in the early 1990s -- I've looked at them, but the learning curve always seems far greater than the benefit. > So, what is the advantage of running the file from Terminal? I can see > only disadvantages: > > a) it is slower since I have to type $python filename.py (ok, this > takes very little time but clicking a button or typing a key shortcut > to execute the code takes less time) If you're repeatedly running the file, it takes even less time to just hit UP-ARROW to get the last-used line, then ENTER to execute it. My usual working technique is: I have an editor and a terminal open. The terminal has at least two tabs open. One tab is for the shell, where I run `python filename.py`. The second tab is for running an interactive Python shell. I run the script from one tab, and see if it works: $ python filename.py After the first time, I just hit UP ARROW and ENTER. If it doesn't work, nine times out of ten I can see why just from the failure. I fix that bug in the editor, and run it again. Repeat until no more bugs. The other nine times out of ten *wink* I need to do debugging, and I swap tabs and work in my interactive Python interpreter. import filename # first time only reload(filename) # all subsequent times # test something: filename.function_that_isnt_working(some_useful_data) (I keep meaning to learn how to use the Python debugger, but honestly, I haven't needed it yet. You can go a long, long way with a few print statements.) Notice that this is a very good reason for breaking your programs up into small, single-purpose functions. It makes it simple to isolate problems into a small part of your program. Occasionally, when the environment gets too full of testing gunk, I exit the interpreter, and then immediately start it up again. Also, I'm a big believer in test-driven development. I must admit though I'm not so pedantic to write the tests first, but for anything except quick-and-dirty scripts, I make sure that *every* function in my program, without exception, has a test to ensure that it works correctly. So I'll often have a third tab open for running my test suite. I use a mix of doctests and unit-tests. Here's an example from a project I'm working on at the moment: [steve at sylar tests]$ python3 main_test.py Doctests: failed 0, attempted 80 WARNING: No example text file found. Running unit tests: ............................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 255 tests in 0.491s OK No garbage found. [steve at sylar tests]$ If I see that, I know everything is working correctly (to the extent that everything is covered by tests). Each dot in the output represents one test. A dot means the test passes, E means it has an error, and F means the test failed. If there are any errors or failures, a full diagnostic is printed. Of course, it's a bit more work up front to write the tests, but: (1) it pays off a dozen times over in the long run; (2) the discipline of writing functions that are easy to test forces you to use good programming practice, avoid bad habits, and helps you design the program to be easy to maintain and debug; and (3) if you want your work to be included in the standard library, you MUST have a full test suite. -- Steven From alan.gauld at btinternet.com Mon Nov 22 20:39:17 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 22 Nov 2010 19:39:17 -0000 Subject: [Tutor] IDEs References: Message-ID: "Josep M. Fontana" wrote >> Don;t run your code inside the IDE except for testing. IDEs are >> Development Environments, they are not ideal for executing >> production >> code. Run your file from the Terminal command prompt directly. > > I thought the code was not run inside the IDE but it was run by > Python > independently, that is, the IDE just provides an interface. Only partly true, the IDE wraps the interpreter so that it can catch errors and warnings and in some cases treat them differently to the way the ternminal would do it. Plus the IDE introduces a (small) overhead so you may not get accurate timings. But the biggest issues I find are that a lot of IDEs catch things like Ctrl-C interrupts and either ignore them or don;t report them accurately. Also some try to turn Pythons stack trace error reports into dialog boxes or worse, highlighted bars in the editor - losing a lot of detailed info about the bug in the process. Finally some IDEs intersperse their printed output with the interactive prompt window which makes it harder toi go bacvk and figure out what came from the program and what was test input by you! Also IDEs sometimes inherit spurious variable settings and imports that you have set during an interactive sssion. Then you get bizarre results which don't reflect the real behaviour of your code when run from a command prompt or fuile explorer (Finder in your case). > a) it is slower since I have to type $python filename.py (ok, this > takes very little time but clicking a button or typing a key > shortcut > to execute the code takes less time) You can use command history to recall the last command. Its very quick. > b) with the terminal I don't get the debugging benefits that an IDE > provides (I must say though that I still haven't really taken > advantage of the benefits that Eclipse provides since the code I'm > writing so far is pretty simple). Debug your code in the IDE to the point that it looks right. Then run it outside the IDE to make sure that it really is right! And don't try to do timing or volume load testing in the IDE - it will alter the results by a greater or lesser degree depending on how the IDE is written. And unless you know how the IDE is coded how do you know how much is the IDE and how much your code? IDEs are useful tools but thats all, development tools. After all you wouldn't really test your car's acceleration in a workshop test roller would you? You'd take it out on the road... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Nov 22 22:08:36 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 22 Nov 2010 21:08:36 +0000 (GMT) Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 Message-ID: <386909.78882.qm@web86705.mail.ird.yahoo.com> Forwarding to the list Please send list mail to tutor at python.org not tutor-owner... ----- Forwarded Message ---- > From: John Smith > To: tutor-owner at python.org > Sent: Monday, 22 November, 2010 19:29:37 > Subject: Installing Pyserial for Python27 on Win 7 > > My OS is Win 7. I have the 64-bit Python27 installed and it works well. > > I want to be able to do serial communications. I downloaded Pyserial, >unfortunately in 32 bit release only, and I cannot install it. When I attempt >the installation, it says "No Python installation found in the registry" and I >cannot continue. > > 1) Does a 64-bit release of Pyserial exist? > > 2) Will the 32-bit release of Pyserial work with my OS somehow? > > 3) If the answer is Yes to #2, how do I get past my problem? > > Thanks in advance for help. > > Cheers, > John > From emile at fenx.com Mon Nov 22 23:02:30 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 22 Nov 2010 14:02:30 -0800 Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 In-Reply-To: <386909.78882.qm@web86705.mail.ird.yahoo.com> References: <386909.78882.qm@web86705.mail.ird.yahoo.com> Message-ID: See http://sourceforge.net/tracker/index.php?func=detail&aid=2921957&group_id=46487&atid=446302 where it's explained that this bug won't get fixed, but that you can install from sources. Emile On 11/22/2010 1:08 PM ALAN GAULD said... > Forwarding to the list > Please send list mail to tutor at python.org not tutor-owner... > > ----- Forwarded Message ---- > >> From: John Smith >> To: tutor-owner at python.org >> Sent: Monday, 22 November, 2010 19:29:37 >> Subject: Installing Pyserial for Python27 on Win 7 >> >> My OS is Win 7. I have the 64-bit Python27 installed and it works well. >> >> I want to be able to do serial communications. I downloaded Pyserial, >> unfortunately in 32 bit release only, and I cannot install it. When I attempt >> the installation, it says "No Python installation found in the registry" and I >> cannot continue. >> >> 1) Does a 64-bit release of Pyserial exist? >> >> 2) Will the 32-bit release of Pyserial work with my OS somehow? >> >> 3) If the answer is Yes to #2, how do I get past my problem? >> >> Thanks in advance for help. >> >> Cheers, >> John >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Tue Nov 23 01:18:27 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 22 Nov 2010 16:18:27 -0800 Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 In-Reply-To: <4CEAF720.20304@verizon.net> References: <386909.78882.qm@web86705.mail.ird.yahoo.com> <4CEAF720.20304@verizon.net> Message-ID: <4CEB0853.1090302@fenx.com> On 11/22/2010 3:05 PM John Smith said... > Hi, Emile - > > Install from sources? What is that? see http://pyserial.sourceforge.net/pyserial.html#installation the From Source section. I'm not sure what else may be required but it should help get you started. Emile > I searched for that phrase but did not find anything I could > understand. My shortcoming, perhaps. > > Thanks for your reply. > > John > > On 11/22/2010 4:02 PM, Emile van Sebille wrote: >> See >> http://sourceforge.net/tracker/index.php?func=detail&aid=2921957&group_id=46487&atid=446302 >> >> where it's explained that this bug won't get fixed, but that you can >> install from sources. >> >> Emile >> >> >> On 11/22/2010 1:08 PM ALAN GAULD said... >>> Forwarding to the list >>> Please send list mail to tutor at python.org not tutor-owner... >>> >>> ----- Forwarded Message ---- >>> >>>> From: John Smith >>>> To: tutor-owner at python.org >>>> Sent: Monday, 22 November, 2010 19:29:37 >>>> Subject: Installing Pyserial for Python27 on Win 7 >>>> >>>> My OS is Win 7. I have the 64-bit Python27 installed and it works >>>> well. >>>> >>>> I want to be able to do serial communications. I downloaded Pyserial, >>>> unfortunately in 32 bit release only, and I cannot install it. When I >>>> attempt >>>> the installation, it says "No Python installation found in the >>>> registry" and I >>>> cannot continue. >>>> >>>> 1) Does a 64-bit release of Pyserial exist? >>>> >>>> 2) Will the 32-bit release of Pyserial work with my OS somehow? >>>> >>>> 3) If the answer is Yes to #2, how do I get past my problem? >>>> >>>> Thanks in advance for help. >>>> >>>> Cheers, >>>> John >>>> >>> _______________________________________________ >>> 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 jocjo.s at verizon.net Tue Nov 23 04:02:56 2010 From: jocjo.s at verizon.net (John Smith) Date: Mon, 22 Nov 2010 21:02:56 -0600 Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 In-Reply-To: <4CEB0853.1090302@fenx.com> References: <386909.78882.qm@web86705.mail.ird.yahoo.com> <4CEAF720.20304@verizon.net> <4CEB0853.1090302@fenx.com> Message-ID: <4CEB2EE0.6040502@verizon.net> So, let's see.... Serial communications does not come with Python so a separate package has to be installed. Okay, but the pyserial Windows installer will not work in Windows 7 and will not be fixed. So, a source install is required. I _assume_ the source is the one that is a tar.gz thingy. Since Windows will not handle the unpacking of that, I have to install a decompressor/unpacker to do it. Then I can finally get around to installing the serial package. Maybe. Unless I run into a similar problem because of Win 7 or because pyserial is 32-bit. I think it is better that I stop now before I install a bunch of extra applications that I need only to install one or two Python modules. I like Python itself. Very powerful. But I guess I'll look for some other language which provides the features I need without the hassle. Thanks again for your help. Cheers, John On 11/22/2010 6:18 PM, Emile van Sebille wrote: > On 11/22/2010 3:05 PM John Smith said... >> Hi, Emile - >> >> Install from sources? What is that? > > see http://pyserial.sourceforge.net/pyserial.html#installation the From > Source section. > > I'm not sure what else may be required but it should help get you started. > > Emile > > >> I searched for that phrase but did not find anything I could >> understand. My shortcoming, perhaps. >> >> Thanks for your reply. >> >> John >> >> On 11/22/2010 4:02 PM, Emile van Sebille wrote: >>> See >>> http://sourceforge.net/tracker/index.php?func=detail&aid=2921957&group_id=46487&atid=446302 >>> >>> where it's explained that this bug won't get fixed, but that you can >>> install from sources. >>> >>> Emile >>> >>> >>> On 11/22/2010 1:08 PM ALAN GAULD said... >>>> Forwarding to the list >>>> Please send list mail to tutor at python.org not tutor-owner... >>>> >>>> ----- Forwarded Message ---- >>>> >>>>> From: John Smith >>>>> To: tutor-owner at python.org >>>>> Sent: Monday, 22 November, 2010 19:29:37 >>>>> Subject: Installing Pyserial for Python27 on Win 7 >>>>> >>>>> My OS is Win 7. I have the 64-bit Python27 installed and it works >>>>> well. >>>>> >>>>> I want to be able to do serial communications. I downloaded Pyserial, >>>>> unfortunately in 32 bit release only, and I cannot install it. When I >>>>> attempt >>>>> the installation, it says "No Python installation found in the >>>>> registry" and I >>>>> cannot continue. >>>>> >>>>> 1) Does a 64-bit release of Pyserial exist? >>>>> >>>>> 2) Will the 32-bit release of Pyserial work with my OS somehow? >>>>> >>>>> 3) If the answer is Yes to #2, how do I get past my problem? >>>>> >>>>> Thanks in advance for help. >>>>> >>>>> Cheers, >>>>> John >>>>> >>>> _______________________________________________ >>>> 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 rdmoores at gmail.com Tue Nov 23 12:28:51 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 23 Nov 2010 03:28:51 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose Message-ID: I've always disliked using "if not n % 2" to test for even/odd ints because of its convoluted logic. But I ran some speed tests and found it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to 9.5% faster, depending on the integer tested - size and whether odd or even. See the speed testing script and results at . Dick Moores http://tutoree7.pastebin.com/iragLgDz From josep.m.fontana at gmail.com Tue Nov 23 13:55:44 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Tue, 23 Nov 2010 13:55:44 +0100 Subject: [Tutor] IDEs In-Reply-To: References: Message-ID: Great. Thanks Marc, Steven and Alan for the enlightening answers. I will certainly take your advice into account. I work in many different computers and while I do most of my coding (sounds as if I did a lot of coding, but I don't) on my desktop computer at home I wanted to start doing it on my laptop and on another old and way less powerful desktop computer at work. I think I'll keep Eclipse on my main computer (there's a learning curve, definitely, but I think it is a good time investment) but I'll use a setup like the one Steve (and most seasoned programmers I know) suggests for the other computers. One question for Steve (or for whoever wants to answer): you say you have a terminal with two tabs (neat, I wonder whether I can get these terminals in OS X) and when you need to do debugging you turn to your interactive python terminal and do; import filename # first time only reload(filename) # all subsequent times If I do with a "normal" python file, I get the error: "ImportError: No module named py" if I enter the file name with the py extension. If I just enter the file name without the extension, everything seems to work fine and I don't get any error message but then when I call a variable I get a message saying "'X' is not defined". Josep M. From ljmamoreira at gmail.com Tue Nov 23 14:16:46 2010 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Tue, 23 Nov 2010 13:16:46 +0000 Subject: [Tutor] variable numbers of for loops Message-ID: <201011231316.46810.ljmamoreira@gmail.com> Hi, This is a somewhat algorithmic question, not strictly pythonic. I was writing a program to generate all possible n-letter words with letters taken from an alphabet (I mean, if the alphabet is ['a','b'] the one-letter words are 'a' and 'b', the two letter words are 'aa', 'ab', 'ba', 'bb' and so on). I wrote a recursive function that does the job easy enough, but I read somewhere that for any recursive algorithm there is a sequential one that is equivalent, in the sense that the same output is produced for the same inputs. Now the easiest way to solve my n-letter problem sequentially is to, for each of the n letters that compose the word, cycle through all the possibilities allowed for in the alphabet. However, in this solution the value of n (the length of the words) is hardwired, you have to write different programs (with different numbers of for loops) for each value of n. I managed to work around that problem by writing the following function, that generates different programs, depending on the value of n,exec's it and returns the results: def allwrds(alphabet,n): ind = ' ' prog = "listOfWords=[]\n" for i in range(n): prog += i*ind + 'for l' + str(i) + ' in alphabet:\n' prog += n*ind + 'word = "".join([eval("l"+str(i)) for i in range(n)])\n' prog += n*ind + 'listOfWords.append(word)\n' #print prog #Uncomment to see the generated program exec(prog) return listOfWords This works fine (comments are welcome, of course) but I find this approach (to write programs that write programs that solve the problem) somehow twisted (to say the least). Is there a more straightforward way of solving my specific problem or, better yet, a general solution to the need of a variable number of for loops? Thanks Jose From andreengels at gmail.com Tue Nov 23 14:47:27 2010 From: andreengels at gmail.com (Andre Engels) Date: Tue, 23 Nov 2010 14:47:27 +0100 Subject: [Tutor] variable numbers of for loops In-Reply-To: <201011231316.46810.ljmamoreira@gmail.com> References: <201011231316.46810.ljmamoreira@gmail.com> Message-ID: On Tue, Nov 23, 2010 at 2:16 PM, Jose Amoreira wrote: > Is there a more straightforward way of solving my specific problem or, better > yet, a general solution to the need of a variable number of for loops? If you need a variable number of loops, put the loops themselves in a loop, which you go through the required number of times. In your case I would do: def allwrds(alphabet,n): result = [""] # for n=0, we have a single empty string for _ in range(n): result = [w+letter for letter in alphabet for w in result] return result Or, in case you are not comfortable with list comprehension (or want easy translation to a language without such a powerful tool): def allwrds(alphabet,n): result = [""] # for n=0, we have a single empty string for _ in range(n): tempwrds = [] for w in result: for letter in alphabet: tempwrds.append(w+letter) result = tempwrds return result -- Andr? Engels, andreengels at gmail.com From wprins at gmail.com Tue Nov 23 14:57:23 2010 From: wprins at gmail.com (Walter Prins) Date: Tue, 23 Nov 2010 13:57:23 +0000 Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 In-Reply-To: <4CEB2EE0.6040502@verizon.net> References: <386909.78882.qm@web86705.mail.ird.yahoo.com> <4CEAF720.20304@verizon.net> <4CEB0853.1090302@fenx.com> <4CEB2EE0.6040502@verizon.net> Message-ID: On 23 November 2010 03:02, John Smith wrote: > I _assume_ the source is the one that is a tar.gz thingy. Since Windows > will not handle the unpacking of that, I have to install a > decompressor/unpacker to do it. Then I can finally get around to installing > the serial package. Maybe. Unless I run into a similar problem because of > Win 7 or because pyserial is 32-bit. > > I think it is better that I stop now before I install a bunch of extra > applications that I need only to install one or two Python modules. > > I like Python itself. Very powerful. But I guess I'll look for some other > language which provides the features I need without the hassle. Thanks again > for your help. > Without wanting to be rude: Maybe you shouldn't *assume* anything about something you apparently know little about and jump to conclusions so quickly, and rather ask some pertinent questions. You know what they say about "assume", it makes an "ass" out of "u" an "me". Firstly, .tar.gz is more or less the standard archive format for Unix and Linux based systems (actually it's an archive that's then subsequently compressed but I digress.) It's hardly esoteric these days, and there's numerous archivers that will deal with this format for you on Windows. It's a 1 minute problem, literally, to deal with. My favourite on Windows is IZArc, here: http://www.izarc.org/ Frankly I don't understand why dealing with this is seen as a lot of hassle or why you're afraid of this cluttering up your system due to a simple (to you unknown new) file format problem, and why you assume that implies you'll have 32/64 bit problems as well. In any case for the record, Python source, especially cross-platform source, will often be distributed as .tar.gz and oftentimes its actually preferred to use the source if possible, there's no need to be worried about this or to fear it in any way. Furthermore, let me point out that you could even have dealt with this file with for Python itself , e.g: > import gzip > import StringIO > import tarfile > > tardata = gzip.open('c:/pyserial-2.5.tar.gz', 'rb').read() > tardataIO = StringIO.StringIO(tardata) > tf = tarfile.TarFile(fileobj=tardataIO) > tf.extractall('c:/temp') > That will uncompress and then extract the file using standard Python. All you then have to do is go and run "python setup.py install" from a command prompt in the extracted folder, to install it into your Python installation (which again is an action you'll get quite used to if you're used to using Python for a while and want to install from source, when you're not using even easier methods like "easy_setup" or "pip"...) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Tue Nov 23 15:01:40 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 23 Nov 2010 15:01:40 +0100 Subject: [Tutor] variable numbers of for loops In-Reply-To: <201011231316.46810.ljmamoreira@gmail.com> References: <201011231316.46810.ljmamoreira@gmail.com> Message-ID: <20101123150140.3f52aa95@jabbar> On Tue, 23 Nov 2010 13:16:46 +0000 Jose Amoreira wrote: > I read somewhere that for any recursive algorithm there is a > sequential one that is equivalent > [...] > Is there a more straightforward way of solving my specific problem > or, better yet, a general solution to the need of a variable number > of for loops? I am not 100% sure I got the terms of your problem and I am neither an official tutor of this list, so disregard my comment if it is irrelevant... ...yet, the way I normally understand the first sentence I quoted is that any recursive solution can be written iteratively, or in other words "flat" (i.e. having the same procedure called by the main program X number of times, rather than having the procedure calling itself, so effectively nesting itself X number of times). The code you wrote generates programs like: for l0 in alphabet: for l1 in alphabet: for l2 in alphabet: word = "".join([eval("l"+str(i)) for i in range(n)]) listOfWords.append(word) which are recursive in essence (although the recursion is hard-coded rather than dynamic). This is not bad (problems in the domain of combinatorics - like yours - get normally solved recursively) but I can't imagine what would the advantage of this code over dynamic recursion. As for a more straightforward way to solve your specific problem: I would suggest you take a look to the combinatoric generators in the itertools module (http://docs.python.org/library/itertools.html). HTH at least a bit! Mac. From josep.m.fontana at gmail.com Tue Nov 23 15:02:27 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Tue, 23 Nov 2010 15:02:27 +0100 Subject: [Tutor] IDEs In-Reply-To: <4CEA43B2.2030907@pearwood.info> References: <4CEA43B2.2030907@pearwood.info> Message-ID: Hi Steven, > Also, I'm a big believer in test-driven development. I must admit though I'm > not so pedantic to write the tests first, but for anything except > quick-and-dirty scripts, I make sure that *every* function in my program, > without exception, has a test to ensure that it works correctly. So I'll > often have a third tab open for running my test suite. I use a mix of > doctests and unit-tests. Here's an example from a project I'm working on at > the moment: Does anybody know of any good reference on testing? How do you develop tests for functions? I haven't found much information on this in the Python books I own. JM From steve at pearwood.info Tue Nov 23 15:12:03 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Nov 2010 01:12:03 +1100 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: Message-ID: <4CEBCBB3.40201@pearwood.info> Richard D. Moores wrote: > I've always disliked using "if not n % 2" to test for even/odd ints > because of its convoluted logic. I don't find it convoluted. It's not quite as straightforward as a hypothetical "if even(n)", but it's pretty straightforward. Perhaps you just need to get used it it. > But I ran some speed tests and found > it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to > 9.5% faster, depending on the integer tested - size and whether odd or > even. I suspect that the time difference you're seeing has nothing to do with it being even or odd, but merely random fluctuations.But regardless, this truly is a micro-optimization. Given the results you show, you potentially save all of (approx) 0.0000004 second per test. See the speed testing script and results at > . You missed what I predict will be even faster: def x3(n): return not n % 2 -- Steven From wangoloj at yahoo.com Tue Nov 23 16:30:05 2010 From: wangoloj at yahoo.com (Wangolo Joel) Date: Tue, 23 Nov 2010 15:30:05 +0000 (GMT) Subject: [Tutor] Tutor Digest, Vol 81, Issue 78 In-Reply-To: Message-ID: <83542.90313.qm@web29718.mail.ird.yahoo.com> ?I NO LONGER WANT YOUR TUTORIAL -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Tue Nov 23 16:40:07 2010 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 23 Nov 2010 16:40:07 +0100 Subject: [Tutor] IDEs In-Reply-To: References: <4CEA43B2.2030907@pearwood.info> Message-ID: <201011231640.40670.eike.welk@gmx.net> On Tuesday 23.11.2010 15:02:27 Josep M. Fontana wrote: > Does anybody know of any good reference on testing? How do you develop > tests for functions? I haven't found much information on this in the > Python books I own. The basic idea is to call your function with known inputs, and test if it has the desired output. For practical application you use a test framework, and write the tests in the format that the framework recognizes. The framework will then run the tests, print eventual error messages, and a summary of the test run. In "Test Driven Development" you write the tests first and the program code second. This is IMHO very useful as you do at least some design (API design). For more information google for: "Python test driven development" Here are some websites that seem promising: http://en.wikipedia.org/wiki/Test-driven_development http://www.slideshare.net/Siddhi/test-driven-development-with-python I use the "py.test" framework but there are also "nose", the built in "unittest" and the built in "Doctest". (Pydev/Eclipse can somehow collaborate with "unittest" I think.) http://codespeak.net/py/dist/test/ http://somethingaboutorange.com/mrl/projects/nose/0.11.2/index.html http://docs.python.org/library/unittest.html http://docs.python.org/library/doctest.html Eike. From quasipedia at gmail.com Tue Nov 23 16:43:35 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 23 Nov 2010 16:43:35 +0100 Subject: [Tutor] IDEs In-Reply-To: References: <4CEA43B2.2030907@pearwood.info> Message-ID: <20101123164335.60374910@jabbar> On Tue, 23 Nov 2010 15:02:27 +0100 "Josep M. Fontana" wrote: > Does anybody know of any good reference on testing? How do you develop > tests for functions? I haven't found much information on this in the > Python books I own. When I first learnt python I found the "Dive into Python" section of the book rather well done: http://diveintopython.org/unit_testing/index.html If you have the patience to look in the ML archives you will also find some good thread about unit testing there. HTH, Mac. From alan.gauld at btinternet.com Tue Nov 23 17:22:53 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Nov 2010 16:22:53 -0000 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed:aesthetics lose References: Message-ID: "Richard D. Moores" wrote > it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to > 9.5% faster, depending on the integer tested - size and whether odd > or > even. See the speed testing script and results at > . Did you try: if n % 2: pass else: do it here? ie inverting the logic and omitting the equality test. No idea if it makes a difference or not. Alan G. From emile at fenx.com Tue Nov 23 17:27:38 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Nov 2010 08:27:38 -0800 Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 In-Reply-To: References: <386909.78882.qm@web86705.mail.ird.yahoo.com> <4CEAF720.20304@verizon.net> <4CEB0853.1090302@fenx.com> <4CEB2EE0.6040502@verizon.net> Message-ID: On 11/23/2010 5:57 AM Walter Prins said... > On 23 November 2010 03:02, John Smith wrote: >> I like Python itself. Very powerful. But I guess I'll look for some other >> language which provides the features I need without the hassle. Thanks again >> for your help. >> > > In any case for the record, Python source, especially cross-platform source, > will often be distributed as .tar.gz and oftentimes its actually preferred > to use the source if possible, there's no need to be worried about this or > to fear it in any way. > To add to what Walter said, in general it's probably a good thing to learn to be somewhat comfortable installing from sources, whether for python or any other language or OS. You're likely to run in to version conflicts sooner or later and often the resolution involves building from source or installing or reverting to specific versions of packages. Speaking of which, you can also install the version of python supported by the maintainers of PYSERIAL so that you can use the installer. In any case, serial communications is rarely simple -- I still have books on my shelf from the early 80s detailing the hundreds of RS232 'standards' that were in common use then. Emile From emile at fenx.com Tue Nov 23 17:33:33 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Nov 2010 08:33:33 -0800 Subject: [Tutor] Tutor Digest, Vol 81, Issue 78 In-Reply-To: <83542.90313.qm@web29718.mail.ird.yahoo.com> References: <83542.90313.qm@web29718.mail.ird.yahoo.com> Message-ID: On 11/23/2010 7:30 AM Wangolo Joel said... > > > I NO LONGER WANT YOUR TUTORIAL > > you can unsubscribe at 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 rdmoores at gmail.com Tue Nov 23 17:33:47 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 23 Nov 2010 08:33:47 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed:aesthetics lose In-Reply-To: References: Message-ID: On Tue, Nov 23, 2010 at 08:22, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to >> 9.5% faster, depending on the integer tested - size and whether odd or >> even. See the speed testing script and results at >> . > > Did you try: > > if n % 2: pass > else: ?do it here? > > ie inverting the logic and omitting the equality test. Alan, since I'm doing comparison's, why do you suggest omitting the equality test? Also, what do you mean by "do it here?" Dick From alan.gauld at btinternet.com Tue Nov 23 17:35:39 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 23 Nov 2010 16:35:39 +0000 (GMT) Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed:aesthetics lose In-Reply-To: References: Message-ID: <656000.62442.qm@web86703.mail.ird.yahoo.com> > > Did you try: > > > > if n % 2: pass > > else: do it here? > > > > ie inverting the logic and omitting the equality test. > > Alan, since I'm doing comparison's, why do you suggest omitting the > equality test? Because the equality test with 0 might be slower than the implicit test of trueness. > Also, what do you mean by "do it here?" I mean whatever you wanted to do inside the n%2==0 block. Alan G. From alan.gauld at btinternet.com Tue Nov 23 17:34:12 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 23 Nov 2010 16:34:12 +0000 (GMT) Subject: [Tutor] Lambda function, was: Simple counter to determine frequencies of words in adocument In-Reply-To: References: <41083.43755.qm@web86706.mail.ird.yahoo.com> Message-ID: <509675.78501.qm@web86703.mail.ird.yahoo.com> > OK, all of this is perfectly clear but what is still difficult for me > to understand is the following. If you remember the line of code in > question was: > > >sorted(word_table.items(), key=lambda item: item[1], reverse=True) > > This is supposed to return a list of tuples such as > > [('the', 3), ('in', 1), ('fig', 1)] > > If this list of tuples is what is in the context, why is item[1] > referring to the second position in any tuple and not to the second > tuple in the list of tuples? I mean, if I do: Because sorted() passes each item in the sequence being sorted to the function defined in key, like this: def sorted(seq, key): result = [] for item in seq: sortVal = key(item) insertItemInResult(item,sortVal,result) return result Notice that it uses key as a function inside sorted. And lambda creates a function so sorted applies the lambda to each item in turn to retrieve the sort key. > I guess I'm having trouble figuring out what the scope of the variable > 'item' is in this case. Why is tuple[1] in this line of code > interpreted to mean "the second position in any of the tuples" and not > "the second tuple in the available list of tuples". Because item in the lambda is a local variable within the lambda. When the lambda is used inside sorted the value of item is a single tuple of your sequence. > Perhaps this is a very stupid question but it is hard for me > to wrap my mind around this. It is a biot odd when you aren't used to thinking of function 'objects' that can be passed around like data and then executed. But it is a very powerful technique once you get your head wrapped around it. [ FWIW Languages like C do the same thing with the concept of a pointer to a function. ] HTH, Alan G. From emile at fenx.com Tue Nov 23 17:49:25 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Nov 2010 08:49:25 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed:aesthetics lose In-Reply-To: References: Message-ID: On 11/23/2010 8:22 AM Alan Gauld said... > > "Richard D. Moores" wrote > >> it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to >> 9.5% faster, depending on the integer tested - size and whether odd or >> even. See the speed testing script and results at >> . > > Did you try: > > if n % 2: pass > else: do it here? > or def x2(n): return not (n % 2) Emile From rdmoores at gmail.com Tue Nov 23 18:50:59 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 23 Nov 2010 09:50:59 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: <4CEBCBB3.40201@pearwood.info> References: <4CEBCBB3.40201@pearwood.info> Message-ID: On Tue, Nov 23, 2010 at 06:12, Steven D'Aprano wrote: > Richard D. Moores wrote: >> >> I've always disliked using "if not n % 2" ?to test for even/odd ints >> because of its convoluted logic. > > I don't find it convoluted. It's not quite as straightforward as a > hypothetical "if even(n)", but it's pretty straightforward. Perhaps you just > need to get used it it. OK, somewhat convoluted. And after messing around with it for these tests, I'm used to it now. >> But I ran some speed tests and found >> >> it was the way to go over "if n % 2 == 0". By my tests, it's 4.3% to >> 9.5% faster, depending on the integer tested - size and whether odd or >> even. > > I suspect that the time difference you're seeing has nothing to do with it > being even or odd, I only threw in odd vs even out of curiosity. But I rand x1 against x2 against your x3 for the same ints as before: . I show the original x1 vs. x2 results, followed by 3 sets that include x3. I think you can see that odd ints take longer in almost all cases than evens. >but merely random fluctuations.But regardless, this truly > is a micro-optimization. Given the results you show, you potentially save > all of (approx) 0.0000004 second per test. Sure, but I've satisfied my curiosity. > ?See the speed testing script and results at >> >> . > > > You missed what I predict will be even faster: > > def x3(n): > ? ?return not n % 2 Yes, generally faster, but marginally. Thanks for the idea. Dick From cfuller084 at thinkingplanet.net Tue Nov 23 18:49:42 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Tue, 23 Nov 2010 11:49:42 -0600 Subject: [Tutor] variable numbers of for loops (also iteration/recursion) In-Reply-To: <201011231316.46810.ljmamoreira@gmail.com> References: <201011231316.46810.ljmamoreira@gmail.com> Message-ID: <201011231149.50467.cfuller084@thinkingplanet.net> You can always substitute Iteration for Recursion by making the stack an explicit part of your code. As an example, imagine you are traversing this directory tree: birds birds/owls birds/owls/snowy birds/owls/barn birds/owls/great-horned birds/eagles birds/eagles/golden birds/eagles/bald birds/eagles/osprey Where the third-level items are files, rather than more directories. In a recursive approach, a function is defined that does the recursion. This is a feature of recursion. You can't slip it inline with your code (unless your language supports inline functions and the right sort of scoping rules, but you probably don't want to try that here). The function takes a directory, iterates through the contents, calling itself again for every subdirectory. Your application code calls the function with the argument of "birds". The function then calls itself twice, once with "owls" and again with "eagles". The contents of these are files, and not directories, so recursion ends. In an iterative approach, there is a stack and a loop. The loop stops when the stack is empty. The loop pops the most recently pushed item from the stack, and then pushes onto the stack any subdirectories. We start with the directory "birds" on the stack. The loop pops "birds" and then pushes "owls" and "eagles". It loops twice more to process these, and then stops. Your program is really more iterative than recursive. I couldn't manage a recursive expression of the problem. You can always make a iterative version of a recursive algorithm, but not necessarily the other way. This makes sense when you inspect the problem. Your solution is abstractly equivalent to an n- dimensional "cube" with side length equal to the length of the alphabet, not anything that looks like a tree. One thing I noticed about your generated code is that it can be collapsed into a list comprehension: >>> allwrds('ab',2) listOfWords=[] for l0 in alphabet: for l1 in alphabet: word = "".join([eval("l"+str(i)) for i in range(n)]) listOfWords.append(word) ['aa', 'ab', 'ba', 'bb'] is equivalent to >>> alphabet='ab' >>> [l0+l1 for l0 in alphabet for l1 in alphabet] ['aa', 'ab', 'ba', 'bb'] Now, the result is a 1D list of length len(alphabet)**n. Why not iterate over that space, and fill in the blanks? Think of your problem modeled as a n- dimensional hypercube. The value at any element is equal to the concatenation of the n indices of that element's location. Some 2D examples: allwrds('ab',2): a b a aa ab b ba bb allwrds('abc',2): a b c a aa ab ac b ba bb bc c ca cb cc Mapping from n dimensions to 1D isn't hard if you know the size of each dimension. In this case, they're all equal. I'll use a 3D example to make it more clear: i = 0 j=0 1 2 k 0 0 1 2 1 3 4 5 2 6 7 8 i = 1 j=0 1 2 k 0 9 10 11 1 12 13 14 2 15 16 17 i = 2 j=0 1 2 k 0 18 19 20 1 21 22 23 2 24 25 26 Find the i,j,k for 1D index 17. Start with the highest order index (i). Divide by the product of the sizes of the lower dimensions, which is the length of the alphabet squared. This alphabet is length 3, so we divide by 9. We get 1 rmdr 8. i=1. Now take the remainder and repeat. 8 divided by 3 is 2 rmdr 2. j=2. You could take it another step if using n-cubes and powers of the dimension size, since 3**0 equals one, and the next answer is still 2, but this fails when the dimensions aren't all equal. k=2. Got that? Now these i,j,k values are just indices into the alphabet! Just get the letter at that indexd and join them up. Here's the code: def allwrds(alphabet, n): listOfWords=[] for i in range(len(alphabet)**n): word = '' q = i for j in range(n-1): q, r = divmod(q, len(alphabet)) word += alphabet[q] q = r word += alphabet[q] listOfWords.append(word) return listOfWords Cheers From amonroe at columbus.rr.com Tue Nov 23 19:29:45 2010 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 23 Nov 2010 13:29:45 -0500 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: Message-ID: <34358288121.20101123132945@columbus.rr.com> > I've always disliked using "if not n % 2" to test for even/odd ints > because of its convoluted logic. But I ran some speed tests and found > it was the way to go over "if n % 2 == 0". Did you try bitwise-and with 1? Alan From rdmoores at gmail.com Tue Nov 23 20:56:03 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 23 Nov 2010 11:56:03 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: <34358288121.20101123132945@columbus.rr.com> References: <34358288121.20101123132945@columbus.rr.com> Message-ID: On Tue, Nov 23, 2010 at 10:29, R. Alan Monroe wrote: >> I've always disliked using "if not n % 2" ?to test for even/odd ints >> because of its convoluted logic. But I ran some speed tests and found >> it was the way to go over "if n % 2 == 0". > > Did you try bitwise-and with 1? What's that? Dick From waynejwerner at gmail.com Tue Nov 23 21:52:27 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 23 Nov 2010 14:52:27 -0600 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: <34358288121.20101123132945@columbus.rr.com> Message-ID: On Tue, Nov 23, 2010 at 1:56 PM, Richard D. Moores wrote: > On Tue, Nov 23, 2010 at 10:29, R. Alan Monroe > wrote: > >> I've always disliked using "if not n % 2" to test for even/odd ints > >> because of its convoluted logic. But I ran some speed tests and found > >> it was the way to go over "if n % 2 == 0". > > > > Did you try bitwise-and with 1? > > What's that? > >>> 2 & 1 0 >>> 3 & 1 1 >>> 10 & 1 0 >>> 11 & 1 0 For an example (base 2): 1 0 1 1 & 0 0 0 1 --------------------- 0 0 0 1 HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 23 21:53:40 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 24 Nov 2010 07:53:40 +1100 Subject: [Tutor] Unsubscribing from mailing lists In-Reply-To: <83542.90313.qm@web29718.mail.ird.yahoo.com> References: <83542.90313.qm@web29718.mail.ird.yahoo.com> Message-ID: <4CEC29D4.8070203@pearwood.info> Wangolo Joel wrote: > > I NO LONGER WANT YOUR TUTORIAL There's no need to SHOUT. Writing in all-caps is rude. If you don't want these emails, unsubscribe yourself. Just follow the instructions given in every single email: > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor If you have tried to unsubscribe, and failed, then it is appropriate to *politely* ask for help by writing to the list. Until then, you subscribed yourself, you can unsubscribe yourself. -- Steven From ljessen200 at hotmail.com Tue Nov 23 19:56:11 2010 From: ljessen200 at hotmail.com (Laura Jessen) Date: Tue, 23 Nov 2010 11:56:11 -0700 Subject: [Tutor] python script Message-ID: How would i write a simple python script to issue a scsi inquiry to a drive? Laura J. Jessen -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Tue Nov 23 22:26:24 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 23 Nov 2010 13:26:24 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: <34358288121.20101123132945@columbus.rr.com> Message-ID: On Tue, Nov 23, 2010 at 12:52, Wayne Werner wrote: > On Tue, Nov 23, 2010 at 1:56 PM, Richard D. Moores > wrote: >> >> On Tue, Nov 23, 2010 at 10:29, R. Alan Monroe >> wrote: >> >> I've always disliked using "if not n % 2" ?to test for even/odd ints >> >> because of its convoluted logic. But I ran some speed tests and found >> >> it was the way to go over "if n % 2 == 0". >> > >> > Did you try bitwise-and with 1? >> >> What's that? > >>>> 2 & 1 > 0 >>>> 3 & 1 > 1 >>>> 10 & 1 > 0 >>>> 11 & 1 > 0 > For an example (base 2): > ?? ? ? 1 0 1 1 > ?? ?& 0 0 0 1 > --------------------- > ?? ? ? 0 0 0 1 So what's the connection with the tests I've run? Dick From emile at fenx.com Tue Nov 23 23:33:50 2010 From: emile at fenx.com (Emile van Sebille) Date: Tue, 23 Nov 2010 14:33:50 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: <34358288121.20101123132945@columbus.rr.com> Message-ID: On 11/23/2010 1:26 PM Richard D. Moores said... > So what's the connection with the tests I've run? It's an even/odd test. [ii&1 for ii in range(1,1000,2)] [ii&1 for ii in range(0,1000,2)] Emile From hugo.yoshi at gmail.com Wed Nov 24 00:29:58 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 24 Nov 2010 00:29:58 +0100 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: <34358288121.20101123132945@columbus.rr.com> Message-ID: On Tue, Nov 23, 2010 at 9:52 PM, Wayne Werner wrote: >> > >> > Did you try bitwise-and with 1? >> >> What's that? > >>>> 2 & 1 > 0 >>>> 3 & 1 > 1 >>>> 10 & 1 > 0 >>>> 11 & 1 > 0 That last one should be 1, I'd say. From alan.gauld at btinternet.com Wed Nov 24 02:15:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Nov 2010 01:15:48 -0000 Subject: [Tutor] IDEs References: <4CEA43B2.2030907@pearwood.info> Message-ID: "Josep M. Fontana" wrote >> Also, I'm a big believer in test-driven development. I must admit >> though I'm > Does anybody know of any good reference on testing? How do you > develop > tests for functions? The basic idea in testing is to try to break your code. Try to think of every kind of evil input that could possibly come along and see if your code survives. In amongst all of that you should have a some valid values too, and know what to expect as out put. But if you write a function like square(x) you should test it with inputs like a large negative and large positive value, zero, complex numbers, floats(both huge and small), sequences(vectors), and expect all of these to produce meaningful results. You should also check that it handles input like strings, booleans, classes and objects (both with and without __mul__ defined), and anything else you can think of. Test Driven Development tends to focus on the more normal inputs in my experience, but done properly your test code will usually be bigger than your production code. In a recent project that we completed we had 600k lines of production code and over a million lines of test code. And we still wound up with over 50 reported bugs during Beta test... But that was much better than the 2000 bugs on an earlier project :-) But testing is hard. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Nov 24 02:22:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Nov 2010 01:22:48 -0000 Subject: [Tutor] variable numbers of for loops References: <201011231316.46810.ljmamoreira@gmail.com> <20101123150140.3f52aa95@jabbar> Message-ID: "Mac Ryan" wrote > I am not 100% sure I got the terms of your problem and I am neither > an > official tutor of this list, so disregard my comment if it is > irrelevant... If you are a member of the list and contribute you are an official tutor. There are no high priests here :-) Alan G. From alan.gauld at btinternet.com Wed Nov 24 02:29:39 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Nov 2010 01:29:39 -0000 Subject: [Tutor] python script References: Message-ID: "Laura Jessen" wrote > How would i write a simple python script to issue a scsi inquiry to > a drive? Depending on what you want to do and how you define "simple" it may not be possible. If its just to read data from a scsi device then once mounted it should be accesible like any other device. If you want to access the SCSI controller then things get more difficult. There appear to be a few modules available, some of them from SCSI vendors. But most look quite old and none looked "simple" to me. But it probably depends on how well you understand the SCSI interface standards. A Google search for python scsi will throw up a lot of hits... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ljmamoreira at gmail.com Wed Nov 24 03:07:57 2010 From: ljmamoreira at gmail.com (Jose Amoreira) Date: Wed, 24 Nov 2010 02:07:57 +0000 Subject: [Tutor] variable numbers of for loops In-Reply-To: <20101123150140.3f52aa95@jabbar> References: <201011231316.46810.ljmamoreira@gmail.com> <20101123150140.3f52aa95@jabbar> Message-ID: <201011240207.57993.ljmamoreira@gmail.com> On Tuesday, November 23, 2010 02:01:40 pm Mac Ryan wrote: > The code you wrote generates programs like: > > for l0 in alphabet: > for l1 in alphabet: > for l2 in alphabet: > word = "".join([eval("l"+str(i)) for i in range(n)]) > listOfWords.append(word) > > which are recursive in essence (although the recursion is hard-coded > rather than dynamic). This is not bad (problems in the domain of > combinatorics - like yours - get normally solved recursively) but I > can't imagine what would the advantage of this code over dynamic > recursion. I meant recursion in the sense of a function invoking itself (I guess it is what you call dynamic recursion). I also can't imagine any advantages of this code, I just thought it'd be a fun thing to try. > > As for a more straightforward way to solve your specific problem: I > would suggest you take a look to the combinatoric generators in the > itertools module (http://docs.python.org/library/itertools.html). > Thanks for this link, I didn't know about itertools. So long, Jose From robert.sjoblom at gmail.com Wed Nov 24 03:22:35 2010 From: robert.sjoblom at gmail.com (=?ISO-8859-1?Q?Robert_Sj=F6blom?=) Date: Wed, 24 Nov 2010 03:22:35 +0100 Subject: [Tutor] Help regarding lists, dictionaries and tuples (bob gailer) Message-ID: On Mon, Nov 22, 2010 at 10:27 AM, wrote: > Send Tutor mailing list submissions to > ? ? ? ?tutor at python.org > [snip] >> Ok, I'm clearly thinking in circles here. I used the interpreter to >> figure out that both are fine but the first example has integers, >> whereas the second has strings. Good to know. What I'm wondering then, >> instead, is whether there's a good way to sum up the value of integral >> data in a dictionary? > > Why would you want to sum them? You start with 30 points in the pool, > then allocate them to the attributes. The sum will still be 30. > Bob Gailer Because the user should be able to spend 30 points, or remove points from an attribute and get them back in the pool. Like so: attributes { "Strength" : 0, "Health" : 0, "Wisdom" : 0, "Dexterity" : 0) points = 30 - sum(attributes.values()) Or is there a better way to achieve the same result? best regards, Robert S. From amonroe at columbus.rr.com Wed Nov 24 05:09:21 2010 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue, 23 Nov 2010 23:09:21 -0500 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: References: <34358288121.20101123132945@columbus.rr.com> Message-ID: <113393063715.20101123230921@columbus.rr.com> >>> >> I've always disliked using "if not n % 2" ?to test for even/odd ints >>> >> because of its convoluted logic. But I ran some speed tests and found >>> >> it was the way to go over "if n % 2 == 0". >>> > Did you try bitwise-and with 1? >>> What's that? >>>>> 2 & 1 >> 0 >>>>> 3 & 1 >> 1 > So what's the connection with the tests I've run? I'm wagering it will be faster than a modulo operation. Let us know how it turns out :) Alan From quasipedia at gmail.com Wed Nov 24 07:38:58 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Wed, 24 Nov 2010 07:38:58 +0100 Subject: [Tutor] IDEs In-Reply-To: References: <4CEA43B2.2030907@pearwood.info> Message-ID: <20101124073858.32476fd2@jabbar> On Wed, 24 Nov 2010 01:15:48 -0000 "Alan Gauld" wrote: > In a recent project that we > completed we had 600k lines of production code and over a > million lines of test code. > > And we still wound up with over 50 reported bugs during Beta test... > But that was much better than the 2000 bugs on an earlier project :-) > But testing is hard. Somewhere I read a quote that I liked a lot because IMO it perfectly summarise the idea of test-driven development. Here it is: "Every bug is a test not yet written". Mac. From alan.gauld at btinternet.com Wed Nov 24 10:08:34 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Nov 2010 09:08:34 -0000 Subject: [Tutor] Help regarding lists, dictionaries and tuples (bob gailer) References: Message-ID: "Robert Sj?blom" wrote >> Why would you want to sum them? You start with 30 points in the >> pool, >> then allocate them to the attributes. The sum will still be 30. > >Because the user should be able to spend 30 points, or remove points > from an attribute and get them back in the pool. Like so: > > attributes { "Strength" : 0, "Health" : 0, "Wisdom" : 0, "Dexterity" > : 0) > points = 30 - sum(attributes.values()) > > Or is there a better way to achieve the same result? If you write a couple of functions to add/remove points then they can ensure that the total is correct without the need to sum the values. attributes { "Strength" : 0, "Health" : 0, "Wisdom" : 0, "Dexterity" : 0) points = 30 - sum(attributes.values()) def addPoints(attribute, number): attributes[attribute] += number points -= number return points def removePoints(attribute, number): return addPoints(attribute, -number) Now you can add and remove the points and the function will ensure there are only ever 30 points in total use. You would really need checks to ensure the attribute values and points never went negative of course... but you need that anyway. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Wed Nov 24 10:32:08 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 24 Nov 2010 01:32:08 -0800 Subject: [Tutor] "if n % 2 == 0" vs. "if not n % 2" compared for speed: aesthetics lose In-Reply-To: <113393063715.20101123230921@columbus.rr.com> References: <34358288121.20101123132945@columbus.rr.com> <113393063715.20101123230921@columbus.rr.com> Message-ID: On Tue, Nov 23, 2010 at 20:09, R. Alan Monroe wrote: > >>>> >> I've always disliked using "if not n % 2" ?to test for even/odd ints >>>> >> because of its convoluted logic. But I ran some speed tests and found >>>> >> it was the way to go over "if n % 2 == 0". > >>>> > Did you try bitwise-and with 1? > >>>> What's that? > >>>>>> 2 & 1 >>> 0 >>>>>> 3 & 1 >>> 1 > >> So what's the connection with the tests I've run? > > I'm wagering it will be faster than a modulo operation. Let us know > how it turns out :) You'd win. See My thanks to Emile for the list comprehension suggestion. Dick From josep.m.fontana at gmail.com Wed Nov 24 13:02:05 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Wed, 24 Nov 2010 13:02:05 +0100 Subject: [Tutor] IDEs In-Reply-To: <201011231640.40670.eike.welk@gmx.net> References: <4CEA43B2.2030907@pearwood.info> <201011231640.40670.eike.welk@gmx.net> Message-ID: Great. Thanks Eike and Alan. Josep M. From josep.m.fontana at gmail.com Wed Nov 24 13:32:44 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Wed, 24 Nov 2010 13:32:44 +0100 Subject: [Tutor] Working with interactive Python shell Message-ID: Hi, When a thread gets too long and new subtopics appear it gets pretty hard to keep track of what has been said by whom and what has been answered. Anyway, in one of the threads I started, Steven d'Aprano gave me a very nice response telling me what his preferred working environment was. This prompted the following question from me which was not answered due to the fact that was one of the many subtopics that emerged from the original question. I'm still interested in finding out about this in case anybody can give me an answer. I reproduce my question to Steve: ------- One question for Steve (or for whoever wants to answer): you say you have a terminal with two tabs (neat, I wonder whether I can get tabs as well for my terminal in OS X) and when you need to do debugging you turn to your interactive python terminal and do; import filename # first time only reload(filename) # all subsequent times If I do this with a "normal" python file (filename.py), I get the error: "ImportError: No module named py" This is if I enter the file name with the .py extension. If I just enter the file name without the extension, everything seems to work fine and I don't get any error message but then when I call a variable I get a message saying "'X' is not defined". -------------- I'm wondering whether I'm doing something wrong or whether I didn't properly understand what Steve was saying about working with the interactive Python shell. If I understood correctly, one can import a Python script into the interactive shell (not just modules) and then test different things from the prompt. I've tried to import various files following Steve's instructions but I get the errors I describe above. Josep M. From evert.rol at gmail.com Wed Nov 24 14:00:51 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 24 Nov 2010 14:00:51 +0100 Subject: [Tutor] Working with interactive Python shell In-Reply-To: References: Message-ID: > > ------- > One question for Steve (or for whoever wants to answer): you say you > have a terminal with two tabs (neat, I wonder whether I can get tabs > as well for my terminal in OS X) In Terminal.app, just type command-T and you get a new tab. Switch with the mouse or command-shift-[ & command-shift-] But sometimes, two separate terminals can be more convenient, so you can see both at the same time. > and when you need to do debugging you > turn to your interactive python terminal and do; > > import filename # first time only > reload(filename) # all subsequent times > > If I do this with a "normal" python file (filename.py), I get the error: > > "ImportError: No module named py" You're not really showing what exactly you type. That's often more clearer than describing what you do, although in this case we can get a pretty good picture anyway. > This is if I enter the file name with the .py extension. Perhaps try and read through the module section of the standard Python tutorial: http://docs.python.org/tutorial/modules.html The .py extension just signifies the file is a Python file, but the actual module name comes before the extension. The dot in module names is to divide modules up into submodules, or package things (further down in the Python tutorial on modules). > If I just enter the > file name without the extension, everything seems to work fine and I > don't get any error message but then when I call a variable I get a > message saying "'X' is not defined". How do you 'call the variable'? Btw, you don't really call a variable: access would probably be a more accurate term imo. You would call a function though (and that function would then be executed). But if you call a variable that is defined inside the module, you'll need to prepend the module name, like: >>> import mymodule >>> mymodule.X This is actually a form of namespacing: X is not defined in your global environment, just in mymodule. And again, see the examples in the tutorial. > -------------- > > I'm wondering whether I'm doing something wrong or whether I didn't > properly understand what Steve was saying about working with the > interactive Python shell. If I understood correctly, one can import a > Python script into the interactive shell (not just modules) and then > test different things from the prompt. Yes, correct. > I've tried to import various > files following Steve's instructions but I get the errors I describe > above. Ok, I don't have Steve's instructions handy (they've been stripped of this thread now), but I assume that if you apply the above, you should get a bit further. But without actually showing us what you've typed and the errors, we can't give you concrete advice (copy-paste is often a very good idea). Btw, should you want to delve further into using the interactive prompt, there are various interactive prompts that provide more conveniences than the standard Python prompt. IPython is my favourite, but before you do that, try and use the default prompt. Good luck, Evert From steve at pearwood.info Wed Nov 24 14:06:00 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Nov 2010 00:06:00 +1100 Subject: [Tutor] IDEs In-Reply-To: References: <4CEA43B2.2030907@pearwood.info> Message-ID: <4CED0DB8.4090606@pearwood.info> Alan Gauld wrote: > The basic idea in testing is to try to break your code. Try to think > of every kind of evil input that could possibly come along and see > if your code survives. In amongst all of that you should have a > some valid values too, and know what to expect as out put. Testing is more than just trying to break code of course. I'm reminded of a quote: "I find it amusing when novice programmers believe their main job is preventing programs from crashing. ... More experienced programmers realize that correct code is great, code that crashes could use improvement, but incorrect code that doesn't crash is a horrible nightmare." -- Chris Smith Testing is an attempt to ensure that code is *correct* -- that it does what it is supposed to do. There are a number of different types of tests, with different purposes. Unit tests are for testing that code behaves as expected. If you give the function this input, this will be its result. (The result might be to return a value, or it might be to raise an exception.) If you have a function that's supposed to add two numbers, it's important to be sure that it actually, ya know, *adds two numbers*, and not something else. ("It *almost* adds them, it's just that sometimes the answer is off by one or two...") Doctests are examples that you put into the documentation (usually into docstrings of functions and methods). Their primary purpose is to be examples for the reader to read, but the secondary aspect is that you can run the examples and be sure that they actually work as they are supposed to work. Regression tests are to prevent bugs from re-occurring. For example, suppose you have a function spam() and you discover it fails for one particular input, "aardvark". The first thing you should do, before even fixing the bug, is write a test: assert spam("aardvark") == "expected result" This test will fail, because there's a bug in spam(). Now go ahead and fix the bug, and the test will then pass. If your code ever has a *regression* that returns the bug in spam(), the test will fail again and you will immediately notice. Regression tests are to prevent fixed bugs from returning. User Acceptance Tests are mostly relevant when you're building software for a client. Both parties need a way to know when the software is "done". Of course software is never done, but if you're charging $10000 for a software project, you need to have way of saying "This is where we stop, if you want us to continue, it will cost you more". UATs give both parties an objective way of telling that the promised functionality is there (e.g. "if the user clicks the Stop button, processing must stop within one second") and identifying bugs and/or areas that weren't specified in enough detail. Of course, all of these are fuzzy categories -- there's no hard line between them. > Test Driven Development tends to focus on the more normal inputs > in my experience, but done properly your test code will usually > be bigger than your production code. In a recent project that we > completed we had 600k lines of production code and over a > million lines of test code. I can well believe that. I've had a look at a couple of my projects (*much* smaller than 600 KLOC!) and I'm averaging about 800 lines in the test suite per 1000 lines in the project. That's an over-estimate: the 1000 lines includes doc tests, so should be counted towards the tests. Taking that into account, I get (very roughly) 1:1 ratio of test code to production code. > And we still wound up with over 50 reported bugs during Beta test... > But that was much better than the 2000 bugs on an earlier project :-) > But testing is hard. Maybe so, but nothing beats running your test suite and seeing everything pass! -- Steven From steve at pearwood.info Wed Nov 24 14:16:27 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 25 Nov 2010 00:16:27 +1100 Subject: [Tutor] Working with interactive Python shell In-Reply-To: References: Message-ID: <4CED102B.9000504@pearwood.info> Josep M. Fontana wrote: > One question for Steve (or for whoever wants to answer): you say you > have a terminal with two tabs (neat, I wonder whether I can get tabs > as well for my terminal in OS X) and when you need to do debugging you > turn to your interactive python terminal and do; > > import filename # first time only > reload(filename) # all subsequent times > > If I do this with a "normal" python file (filename.py), I get the error: > > "ImportError: No module named py" You're probably writing: import filename.py instead of just: import filename When you import a module, it doesn't necessarily come from a .py file. It could come from a pre-compiled .pyc or .pyo file, or from a Windows .pyw file, or a .dll or .so compiled C library, or out of a zip file, to mention just a few. There are many different possibilities. So Python expects you to just give the module name, "filename", without the file extension, and it will search for the correct file regardless of the extension. Python uses the dot notation for packages. "import filename.py" looks for a module called "py" inside a package called "filename". Since it doesn't find one, it raises ImportError. > This is if I enter the file name with the .py extension. If I just enter the > file name without the extension, everything seems to work fine and I > don't get any error message but then when I call a variable I get a > message saying "'X' is not defined". Please show the actual line of code you use, and the actual error message, in full, copied and pasted, and not retyped from memory, or paraphrased, or simplified, or otherwise changed in any way. -- Steven From josep.m.fontana at gmail.com Wed Nov 24 14:50:50 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Wed, 24 Nov 2010 14:50:50 +0100 Subject: [Tutor] Working with interactive Python shell In-Reply-To: References: Message-ID: Thanks Evert and Steve, Both of you are right when you say: > You're not really showing what exactly you type. That's often more clearer than describing what you do, although in this case we can get a pretty good picture anyway. OK, here's what I do: >>>import test I know the shell is importing the file because I can see the following message: The file test.py has the following contents (this is a little line of code I constructed to see how the interactive shell worked importing the file): words = 'in the garden on the bank behind the tree'.split() > How do you 'call the variable'? Sorry, you are right. That was a sloppy use of the term 'call'. I meant to say "print the variable". When I do: >>print words and >>print words[3] In principle I should get: ['in', 'the', 'garden', 'on', 'the', 'bank', 'behind', 'the', 'tree'] and on What I do get is: Traceback (most recent call last): File "", line 1, in NameError: name 'words' is not defined If the file has the contents that I showed above (and it does), 'words' should be defined, shouldn't it? By the way Evert, thanks also for the tip on how to get tabs on a Mac terminal. I didn't know that. Josep M. From evert.rol at gmail.com Wed Nov 24 15:00:13 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 24 Nov 2010 15:00:13 +0100 Subject: [Tutor] Working with interactive Python shell In-Reply-To: References: Message-ID: >> You're not really showing what exactly you type. That's often more clearer than describing what you do, although in this case we can get a pretty good picture anyway. > > OK, here's what I do: > >>>> import test > > I know the shell is importing the file because I can see the following message: > > > > > The file test.py has the following contents (this is a little line of > code I constructed to see how the interactive shell worked importing > the file): > > words = 'in the garden on the bank behind the tree'.split() > >> How do you 'call the variable'? > > Sorry, you are right. That was a sloppy use of the term 'call'. I > meant to say "print the variable". > > When I do: > >>> print words > > and > >>> print words[3] > > In principle I should get: > > ['in', 'the', 'garden', 'on', 'the', 'bank', 'behind', 'the', 'tree'] > > and > > on > > What I do get is: > > Traceback (most recent call last): > File "", line 1, in > NameError: name 'words' is not defined > > If the file has the contents that I showed above (and it does), > 'words' should be defined, shouldn't it? Then you haven't read my previous response carefully enough, or I haven't phrased it properly. The example I gave was: >>> import mymodule >>> mymodule.X where X is defined in a file called mymodule.py In your case, replace mymodule with test, and X with words. Also, really, read the tutorial on modules. I know we tutor here, but those tutorials are there to explain the most common cases (and the standard Python tutorial isn't the only tutorial, but since it comes with Python, it's the one I generally point to). Of course, if something is unclear in the tutorial, let us know! Cheers, Evert From josep.m.fontana at gmail.com Wed Nov 24 15:52:25 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Wed, 24 Nov 2010 15:52:25 +0100 Subject: [Tutor] Working with interactive Python shell In-Reply-To: References: Message-ID: On Wed, Nov 24, 2010 at 3:00 PM, Evert Rol wrote: > Then you haven't read my previous response carefully enough, or I haven't phrased it properly. The example I gave was: > >>>> import mymodule >>>> mymodule.X > > where X is defined in a file called mymodule.py > In your case, replace mymodule with test, and X with words. No, you had phrased it perfectly. I just read your answer too fast. My bad. > Also, really, read the tutorial on modules. I know we tutor here, but those tutorials are there to explain the most common cases (and the standard Python tutorial isn't the only tutorial, but since it comes with Python, it's the one I generally point to). > Of course, if something is unclear in the tutorial, let us know! You are right. I didn't read the link because I assumed it would be general information about modules and I didn't connect that with the problem I was having using the interactive shell. No I checked it and saw that, in fact, the relevant information was right there in the first paragraphs. My apologies. Thanks for your help. Josep M. From susana.delgado_s at utzmg.edu.mx Wed Nov 24 17:19:46 2010 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 24 Nov 2010 10:19:46 -0600 Subject: [Tutor] If os.path.lexists() isn't working properly Message-ID: Hello memebers: I'm writing a python script to validate if files with extension .prj exist, if they exist it should write 1 or 0 into an excel cell. I've working to do this properly, but I'm not getting the results I need. The script doesn't find all the files, is like the files don't exist but they exist, besides I think is just reading some of the files that are in C:\Python 26. I really need a hand on this. import os, time, socket, pylab from xlwt import Workbook from osgeo import ogr,gdal,osr from dbf import * #Register GAL drivers gdal.AllRegister() #Create an empty list file_list = [] folders = None #Code to indicate directory for root, folders, files in os.walk( "C:\\" ): file_list.extend(os.path.join(root,fi) for fi in files if fi.endswith(".shp")) #Open excel book wrkbk = Workbook() #Add excel sheet wksht = wrkbk.add_sheet('shp') wksht.row(0).write(0,'ruta') wksht.row(0).write(1,'archivo') wksht.row(0).write(2,'prj') for row, filepath in enumerate(file_list, start=1): wksht.row(row).write(0, filepath) (ruta, filename) = os.path.split(filepath) wksht.row(row).write(1, filename) n = os.path.splitext(filename) p = n[0]+'.prj' if os.path.lexists(p): wksht.row(row).write(2, 1) else: wksht.row(row).write(2, 0) wrkbk.save('shp3.xls') -------------- next part -------------- An HTML attachment was scrubbed... URL: From jocjo.s at verizon.net Wed Nov 24 18:15:04 2010 From: jocjo.s at verizon.net (John Smith) Date: Wed, 24 Nov 2010 11:15:04 -0600 Subject: [Tutor] Fw: Installing Pyserial for Python27 on Win 7 In-Reply-To: References: <386909.78882.qm@web86705.mail.ird.yahoo.com> <4CEAF720.20304@verizon.net> <4CEB0853.1090302@fenx.com> <4CEB2EE0.6040502@verizon.net> <4CEC33AC.5000100@verizon.net> <4CEC3C14.2090304@verizon.net> Message-ID: <4CED4818.9050104@verizon.net> Hi, Walter - Thanks to you, pyserial is installed and imports into Python. Not having double backslashes was the latest problem that you got me through. I am grateful for the support and education you have given me. Cheers, John From __peter__ at web.de Wed Nov 24 19:36:32 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 24 Nov 2010 19:36:32 +0100 Subject: [Tutor] If os.path.lexists() isn't working properly References: Message-ID: Susana Iraiis Delgado Rodriguez wrote: > Hello memebers: > > I'm writing a python script to validate if files with extension .prj > exist, if they exist it should write 1 or 0 into an excel cell. I've > working to do this properly, but I'm not getting the results I need. The > script doesn't find all the files, is like the files don't exist but they > exist, besides I think is just reading some of the files that are in > C:\Python 26. I really need a hand on this. > > import os, time, socket, pylab > from xlwt import Workbook > from osgeo import ogr,gdal,osr > from dbf import * > #Register GAL drivers > gdal.AllRegister() > #Create an empty list > file_list = [] > folders = None > #Code to indicate directory > for root, folders, files in os.walk( "C:\\" ): > file_list.extend(os.path.join(root,fi) for fi in files if > fi.endswith(".shp")) > #Open excel book > wrkbk = Workbook() > #Add excel sheet > wksht = wrkbk.add_sheet('shp') > wksht.row(0).write(0,'ruta') > wksht.row(0).write(1,'archivo') > wksht.row(0).write(2,'prj') > for row, filepath in enumerate(file_list, start=1): > wksht.row(row).write(0, filepath) > (ruta, filename) = os.path.split(filepath) > wksht.row(row).write(1, filename) > n = os.path.splitext(filename) > p = n[0]+'.prj' Add print "looking for", p here. Does it show what you expect/want? In what directory will lexists() look for the file? > if os.path.lexists(p): lexists()' claim to fame is that it "Returns True for broken symbolic links". Are you sure you prefer that over good old os.path.exists()? > wksht.row(row).write(2, 1) > else: > wksht.row(row).write(2, 0) > wrkbk.save('shp3.xls') From alan.gauld at btinternet.com Wed Nov 24 19:58:10 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 24 Nov 2010 18:58:10 +0000 (GMT) Subject: [Tutor] Lambda function, was: Simple counter to determine frequencies of words in adocument In-Reply-To: References: <41083.43755.qm@web86706.mail.ird.yahoo.com> <509675.78501.qm@web86703.mail.ird.yahoo.com> Message-ID: <259505.94883.qm@web86707.mail.ird.yahoo.com> > > Notice that it uses key as a function inside sorted. > > And lambda creates a function so sorted applies > > the lambda to each item in turn to retrieve the sort key. > > OK. I get it. Thanks a lot. This should have been clear if I had been > able to see the code for the sorted() method. OK Good, But I stress the code I posted bears no relation to the actual code for sorted! It was purely illustrative. > Can anyone point me to a URL (or some other document) > where the code for the different built-in methods can be examined? The source code for Python, including all the standard modules and the builtin stuff is available on the web site to view or download. (The joy of Opensource.) Much of the core code (like sorted) is actually written in C but many of the higher level modules are in Python - and you probably have it on your PC/Mac if you look for the Python modules folder... The good news is that unlike some opensource projects the code quality is pretty good and you can usually figure out how it works fairly easily, even the C stuff. (Having said that I only look at the source about once a year on average, only if things are getting really hairy... :-) HTH, Alan G. From alan.gauld at btinternet.com Wed Nov 24 20:17:10 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Nov 2010 19:17:10 -0000 Subject: [Tutor] IDEs References: <4CEA43B2.2030907@pearwood.info> <4CED0DB8.4090606@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> And we still wound up with over 50 reported bugs during Beta >> test... >> But that was much better than the 2000 bugs on an earlier project >> :-) >> But testing is hard. > > Maybe so, but nothing beats running your test suite and seeing > everything pass! Yes, I should have added ... but debugging is even harder! :-) Alan G. From alan.gauld at btinternet.com Wed Nov 24 20:30:03 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 24 Nov 2010 19:30:03 -0000 Subject: [Tutor] If os.path.lexists() isn't working properly References: Message-ID: "Susana Iraiis Delgado Rodriguez" wrote > I'm writing a python script to validate if files with extension .prj > exist, > if they exist it should write 1 or 0 into an excel cell. I've > working to do > this properly, but I'm not getting the results I need. The script > doesn't > find all the files, is like the files don't exist but they exist, > besides I > think is just reading some of the files that are in C:\Python 26. I > really > need a hand on this. I haven't checked the code thoroughly but it looks like you should maybe put in a print statement to print the root to check it is going where you think it should. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From susana.delgado_s at utzmg.edu.mx Wed Nov 24 21:55:11 2010 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Wed, 24 Nov 2010 14:55:11 -0600 Subject: [Tutor] If os.path.lexists() isn't working properly Message-ID: Hello Peter! I added the line you suggested me and found out that I was just searching for the filenames without pointing to a specific directory, so Python took its directory (Python26) as default. After that I need to add a '\' to separate the path from the filename because it was reading them as a single string. But finally it worked nicely! here is the corrected script. import os, time, socket, pylab, fnmatch from xlwt import Workbook from osgeo import ogr,gdal,osr from dbf import * gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk( "C:\\" ): for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename)) wrkbk = Workbook() wksht = wrkbk.add_sheet('shp') wksht.row(0).write(0,'ruta') wksht.row(0).write(1,'archivo') wksht.row(0).write(2,'prj') for row, filepath in enumerate(file_list, start=1): wksht.row(row).write(0, filepath) (ruta, filename) = os.path.split(filepath) wksht.row(row).write(1, filename) n = os.path.splitext(filename) p = ruta+'\\'+n[0]+'.prj' #"ruta" is the variable that saves the pathfile print "looking for", p #I changed to os.path.exists() if os.path.exists(p): wksht.row(row).write(2, 1) else: wksht.row(row).write(2, 0) wrkbk.save('shp3.xls') #Mensajes para mostar en la consola SEARCH_PATH = os.getcwd() TARGET_FILE = os.path.realpath('shp3.xls') print "Buscando en", SEARCH_PATH, "and writing to", TARGET_FILE print "Encontrando archivos..." print "Escribiendo archivo de Excel..." print "Listo." Thank you so much fro your help! -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffbgoodwin at gmail.com Wed Nov 24 22:51:26 2010 From: jeffbgoodwin at gmail.com (Jeff Goodwin) Date: Wed, 24 Nov 2010 16:51:26 -0500 Subject: [Tutor] Random Number Question Message-ID: Hello, I'm trying to find a way to use the random.randint function to generate a random number, but everytime I run the program it locks up IDLE. Here is what I have so far: import random def main(): x = input("Enter a number: ") y = input("Enter a different number: ") z = random.randint(x,y) print "The random number between ", x, " and ", y, " is ", z main() Can you tell me where I'm going wrong here? When I run the program it allows me to enter the numbers for x and y, then freezes. Thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Wed Nov 24 23:00:42 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 24 Nov 2010 22:00:42 +0000 Subject: [Tutor] Random Number Question In-Reply-To: References: Message-ID: <4CED8B0A.5040602@gmail.com> On 24/11/10 21:51, Jeff Goodwin wrote: > Hello, > I'm trying to find a way to use the random.randint function to > generate a random number, but everytime I run the program it locks up > IDLE. Here is what I have so far: > import random > def main(): > x = input("Enter a number: ") > y = input("Enter a different number: ") > z = random.randint(x,y) > print "The random number between ", x, " and ", y, " is ", z > main() > Can you tell me where I'm going wrong here? When I run the program it > allows me to enter the numbers for x and y, then freezes. > > Thanks! > Jeff > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Your print statement isn't indented. It should print "the random number between" and then throw an exception I think. You should either move the print statement into the function or have main return x, y, z and print the return values of it. HTH. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffbgoodwin at gmail.com Wed Nov 24 23:06:24 2010 From: jeffbgoodwin at gmail.com (Jeff Goodwin) Date: Wed, 24 Nov 2010 17:06:24 -0500 Subject: [Tutor] Random Number Question In-Reply-To: <4CED8B0A.5040602@gmail.com> References: <4CED8B0A.5040602@gmail.com> Message-ID: Thanks Adam, that was a typo on my part, in the program the print is actually indented. Any other suggestions? Thanks again! Jeff On Wed, Nov 24, 2010 at 5:00 PM, Adam Bark wrote: > On 24/11/10 21:51, Jeff Goodwin wrote: > > Hello, > > I'm trying to find a way to use the random.randint function to generate a > random number, but everytime I run the program it locks up IDLE. Here is > what I have so far: > > import random > > def main(): > x = input("Enter a number: ") > y = input("Enter a different number: ") > > z = random.randint(x,y) > > print "The random number between ", x, " and ", y, " is ", z > > main() > > Can you tell me where I'm going wrong here? When I run the program it > allows me to enter the numbers for x and y, then freezes. > > Thanks! > Jeff > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor > > Your print statement isn't indented. It should print "the random number > between" and then throw an exception I think. You should either move the > print statement into the function or have main return x, y, z and print the > return values of it. > > HTH. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffbgoodwin at gmail.com Wed Nov 24 23:10:28 2010 From: jeffbgoodwin at gmail.com (Jeff Goodwin) Date: Wed, 24 Nov 2010 17:10:28 -0500 Subject: [Tutor] Random Number Question In-Reply-To: References: <4CED8B0A.5040602@gmail.com> Message-ID: Ok, I found the problem, I had saved the file as random.py looks like that was a no-no. Its working now that I changed the name. Thanks! Jeff On Wed, Nov 24, 2010 at 5:06 PM, Jeff Goodwin wrote: > Thanks Adam, that was a typo on my part, in the program the print is > actually indented. Any other suggestions? > > Thanks again! > Jeff > > > > On Wed, Nov 24, 2010 at 5:00 PM, Adam Bark wrote: > >> On 24/11/10 21:51, Jeff Goodwin wrote: >> >> Hello, >> >> I'm trying to find a way to use the random.randint function to generate a >> random number, but everytime I run the program it locks up IDLE. Here is >> what I have so far: >> >> import random >> >> def main(): >> x = input("Enter a number: ") >> y = input("Enter a different number: ") >> >> z = random.randint(x,y) >> >> print "The random number between ", x, " and ", y, " is ", z >> >> main() >> >> Can you tell me where I'm going wrong here? When I run the program it >> allows me to enter the numbers for x and y, then freezes. >> >> Thanks! >> Jeff >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options:http://mail.python.org/mailman/listinfo/tutor >> >> Your print statement isn't indented. It should print "the random number >> between" and then throw an exception I think. You should either move the >> print statement into the function or have main return x, y, z and print the >> return values of it. >> >> HTH. >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Thu Nov 25 01:58:23 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 25 Nov 2010 00:58:23 +0000 Subject: [Tutor] Random Number Question In-Reply-To: References: <4CED8B0A.5040602@gmail.com> Message-ID: <4CEDB4AF.2000403@gmail.com> On 24/11/10 22:10, Jeff Goodwin wrote: > Ok, I found the problem, I had saved the file as random.py looks like > that was a no-no. Its working now that I changed the name. > Thanks! > Jeff > Ah yes always avoid giving your modules names that appear in the standard library. It goes wrong, sometimes in unexpected ways. From jgc617 at yahoo.com Wed Nov 24 22:48:08 2010 From: jgc617 at yahoo.com (Judy Chen) Date: Wed, 24 Nov 2010 13:48:08 -0800 (PST) Subject: [Tutor] Python module structure & directories Message-ID: <507863.13562.qm@web31816.mail.mud.yahoo.com> Hi, I am very new to Python, I worked on C/C++ before. I would like to know is it a good practice to put Python development code under ../src/UI/foo.py ../src/businesslogic/bar.py, etc. or should we eliminate "src' directory since it is not pythonic, or it very C/C++ like. I was told that the above directory/file structure does not apply to Python, since Python's source code are objects. What do you say? Are there any standard for how Python source code to be structured? Thanks a lot and I am looking forward to hearing from you soon. Best regards, -- Judy From alan.gauld at btinternet.com Thu Nov 25 02:23:21 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Nov 2010 01:23:21 -0000 Subject: [Tutor] Python module structure & directories References: <507863.13562.qm@web31816.mail.mud.yahoo.com> Message-ID: "Judy Chen" wrote > I am very new to Python, I worked on C/C++ before. > I would like to know is it a good practice to put Python development > code under > > ../src/UI/foo.py > ../src/businesslogic/bar.py, etc. Thats fine, especially if its a big project. src means source code and python is a type of source just as C is. > or should we eliminate "src' directory since it is not pythonic, or > it very C/C++ like. Who says its not pythonic? src is a perfectly common name to use on Unix type systems for all types of source code. > I was told that the above directory/file structure does not apply to > Python, since Python's source code are objects. The source code is not really an object but becaiuse you can import any python file as a module, and modules are objects (once they are loaded) you might get away with saying that. But really, python source files are no different to any other source files when it comes to organising your file system for a project. > Are there any standard for how Python source code to be structured? Not that I'm aware of. There are some standards for how to create packages which might restrict things a little but oprovided you have your PYHONPATH set up tio find the modules all should be well. And you might want to create a build script that moves the modules from src to lib in the production file system. But on a project, especially one with multiple programming languages, having all source files in one place is a definite plus IMHO. Another thing to do would be take a look at some of the Python projects on Sourceforge - DIA for example. See how they structure their code. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Nov 25 02:27:32 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Nov 2010 01:27:32 -0000 Subject: [Tutor] Random Number Question References: <4CED8B0A.5040602@gmail.com> Message-ID: "Jeff Goodwin" wrote > Ok, I found the problem, I had saved the file as random.py looks > like that > was a no-no. Its working now that I changed the name. Yes that's a bad idea. You probably figured out why, but just in case... >>> >>> import random It tries to import itself, which then tries to import itself, which then..... infinite loop time... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jeffbgoodwin at gmail.com Thu Nov 25 03:34:06 2010 From: jeffbgoodwin at gmail.com (Jeff Goodwin) Date: Wed, 24 Nov 2010 21:34:06 -0500 Subject: [Tutor] Random Number Question In-Reply-To: References: <4CED8B0A.5040602@gmail.com> Message-ID: Thanks Adam and Alan for responding, I'm very much a non-programmer, but my 14 year old son wants to learn, so I have to learn to teach him...slow process lol. Happy Thanksgiving! Jeff On Wed, Nov 24, 2010 at 8:27 PM, Alan Gauld wrote: > > "Jeff Goodwin" wrote > > Ok, I found the problem, I had saved the file as random.py looks like >> that >> was a no-no. Its working now that I changed the name. >> > > Yes that's a bad idea. You probably figured out why, but just in case... > > >>>> import random >>>> >>> > It tries to import itself, which then tries to import itself, > which then..... infinite loop time... > > > -- > Alan Gauld > 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 davea at ieee.org Thu Nov 25 04:35:05 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 24 Nov 2010 22:35:05 -0500 Subject: [Tutor] If os.path.lexists() isn't working properly In-Reply-To: References: Message-ID: <4CEDD969.2070800@ieee.org> On 01/-10/-28163 02:59 PM, Susana Iraiis Delgado Rodriguez wrote: > Hello Peter! > > I added the line you suggested me and found out that I was just searching > for the filenames without pointing to a specific directory, so Python took > its directory (Python26) as default. After that I need to add a '\' to > separate the path from the filename because it was reading them as a single > string. But finally it worked nicely! here is the corrected script. > > > wksht.row(row).write(1, filename) > n = os.path.splitext(filename) > p = ruta+'\\'+n[0]+'.prj' > Use os.path.join() to combine these nodes. If you use an explicit backslash you can trigger two problems: 1) Your code won't be portable to other platforms 2) You could have trouble if one of the components already has a path separator. DaveA From quasipedia at gmail.com Thu Nov 25 08:00:07 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 25 Nov 2010 08:00:07 +0100 Subject: [Tutor] Random Number Question In-Reply-To: <4CEDB4AF.2000403@gmail.com> References: <4CED8B0A.5040602@gmail.com> <4CEDB4AF.2000403@gmail.com> Message-ID: <20101125080007.699d7c9d@jabbar> On Thu, 25 Nov 2010 00:58:23 +0000 Adam Bark wrote: > Ah yes always avoid giving your modules names that appear in the > standard library. It goes wrong, sometimes in unexpected ways. I was wondering... apart from checking each name individually, is there any easy-peasy way to get a list of names used in the standard library (I am thinking to something like "dir(....)"? Mac. From ydexy at videotron.ca Thu Nov 25 04:04:29 2010 From: ydexy at videotron.ca (Yves Dextraze) Date: Wed, 24 Nov 2010 22:04:29 -0500 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? Message-ID: Sent from my iPod From alan.gauld at btinternet.com Thu Nov 25 10:27:33 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Nov 2010 09:27:33 -0000 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? References: Message-ID: "Yves Dextraze" wrote > Sent from my iPod There is no mention on Amazon of any new editions and they usually announce several months in advance... A pity a new Tkinter book using Tix and ttk instead of PMW would be a really useful resource! Alan G. From timomlists at gmail.com Thu Nov 25 11:09:10 2010 From: timomlists at gmail.com (Timo) Date: Thu, 25 Nov 2010 11:09:10 +0100 Subject: [Tutor] Random Number Question In-Reply-To: <20101125080007.699d7c9d@jabbar> References: <4CED8B0A.5040602@gmail.com> <4CEDB4AF.2000403@gmail.com> <20101125080007.699d7c9d@jabbar> Message-ID: <4CEE35C6.7070406@gmail.com> On 25-11-10 08:00, Mac Ryan wrote: > On Thu, 25 Nov 2010 00:58:23 +0000 > Adam Bark wrote: > >> Ah yes always avoid giving your modules names that appear in the >> standard library. It goes wrong, sometimes in unexpected ways. > I was wondering... apart from checking each name individually, is there > any easy-peasy way to get a list of names used in the standard library > (I am thinking to something like "dir(....)"? This is the webpage I always use for searching an appropriate module: http://docs.python.org/modindex.html Cheers, Timo > Mac. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From quasipedia at gmail.com Thu Nov 25 13:20:22 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Thu, 25 Nov 2010 13:20:22 +0100 Subject: [Tutor] Random Number Question In-Reply-To: <4CEE35C6.7070406@gmail.com> References: <4CED8B0A.5040602@gmail.com> <4CEDB4AF.2000403@gmail.com> <20101125080007.699d7c9d@jabbar> <4CEE35C6.7070406@gmail.com> Message-ID: <20101125132022.5101eb8f@jabbar> On Thu, 25 Nov 2010 11:09:10 +0100 Timo wrote: > > I was wondering... apart from checking each name individually, is > > there any easy-peasy way to get a list of names used in the > > standard library (I am thinking to something like "dir(....)"? > This is the webpage I always use for searching an appropriate module: > http://docs.python.org/modindex.html I was more thinking to some introspective capacity of python itself rather than a web page... yet, thank you for the link that I did not know beforehand! :) Mac. From cfuller084 at thinkingplanet.net Thu Nov 25 13:27:56 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 25 Nov 2010 06:27:56 -0600 Subject: [Tutor] Random Number Question In-Reply-To: <20101125080007.699d7c9d@jabbar> References: <4CEDB4AF.2000403@gmail.com> <20101125080007.699d7c9d@jabbar> Message-ID: <201011250627.57050.cfuller084@thinkingplanet.net> Well, you can try "import x", but your problem wasn't that you used the same filename as some Python script on your path, the problem was you then tried to import that other script. So to avoid infinite recursion, all you have to do is avoid importing your own filename, which should be easy enough to do (assuming there aren't any indirect loops, of course.. but admitting that possibility is the price you pay for having the advantages of a dynamic language) On Thursday 25 November 2010, Mac Ryan wrote: > On Thu, 25 Nov 2010 00:58:23 +0000 > > Adam Bark wrote: > > Ah yes always avoid giving your modules names that appear in the > > standard library. It goes wrong, sometimes in unexpected ways. > > I was wondering... apart from checking each name individually, is there > any easy-peasy way to get a list of names used in the standard library > (I am thinking to something like "dir(....)"? > > Mac. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From susana.delgado_s at utzmg.edu.mx Thu Nov 25 15:20:56 2010 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Thu, 25 Nov 2010 08:20:56 -0600 Subject: [Tutor] If os.path.lexists() isn't working properly In-Reply-To: <4CEDD969.2070800@ieee.org> References: <4CEDD969.2070800@ieee.org> Message-ID: Hi Dave! Thank you for your suggestion I haven't prevent the problems you're describing, but I'm newbie in this stuff so, where should I repalce the code? Thank you again! 2010/11/24 Dave Angel > On 01/-10/-28163 02:59 PM, Susana Iraiis Delgado Rodriguez wrote: > >> Hello Peter! >> >> I added the line you suggested me and found out that I was just searching >> for the filenames without pointing to a specific directory, so Python took >> its directory (Python26) as default. After that I need to add a '\' to >> separate the path from the filename because it was reading them as a >> single >> string. But finally it worked nicely! here is the corrected script. >> >> >> >> wksht.row(row).write(1, filename) >> n = os.path.splitext(filename) >> p = ruta+'\\'+n[0]+'.prj' >> >> > Use os.path.join() to combine these nodes. If you use an explicit > backslash you can trigger two problems: 1) Your code won't be portable to > other platforms 2) You could have trouble if one of the components already > has a path separator. > > > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Nov 25 17:45:27 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 25 Nov 2010 11:45:27 -0500 Subject: [Tutor] If os.path.lexists() isn't working properly In-Reply-To: References: <4CEDD969.2070800@ieee.org> Message-ID: <4CEE92A7.2000705@ieee.org> On 11/25/2010 09:20 AM, Susana Iraiis Delgado Rodriguez wrote: > Hi Dave! > > Thank you for your suggestion I haven't prevent the problems you're > describing, but I'm newbie in this stuff so, where should I repalce the > code? > > Thank you again! > 2010/11/24 Dave Angel > >> On 01/-10/-28163 02:59 PM, Susana Iraiis Delgado Rodriguez wrote: >> >>> >>> >>> wksht.row(row).write(1, filename) >>> n = os.path.splitext(filename) >>> p = ruta+'\\'+n[0]+'.prj' >>> >>> >> Use os.path.join() to combine these nodes. If you use an explicit >> backslash you can trigger two problems: 1) Your code won't be portable to >> other platforms 2) You could have trouble if one of the components already >> has a path separator. >> >> >> DaveA >> > May I request that you put your response at the end, or directly after whatever you're responding to. What you did is called top-posting, and while it's common in private email, it's bad practice in these forums. It's also good to trim the parts that are no longer relevant, so the messages don't get too huge. I'm guilty of omitting that step way too often. You have an example of os.path.join() in your own code, a few lines up. But for this particular line, you could use p = os.path.join(ruta, n[0], ".lprj") HTH DaveA From kliateni at gmail.com Thu Nov 25 10:42:34 2010 From: kliateni at gmail.com (Karim) Date: Thu, 25 Nov 2010 10:42:34 +0100 Subject: [Tutor] Python module structure & directories In-Reply-To: References: <507863.13562.qm@web31816.mail.mud.yahoo.com> Message-ID: <4CEE2F8A.9080400@gmail.com> Hello, I use to have it under src/lib as follow: src/lib/python src/lib/tcl src/lib/c All *.py modules are in src/lib/python with all the possible modules hierarchy. Then, At build time I copy lib root directory in the install. (with all C code compiled). Then the startup bin executable do the following as Alan said: *if ! echo $PYTHON | grep "/lib" > /dev/null ; then export PYTHONPATH="/lib:${PYTHONPATH}" fi* The conditional statement is here just to not overload the environment variable. Best Regards Karim On 11/25/2010 02:23 AM, Alan Gauld wrote: > > "Judy Chen" wrote > >> I am very new to Python, I worked on C/C++ before. >> I would like to know is it a good practice to put Python development >> code under >> >> ../src/UI/foo.py >> ../src/businesslogic/bar.py, etc. > > Thats fine, especially if its a big project. > src means source code and python is a type of source just as C is. > >> or should we eliminate "src' directory since it is not pythonic, or >> it very C/C++ like. > > Who says its not pythonic? > src is a perfectly common name to use on Unix type systems for all types > of source code. > >> I was told that the above directory/file structure does not apply to >> Python, since Python's source code are objects. > > The source code is not really an object but becaiuse you can import > any python file as a module, and modules are objects (once they are > loaded) you might get away with saying that. But really, python source > files are no different to any other source files when it comes to > organising > your file system for a project. > >> Are there any standard for how Python source code to be structured? > > Not that I'm aware of. There are some standards for how to create > packages which might restrict things a little but oprovided you have > your PYHONPATH set up tio find the modules all should be well. > And you might want to create a build script that moves the modules > from src to lib in the production file system. But on a project, > especially > one with multiple programming languages, having all source files in > one place is a definite plus IMHO. > > Another thing to do would be take a look at some of the Python projects > on Sourceforge - DIA for example. See how they structure their code. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kliateni at gmail.com Thu Nov 25 10:53:32 2010 From: kliateni at gmail.com (Karim) Date: Thu, 25 Nov 2010 10:53:32 +0100 Subject: [Tutor] Python module structure & directories In-Reply-To: References: <507863.13562.qm@web31816.mail.mud.yahoo.com> Message-ID: <4CEE321C.9040100@gmail.com> Another possibility is to place you python library in the site package of your network installation, namely for my computer: *$HOME/build/python/src/Python-2.7.1rc1/Lib/site-packages* I build the latest release of python (rc1). But At build time I believe that the path to the libraries is hard-coded somewhere. Indeed, I provide the python v2.7.1rc1 package along with my application and I use PYTHONPATH to overcome this fact and point to the libraries of v2.7.1rc1 and PATH for python exec. Like that I am independent of the version of python present on a particular machine. Best Regards Karim On 11/25/2010 02:23 AM, Alan Gauld wrote: > > "Judy Chen" wrote > >> I am very new to Python, I worked on C/C++ before. >> I would like to know is it a good practice to put Python development >> code under >> >> ../src/UI/foo.py >> ../src/businesslogic/bar.py, etc. > > Thats fine, especially if its a big project. > src means source code and python is a type of source just as C is. > >> or should we eliminate "src' directory since it is not pythonic, or >> it very C/C++ like. > > Who says its not pythonic? > src is a perfectly common name to use on Unix type systems for all types > of source code. > >> I was told that the above directory/file structure does not apply to >> Python, since Python's source code are objects. > > The source code is not really an object but becaiuse you can import > any python file as a module, and modules are objects (once they are > loaded) you might get away with saying that. But really, python source > files are no different to any other source files when it comes to > organising > your file system for a project. > >> Are there any standard for how Python source code to be structured? > > Not that I'm aware of. There are some standards for how to create > packages which might restrict things a little but oprovided you have > your PYHONPATH set up tio find the modules all should be well. > And you might want to create a build script that moves the modules > from src to lib in the production file system. But on a project, > especially > one with multiple programming languages, having all source files in > one place is a definite plus IMHO. > > Another thing to do would be take a look at some of the Python projects > on Sourceforge - DIA for example. See how they structure their code. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Nov 25 22:14:23 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Nov 2010 22:14:23 +0100 Subject: [Tutor] Random Number Question References: <4CED8B0A.5040602@gmail.com> Message-ID: Alan Gauld wrote: >>>> import random > > It tries to import itself, which then tries to import itself, > which then..... infinite loop time... I think it's more like - look up module random in sys.modules - module random not found in sys.modules; locate the file random.py - file random.py found, create a new empty module object and put it into sys.modules - execute code loaded from random.py, encounter 'import random', look up random in sys.modules - module random found in sys.modules, bind it to the name 'random' in itself - continue execution of random.py code. This will succeed unless you try to access random.some_name for a name not already defined. In short: you are more likely to get an AttributeError than infinite recursion. $ cat module.py print "importing", __name__ import module print module.yadda yadda = 42 $ python -c'import module' importing module Traceback (most recent call last): File "", line 1, in File "module.py", line 3, in print module.yadda AttributeError: 'module' object has no attribute 'yadda' $ cat module2.py print "importing", __name__ yadda = 42 import module2 print module2.yadda $ python -c'import module2' importing module2 42 While the latter "works" as in "runs without error" it still isn't a good idea. By the way, you can generalise the above to arbitrary circular imports where module a imports b which imports c which imports ... which imports z which imports a. Peter From ranceh at gmail.com Thu Nov 25 22:33:24 2010 From: ranceh at gmail.com (Rance Hall) Date: Thu, 25 Nov 2010 15:33:24 -0600 Subject: [Tutor] if syntax expression help Message-ID: I have a user entered variable that I need to check to see if they entered one of the two legal values. But I only need to check this if one other fact is true. we have a variable called "mode" whose value is either "add" or "edit" based on how we where called. we have a userentry variable tied to an imput function. My current if statement looks like this: if ((userentry.lower != "c" or userentry.lower != "i") and mode == "add"): do stuff else: do other stuff My problem is that my other stuff always executes even when I think my stuff should run. so what I want is two conditions tested simultaneously I think I have a syntax problem with the parenthesis because I can't find documentation where this is valid, but it doesn't error out so python doesn't choke on this. I know about nested ifs but I was trying to avoid them for elegance and easier reading. if mode is "add" then my userentry field needs good data, but if my mode is NOT "add" then I don't care about this data cause I'm not going to be using it. Ive tried to construct the logic such that when the if is true, its the stuff that runs, and when the if is false, its the other stuff that runs. Because of the NOT equal tos in the if a false is actually a passed test, and true is actually a failed test. Could someone please help me figure out the best way to say this in python. BTW its python31 From __peter__ at web.de Thu Nov 25 22:47:19 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Nov 2010 22:47:19 +0100 Subject: [Tutor] if syntax expression help References: Message-ID: Rance Hall wrote: > I have a user entered variable that I need to check to see if they > entered one of the two legal values. > > But I only need to check this if one other fact is true. > > > we have a variable called "mode" whose value is either "add" or > "edit" based on how we where called. > > we have a userentry variable tied to an imput function. > > My current if statement looks like this: > > if ((userentry.lower != "c" or userentry.lower != "i") and > mode == "add"): Hint: >>> userentry = "YADDA" >>> userentry.lower >>> userentry.lower() 'yadda' From alan.gauld at btinternet.com Thu Nov 25 23:23:09 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 25 Nov 2010 22:23:09 -0000 Subject: [Tutor] if syntax expression help References: Message-ID: "Rance Hall" wrote > My current if statement looks like this: > > if ((userentry.lower != "c" or userentry.lower != "i") > and > mode == "add"): Peter has poinrted out one roblem but there is another. The or expression will always be true, consider: 1) The first term will only fail if the value is 'c' If the value is 'c; then the second trrrm will be True and the or expression will be True 2)The 2nd term will only fail if the value is 'i' If the value is 'i' then the first term will be True and the or expression will be True And since True and A is the same as A you ight as well just write: if mode == 'add': Based on your code I'm not actually sure what the correct logic should be, but I'm pretty sure its not what you have! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ranceh at gmail.com Fri Nov 26 03:28:28 2010 From: ranceh at gmail.com (Rance Hall) Date: Thu, 25 Nov 2010 20:28:28 -0600 Subject: [Tutor] for loops when there is only one row in the result - is there an alternative? Message-ID: Im using the py-postgresql module (docs here: http://python.projects.postgresql.org/docs/1.0/) in a python 3.1 environment to connect to my database. so far everything is working, but I'm having trouble understanding the structure of the variable returned by a select statement Generally you have something like this: clientlist = get_clients() # where get_clients is a prepared sql statement. normally you would get the individual rows like this: for row in clientlist: do stuff which is great for a long list of results. But I'm running into issues when there are only 0 or 1 results in the set. if there are zero rows then I can do something like: if len(clientlist) == 0: do stuff I'm looking for a better way to access the row when there is just one row in the result. Say from a user login attempt, or a request to edit an existing client record. Is there a decent way to get direct access to the single row in the result set without having to go through the for loop for just one item? It likely helps to know exactly what variable type clientlist would be. I have no idea. What I can say is that once you do get the row result, you can refer to values in the row with syntax like row["columnname"], but I'm honestly not sure if this is helpful information. Ive read the module docs looking for something interesting, but I can't seem to find this particular tidbit. If I have to do the for loop fine, but I just thought it looked a little ugly. Rance From steve at pearwood.info Fri Nov 26 03:55:51 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 26 Nov 2010 13:55:51 +1100 Subject: [Tutor] for loops when there is only one row in the result - is there an alternative? In-Reply-To: References: Message-ID: <4CEF21B7.1010909@pearwood.info> Rance Hall wrote: > Generally you have something like this: > > clientlist = get_clients() # where get_clients is a prepared sql statement. > > normally you would get the individual rows like this: > > for row in clientlist: > do stuff > > > which is great for a long list of results. But I'm running into > issues when there are only 0 or 1 results in the set. If clientlist is empty, you don't need to explicitly test for it: >>> clientlist = [] # nothing there >>> for row in clientlist: ... print("Hello world") ... >>> Notice that nothing gets printed. > if there are zero rows then I can do something like: > > if len(clientlist) == 0: > do stuff Generally one merely needs to check the list itself: if clientlist: ... although be warned that "lazy lists", or iterators, are slightly different -- but if len(clientlist) works, then this should also work. > I'm looking for a better way to access the row when there is just one > row in the result. This should work: row, = clientlist # if one row only -- note the comma! row1, row2 = clientlist # if two rows row1, row2, row3 = clientlist # three rows If the comma in the first example is too subtle, try this: [row] = clientlist Another way which should work: row = clientlist[0] > Say from a user login attempt, or a request to edit an existing client record. > > Is there a decent way to get direct access to the single row in the > result set without having to go through the for loop for just one > item? > > It likely helps to know exactly what variable type clientlist would > be. I have no idea. type(clientlist) will tell you. -- Steven From kb1pkl at aim.com Fri Nov 26 04:47:28 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 25 Nov 2010 22:47:28 -0500 Subject: [Tutor] List Changing Order Message-ID: <4CEF2DD0.3010009@aim.com> Tutors, I recall that the keys of dictionaries have arbitrary order, and may change over time. Is this true of lists? I can't find the answer from a simple Google search. Thank you! From prologic at shortcircuit.net.au Fri Nov 26 05:18:25 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 26 Nov 2010 14:18:25 +1000 Subject: [Tutor] List Changing Order In-Reply-To: <4CEF2DD0.3010009@aim.com> References: <4CEF2DD0.3010009@aim.com> Message-ID: On Fri, Nov 26, 2010 at 1:47 PM, Corey Richardson wrote: > I recall that the keys of dictionaries have arbitrary order, and may change > over time. Is this true of lists? I can't find the answer from a simple > Google search. Thank you! items append to a list retain their order. cheers James -- -- James Mills -- -- "Problems are solved by method" From steve at pearwood.info Fri Nov 26 07:25:26 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 26 Nov 2010 17:25:26 +1100 Subject: [Tutor] List Changing Order In-Reply-To: <4CEF2DD0.3010009@aim.com> References: <4CEF2DD0.3010009@aim.com> Message-ID: <4CEF52D6.6020201@pearwood.info> Corey Richardson wrote: > Tutors, > > I recall that the keys of dictionaries have arbitrary order, and may > change over time. Is this true of lists? I can't find the answer from a > simple Google search. Thank you! Only if you re-arrange it yourself. list.sort(), list.reverse() and random.shuffle(list) explicitly change the list's order. You can also manually move items around, e.g.: list[3], list[5] = list[5], list[3] # swap items 3 and 5 but otherwise lists keep their order. -- Steven From michaelsprayberry at yahoo.com Fri Nov 26 13:02:12 2010 From: michaelsprayberry at yahoo.com (Michael Sprayberry) Date: Fri, 26 Nov 2010 04:02:12 -0800 (PST) Subject: [Tutor] [tutor] list order change Message-ID: <654301.16053.qm@web53902.mail.re2.yahoo.com> You can also sort a list so that is ordered in reverse or alphabetically ? ? Cheers, Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Fri Nov 26 15:20:44 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 26 Nov 2010 09:20:44 -0500 Subject: [Tutor] List Changing Order In-Reply-To: <4CEF52D6.6020201@pearwood.info> References: <4CEF2DD0.3010009@aim.com> <4CEF52D6.6020201@pearwood.info> Message-ID: <4CEFC23C.50003@aim.com> Steven D'Aprano wrote: > Corey Richardson wrote: >> Tutors, >> >> I recall that the keys of dictionaries have arbitrary order, and may >> change over time. Is this true of lists? I can't find the answer from >> a simple Google search. Thank you! > > Only if you re-arrange it yourself. > > list.sort(), list.reverse() and random.shuffle(list) explicitly change > the list's order. You can also manually move items around, e.g.: > > list[3], list[5] = list[5], list[3] # swap items 3 and 5 > > but otherwise lists keep their order. > Many thanks, everyone who replied. From susana.delgado_s at utzmg.edu.mx Fri Nov 26 15:40:46 2010 From: susana.delgado_s at utzmg.edu.mx (Susana Iraiis Delgado Rodriguez) Date: Fri, 26 Nov 2010 08:40:46 -0600 Subject: [Tutor] If os.path.lexists() isn't working properly In-Reply-To: <4CEE92A7.2000705@ieee.org> References: <4CEDD969.2070800@ieee.org> <4CEE92A7.2000705@ieee.org> Message-ID: Hello! After all the sugestions I received throught this list; I tried them all and worked ok. At he end I noticed that a single variable change will bring me the results I was looking for. In my code I replaced the line n = os.path.splitext(filename) for: n = os.path.splitext(filepath) p = n[0]+'.prj' if os.path.exists(p): ....... code I just wanted to pointed out, thank you all of you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From washakie at gmail.com Fri Nov 26 17:10:07 2010 From: washakie at gmail.com (John) Date: Fri, 26 Nov 2010 17:10:07 +0100 Subject: [Tutor] normalize an array Message-ID: I know this is a simple problem, but I want to do it the most efficient way (that is vectorized...) import numpy as np a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) b = np.sum(a,axis=1) for i,elem in enumerate(a): a[i,:] = elem/b[i] suggestions? From piotr-kam at o2.pl Fri Nov 26 18:33:07 2010 From: piotr-kam at o2.pl (=?utf-8?B?UGlvdHIgS2FtacWEc2tp?=) Date: Fri, 26 Nov 2010 18:33:07 +0100 Subject: [Tutor] Random Number Question In-Reply-To: <20101125132022.5101eb8f@jabbar> References: <4CED8B0A.5040602@gmail.com> <4CEDB4AF.2000403@gmail.com> <20101125080007.699d7c9d@jabbar> <4CEE35C6.7070406@gmail.com> <20101125132022.5101eb8f@jabbar> Message-ID: Dnia 25-11-2010 o 13:20:22 Mac Ryan napisa?(a): > On Thu, 25 Nov 2010 11:09:10 +0100 > Timo wrote: > >> > I was wondering... apart from checking each name individually, is >> > there any easy-peasy way to get a list of names used in the >> > standard library (I am thinking to something like "dir(....)"? >> This is the webpage I always use for searching an appropriate module: >> http://docs.python.org/modindex.html > > I was more thinking to some introspective capacity of python itself > rather than a web page... yet, thank you for the link that I did not > know beforehand! :) > > Mac. You can get the list of Python's standard modules by typing help() and then you will see something similar to: >>> help() Welcome to Python 2.6! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". help> modules ...... ...... ======= The last paragraph of the message shows the answer to you question. HTH, Piotr From quasipedia at gmail.com Fri Nov 26 20:43:38 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Fri, 26 Nov 2010 20:43:38 +0100 Subject: [Tutor] Random Number Question In-Reply-To: References: <4CED8B0A.5040602@gmail.com> <4CEDB4AF.2000403@gmail.com> <20101125080007.699d7c9d@jabbar> <4CEE35C6.7070406@gmail.com> <20101125132022.5101eb8f@jabbar> Message-ID: <20101126204338.1767d1bb@jabbar> On Fri, 26 Nov 2010 18:33:07 +0100 Piotr Kami?ski wrote: > You can get the list of Python's standard modules by typing help() > and then you will see something similar to: Thanks a lot! This is what I was after! Mac. From ctsterne at gmail.com Fri Nov 26 21:16:58 2010 From: ctsterne at gmail.com (Cory Teshera-Sterne) Date: Fri, 26 Nov 2010 15:16:58 -0500 Subject: [Tutor] Consequences of opening subprocesses? Message-ID: Hi all, I'm practicing python by rewriting some bash scripts, and I've found a few things that I can't directly translate, like certain calls to command-line tools. I've figured out how to start them with the subprocess module, but I'm wondering if I'm going to get myself in hot water memory- or performance-wise since these scripts are scheduled to run on thousands of files fairly often. Do I need to explicitly close the subprocesses, or clean them up, or something (I have some programming experience, but not a lot of experience with taking into account these kinds of issues - ie, no C ... )? An example is a call to the command-line image manipulation program, ImageMagick: s = subprocess.Popen(['identify', '-format', ''%w %h\n'', 'testimg.jpg'], stdout=subprocess.PIPE) output = s.communicate()[0] print output # output should be the dimensions of testimg.jpg in pixels, ie, 100 50 What I'm thinking is that if, when typed into the terminal, the command appears to give me some output and then exit like the one above (or bash commands like "ls -l"), then I'm ok ... but like I said, I just don't know much about this kind of issue. Can anyone tell me if my intuition's way off on this? Thanks! -Cory -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Nov 26 23:23:51 2010 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Nov 2010 23:23:51 +0100 Subject: [Tutor] normalize an array References: Message-ID: John wrote: > I know this is a simple problem, but I want to do it the most > efficient way (that is vectorized...) > > import numpy as np > > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) > b = np.sum(a,axis=1) > > for i,elem in enumerate(a): > a[i,:] = elem/b[i] > suggestions? I'm not a numpy expert, but: (a.transpose()/np.sum(a, axis=1)).transpose() Peter From alan.gauld at btinternet.com Fri Nov 26 23:37:40 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 26 Nov 2010 22:37:40 -0000 Subject: [Tutor] Consequences of opening subprocesses? References: Message-ID: "Cory Teshera-Sterne" wrote > I'm wondering if I'm going to get myself in hot water memory- or > performance-wise since these scripts are scheduled to run on > thousands of > files fairly often. It shouldn't be worse than your bash scripts since they implicitly start subprocesses anyway. And if you mare moving some of the functionality into Python it should be better overall. > Do I need to explicitly close the subprocesses, or clean > them up, or something Mostly they should just close down themselves. Keep a check with a tool like top when testing to ensure you don't get something stuck spinning in a loop, but it should be OK most of the time. > An example is a call to the command-line image manipulation program, > ImageMagick: > s = subprocess.Popen(['identify', '-format', ''%w %h\n'', > 'testimg.jpg'], > stdout=subprocess.PIPE) If its image manipulation have you checked out the PIL package? It can do most of what imagemagick can do from Python. Its not in the standard library but Google will find it for you. The only snag is that I'm not sure if its on Python 3 yet if you are using v3... > # output should be the dimensions of testimg.jpg in pixels, ie, 100 > 50 PIL should definitely be able to manage that kind of thing. There are also Python bindings to drive ImageMagick from within Python too although I don;t know if they are regularly maintained. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tsolox at gmail.com Sat Nov 27 02:23:40 2010 From: tsolox at gmail.com (john tsolox) Date: Sat, 27 Nov 2010 09:23:40 +0800 Subject: [Tutor] lambda in python Message-ID: <20101127012340.GB3657@dx.domain.name> since in Java i can pass an anonymous class to a function, and this anon class has member functions that can contain a body of implementation codes having the full expression of permissible syntax (if,for,while...), my question is, after seeing various examples of lambda in python being ALL one-liners. These one-liners inside a lambda seems not to have the full permissible use of the full power of python language (if,for,while). Is this correct? Is it correct to say, that within python lambda, you are not allowed to use 'if' ? pls enlighten... From steve at pearwood.info Sat Nov 27 02:31:44 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 27 Nov 2010 12:31:44 +1100 Subject: [Tutor] lambda in python In-Reply-To: <20101127012340.GB3657@dx.domain.name> References: <20101127012340.GB3657@dx.domain.name> Message-ID: <4CF05F80.40408@pearwood.info> john tsolox wrote: > since in Java i can pass an anonymous class to a function, and this anon class has member functions that can contain a > body of implementation codes having the full expression of permissible syntax (if,for,while...), my question is, after > seeing various examples of lambda in python being ALL one-liners. These one-liners inside a lambda seems not to have the > full permissible use of the full power of python language (if,for,while). Is this correct? > > Is it correct to say, that within python lambda, you are not allowed to use 'if' ? pls enlighten... Python lambda is syntactic sugar for an anonymous function, not a class. Lambda is also limited to only a single expression. However, you can use the ternary if: lambda x: x+1 if x < 0 else x-3 is almost the same as: def func(x): if x < 0: return x+1 else: return x-3 -- Steven From carroll at tjc.com Sat Nov 27 02:51:17 2010 From: carroll at tjc.com (Terry Carroll) Date: Fri, 26 Nov 2010 17:51:17 -0800 (PST) Subject: [Tutor] %T as a strftime format identifier Message-ID: Was %T ever a valid format specifier for time.strftime in Python? I just installed a Python streaming MP3 server called Edna (http://edna.sourceforge.net/). It was an easy install except that I got a ValueError on one line, essentially for: time.strftime("%a, %d %b %Y %T GMT") After a few seconds experimentation, I found that "%T" is not recognized, but that in ANSI C strftime, it's a shorthand for %H:%M:%S. I changed it to: time.strftime("%a, %d %b %Y %H:%M:%S PST") and it worked fine. My question: was %T ever a valid format specifier in Python? My best guess is that it was when Edna was written (the most current release is from 2006, and the docs say it needs at least Python 1.5.2, which gives you an example of its age). It seems odd that the format identifier would be dropped if it had existed, though; that seems like a needless upward compatibility issue. I got this working, so this is mere curiosity; anyone know? From steve at pearwood.info Sat Nov 27 09:10:35 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 27 Nov 2010 19:10:35 +1100 Subject: [Tutor] %T as a strftime format identifier In-Reply-To: References: Message-ID: <4CF0BCFB.6010301@pearwood.info> Terry Carroll wrote: > My question: was %T ever a valid format specifier in Python? My best > guess is that it was when Edna was written (the most current release is > from 2006, and the docs say it needs at least Python 1.5.2, which gives > you an example of its age). It seems odd that the format identifier > would be dropped if it had existed, though; that seems like a needless > upward compatibility issue. Works for me: [steve at sylar ~]$ python2.5 Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.strftime("%T") '19:03:16' and similarly for other versions as well. I think what you are seeing is differences in the C compiler, not deliberate language changes. As I recall it, the time format identifiers are dependent on the C library used to compile the time module, and/or the locale. If the C library involved doesn't recognise %T, neither will Python. On the other hand, %T isn't listed in the manual: http://docs.python.org/library/time.html#time.strftime -- Steven From wangoloj at yahoo.com Sat Nov 27 09:55:10 2010 From: wangoloj at yahoo.com (Wangolo Joel) Date: Sat, 27 Nov 2010 08:55:10 +0000 (GMT) Subject: [Tutor] Tutor Digest, Vol 81, Issue 90 In-Reply-To: Message-ID: <631794.21995.qm@web29702.mail.ird.yahoo.com> -- I NOLONGER WANT YOUR TUTORIALS BECAUSE OF SPAM VIRUSES THANK YOU FOR YOUR SERVISES -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Nov 27 11:03:35 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Nov 2010 10:03:35 -0000 Subject: [Tutor] lambda in python References: <20101127012340.GB3657@dx.domain.name> Message-ID: "john tsolox" wrote > seeing various examples of lambda in python being ALL one-liners. > These one-liners inside a lambda seems not to have the > full permissible use of the full power of python language > (if,for,while). Is this correct? The lambda expression was introduced into Python by popular demand to further support the functional style of programming. Functional programming does not encourage the use of state and so lambda was constrained to be a pure expression. For practical purposes this is a slight inconvenience and full function code block syntax - ala Ruby - would be nice, but for most of it's intended uses lambda expressions are adequate. You can always define a named function within the using scope if you need more. IMO. Rather than seeing lambda increased in power we are frankly more likely to see lambda removed from the language in some far future incarnation. This has been seriously discussed several times on the main Python newsgroup. See the functional programming topic in my tutorial for more info on lambda and Python's FP support as a whole. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From delegbede at dudupay.com Sat Nov 27 10:38:17 2010 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sat, 27 Nov 2010 09:38:17 +0000 Subject: [Tutor] Tutor Digest, Vol 81, Issue 90 In-Reply-To: <631794.21995.qm@web29702.mail.ird.yahoo.com> References: <631794.21995.qm@web29702.mail.ird.yahoo.com> Message-ID: <300826519-1290850719-cardhu_decombobulator_blackberry.rim.net-149689915-@b3.c12.bise7.blackberry> I am beginning to feel the name Wangolo Joel is not human. It probably could be the name of a virus. It has been said over and over how to unsubscribe to an extent that someone actually sent a link and yet, we are still getting this mail. Can anyone write a simple program to deactivate this virus. Regards. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Wangolo Joel Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sat, 27 Nov 2010 08:55:10 To: Subject: Re: [Tutor] Tutor Digest, Vol 81, Issue 90 _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Nov 27 11:13:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Nov 2010 10:13:27 -0000 Subject: [Tutor] Tutor Digest, Vol 81, Issue 90 References: <631794.21995.qm@web29702.mail.ird.yahoo.com> Message-ID: I have unsubscribed Joel since he seems incapable of following the instructions. Alan G. Moderator. "Wangolo Joel" wrote in message news:631794.21995.qm at web29702.mail.ird.yahoo.com... -- I NOLONGER WANT YOUR TUTORIALS BECAUSE OF SPAM VIRUSES THANK YOU FOR YOUR SERVISES -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From tkokchen at gmail.com Sat Nov 27 15:00:03 2010 From: tkokchen at gmail.com (Kok Cheng Tan) Date: Sat, 27 Nov 2010 22:00:03 +0800 Subject: [Tutor] Python Exercise Message-ID: Hi, I created this website for practising python online: http://www.pyschools.com. Hope to gather feedback from people here who are interesting in teaching and learning python. Regards, Kok Cheng From alan.gauld at btinternet.com Sat Nov 27 16:04:57 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Nov 2010 15:04:57 -0000 Subject: [Tutor] Reload() in v3? WAS Re: IDEs References: <4CEA43B2.2030907@pearwood.info> Message-ID: "Steven D'Aprano" wrote > The other nine times out of ten *wink* I need to do debugging, and I > swap tabs and work in my interactive Python interpreter. > > import filename # first time only > reload(filename) # all subsequent times I'm working on the v3 version of my tutor and while testing some module code I tried to reload the module in IDLE... I got an error: >>> import os >>> reload(os) Traceback (most recent call last): File "", line 1, in reload(os) NameError: name 'reload' is not defined >>> Has reload been removed in V3? Whats the alternative? Does a repeated import auto-reload? I'm surprised and confused... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Nov 27 16:11:53 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 27 Nov 2010 15:11:53 -0000 Subject: [Tutor] Reload() in v3? WAS Re: IDEs References: <4CEA43B2.2030907@pearwood.info> Message-ID: "Alan Gauld" wrote > Has reload been removed in V3? > Whats the alternative? Does a repeated import auto-reload? > > I'm surprised and confused... Found it, its been moved into the imp module. You need to import imp and then do imp.reload(foo) >>> import os >>> reload(os) Traceback (most recent call last): File "", line 1, in reload(os) NameError: name 'reload' is not defined >>> import imp >>> imp.reload(os) >>> I wonder why that was considered "a good idea"? Alan G. From quasipedia at gmail.com Sat Nov 27 18:12:59 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Sat, 27 Nov 2010 18:12:59 +0100 Subject: [Tutor] Python Exercise In-Reply-To: References: Message-ID: <20101127181259.770ea696@jabbar> On Sat, 27 Nov 2010 22:00:03 +0800 Kok Cheng Tan wrote: > I created this website for practising python online: > http://www.pyschools.com. Hope to gather feedback from people here > who are interesting in teaching and learning python. Here you go with the first suggestion: remove the need to log in! (Haven't really watched at the site content, given that I - like 99% of the Internet users - wouldn't bother to login just to roam around a site). Mac. From eike.welk at gmx.net Sat Nov 27 18:44:25 2010 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 27 Nov 2010 18:44:25 +0100 Subject: [Tutor] normalize an array In-Reply-To: References: Message-ID: <201011271845.38868.eike.welk@gmx.net> Hello John! On Friday 26.11.2010 23:23:51 Peter Otten wrote: > John wrote: > > I know this is a simple problem, but I want to do it the most > > efficient way (that is vectorized...) > > > > import numpy as np > > > > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) > > b = np.sum(a,axis=1) > > > > for i,elem in enumerate(a): > > a[i,:] = elem/b[i] > > > > suggestions? > > I'm not a numpy expert, but: > > (a.transpose()/np.sum(a, axis=1)).transpose() The underlying feature of Peter's solution is called broadcasting. For a detailed explanation look at: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html Eike. From patty at cruzio.com Sat Nov 27 18:17:21 2010 From: patty at cruzio.com (patty at cruzio.com) Date: Sat, 27 Nov 2010 09:17:21 -0800 (PST) Subject: [Tutor] Python Exercise In-Reply-To: <20101127181259.770ea696@jabbar> References: <20101127181259.770ea696@jabbar> Message-ID: Hi - I just wanted to add to Mac's comment. I don't have Google mail/gmail and don't want to create a mail account with them. I was also wondering if I should just try clicking on links anyway and changed my mind and exited. Regards, Patty > On Sat, 27 Nov 2010 22:00:03 +0800 > Kok Cheng Tan wrote: > >> I created this website for practising python online: >> http://www.pyschools.com. Hope to gather feedback from people here >> who are interesting in teaching and learning python. > > Here you go with the first suggestion: remove the need to log in! > (Haven't really watched at the site content, given that I - like 99% of > the Internet users - wouldn't bother to login just to roam around a > site). > > Mac. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From joel at joelschwartz.com Sat Nov 27 19:15:45 2010 From: joel at joelschwartz.com (Joel Schwartz) Date: Sat, 27 Nov 2010 10:15:45 -0800 Subject: [Tutor] Python Exercise In-Reply-To: <20101127181259.770ea696@jabbar> References: <20101127181259.770ea696@jabbar> Message-ID: <007201cb8e5f$1d256b60$6501a8c0@JLAPTOP> > -----Original Message----- > On Sat, 27 Nov 2010 22:00:03 +0800 > Kok Cheng Tan wrote: > > > I created this website for practising python online: > > http://www.pyschools.com. Hope to gather feedback from > people here who > > are interesting in teaching and learning python. > I logged in using my google account and the first page that came up was a ranking of competitors in the site's Python Tournament. I would recommend that you bring people to an introductory learning page after their first sign in (if you keep the sign-in requirement, which I also think is a bad idea) rather than a competition page--that is, unless you want to intimidate some (many?) beginning programmers into looking elsewhere. Joel From washakie at gmail.com Sat Nov 27 19:41:41 2010 From: washakie at gmail.com (John) Date: Sat, 27 Nov 2010 19:41:41 +0100 Subject: [Tutor] normalize an array In-Reply-To: <201011271845.38868.eike.welk@gmx.net> References: <201011271845.38868.eike.welk@gmx.net> Message-ID: Thank you both! Broadcasting is a concept I hadn't yet read about, but knew was important for efficient python programming... thanks for the link! On Sat, Nov 27, 2010 at 6:44 PM, Eike Welk wrote: > Hello John! > > On Friday 26.11.2010 23:23:51 Peter Otten wrote: >> John wrote: >> > I know this is a simple problem, but I want to do it the most >> > efficient way (that is vectorized...) >> > >> > import numpy as np >> > >> > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) >> > b = np.sum(a,axis=1) >> > >> > for i,elem in enumerate(a): >> > ? ? a[i,:] = elem/b[i] >> > >> > suggestions? >> >> I'm not a numpy expert, but: >> >> (a.transpose()/np.sum(a, axis=1)).transpose() > > The underlying feature of Peter's solution is called broadcasting. For a > detailed explanation look at: > http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html > > > Eike. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 From carroll at tjc.com Sat Nov 27 19:57:52 2010 From: carroll at tjc.com (Terry Carroll) Date: Sat, 27 Nov 2010 10:57:52 -0800 (PST) Subject: [Tutor] %T as a strftime format identifier In-Reply-To: <4CF0BCFB.6010301@pearwood.info> References: <4CF0BCFB.6010301@pearwood.info> Message-ID: On Sat, 27 Nov 2010, Steven D'Aprano wrote: > [steve at sylar ~]$ python2.5 > Python 2.5 (r25:51908, Nov 6 2007, 16:54:01) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import time >>>> time.strftime("%T") > '19:03:16' Interesting. On my Windows systems (Windows 7 and Vista, both Activestate Python 2.6.4.8) I get: >>> import time >>> time.strftime("%T") '' >>> On Linux (Ubuntu 10.04 and 10.10, Python 2.6.5) I get: >>> import time >>> time.strftime("%T") '10:54:54' >>> It may be an Activestate thing, hewing closely to the docs. From steve at pearwood.info Sat Nov 27 22:52:37 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 28 Nov 2010 08:52:37 +1100 Subject: [Tutor] Reload() in v3? WAS Re: IDEs In-Reply-To: References: <4CEA43B2.2030907@pearwood.info> Message-ID: <4CF17DA5.6050308@pearwood.info> Alan Gauld wrote: >>>> import os >>>> reload(os) > Traceback (most recent call last): > File "", line 1, in > reload(os) > NameError: name 'reload' is not defined >>>> > > Has reload been removed in V3? Not removed, just moved. >>> import imp >>> imp.reload The reason for moving it is that reload is quite simple-minded and full of traps for the unwary, and consequently isn't useful enough to be in the build-it namespace. > Whats the alternative? Does a repeated import auto-reload? Absolutely not! That would make importing much more expensive, and change the behaviour. import(module) caches the module in sys, so that subsequent imports are fast. -- Steven From tkokchen at gmail.com Sun Nov 28 03:43:52 2010 From: tkokchen at gmail.com (Kok Cheng Tan) Date: Sun, 28 Nov 2010 10:43:52 +0800 Subject: [Tutor] Python Exercise Message-ID: Hi, Thanks for the feedback. I will add a trial section that doesn't require login so that new visitors are able to give the website a try. Regards, Kok Cheng ---------- Forwarded message ---------- From: Date: Sun, Nov 28, 2010 at 2:41 AM Subject: Tutor Digest, Vol 81, Issue 105 To: tutor at python.org 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. Python Exercise (Kok Cheng Tan) 2. Reload() in v3? WAS Re: IDEs (Alan Gauld) 3. Re: Reload() in v3? WAS Re: IDEs (Alan Gauld) 4. Re: Python Exercise (Mac Ryan) 5. Re: normalize an array (Eike Welk) 6. Python Exercise (patty at cruzio.com) 7. Re: Python Exercise (Joel Schwartz) 8. Re: normalize an array (John) ---------------------------------------------------------------------- Message: 1 Date: Sat, 27 Nov 2010 22:00:03 +0800 From: Kok Cheng Tan To: tutor at python.org Subject: [Tutor] Python Exercise Message-ID: Content-Type: text/plain; charset=ISO-8859-1 Hi, I created this website for practising python online: http://www.pyschools.com. Hope to gather feedback from people here who are interesting in teaching and learning python. Regards, Kok Cheng ------------------------------ Message: 2 Date: Sat, 27 Nov 2010 15:04:57 -0000 From: "Alan Gauld" To: tutor at python.org Subject: [Tutor] Reload() in v3? WAS Re: IDEs Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "Steven D'Aprano" wrote > The other nine times out of ten *wink* I need to do debugging, and I > swap tabs and work in my interactive Python interpreter. > > import filename # first time only > reload(filename) # all subsequent times I'm working on the v3 version of my tutor and while testing some module code I tried to reload the module in IDLE... I got an error: >>> import os >>> reload(os) Traceback (most recent call last): File "", line 1, in reload(os) NameError: name 'reload' is not defined >>> Has reload been removed in V3? Whats the alternative? Does a repeated import auto-reload? I'm surprised and confused... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ Message: 3 Date: Sat, 27 Nov 2010 15:11:53 -0000 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] Reload() in v3? WAS Re: IDEs Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response "Alan Gauld" wrote > Has reload been removed in V3? > Whats the alternative? Does a repeated import auto-reload? > > I'm surprised and confused... Found it, its been moved into the imp module. You need to import imp and then do imp.reload(foo) >>> import os >>> reload(os) Traceback (most recent call last): File "", line 1, in reload(os) NameError: name 'reload' is not defined >>> import imp >>> imp.reload(os) >>> I wonder why that was considered "a good idea"? Alan G. ------------------------------ Message: 4 Date: Sat, 27 Nov 2010 18:12:59 +0100 From: Mac Ryan To: tutor at python.org Subject: Re: [Tutor] Python Exercise Message-ID: <20101127181259.770ea696 at jabbar> Content-Type: text/plain; charset=US-ASCII On Sat, 27 Nov 2010 22:00:03 +0800 Kok Cheng Tan wrote: > I created this website for practising python online: > http://www.pyschools.com. Hope to gather feedback from people here > who are interesting in teaching and learning python. Here you go with the first suggestion: remove the need to log in! (Haven't really watched at the site content, given that I - like 99% of the Internet users - wouldn't bother to login just to roam around a site). Mac. ------------------------------ Message: 5 Date: Sat, 27 Nov 2010 18:44:25 +0100 From: Eike Welk To: tutor at python.org Subject: Re: [Tutor] normalize an array Message-ID: <201011271845.38868.eike.welk at gmx.net> Content-Type: Text/Plain; charset="iso-8859-1" Hello John! On Friday 26.11.2010 23:23:51 Peter Otten wrote: > John wrote: > > I know this is a simple problem, but I want to do it the most > > efficient way (that is vectorized...) > > > > import numpy as np > > > > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) > > b = np.sum(a,axis=1) > > > > for i,elem in enumerate(a): > > a[i,:] = elem/b[i] > > > > suggestions? > > I'm not a numpy expert, but: > > (a.transpose()/np.sum(a, axis=1)).transpose() The underlying feature of Peter's solution is called broadcasting. For a detailed explanation look at: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html Eike. ------------------------------ Message: 6 Date: Sat, 27 Nov 2010 09:17:21 -0800 (PST) From: patty at cruzio.com To: tutor at python.org Subject: [Tutor] Python Exercise Message-ID: Content-Type: text/plain;charset=iso-8859-15 Hi - I just wanted to add to Mac's comment. I don't have Google mail/gmail and don't want to create a mail account with them. I was also wondering if I should just try clicking on links anyway and changed my mind and exited. Regards, Patty > On Sat, 27 Nov 2010 22:00:03 +0800 > Kok Cheng Tan wrote: > >> I created this website for practising python online: >> http://www.pyschools.com. Hope to gather feedback from people here >> who are interesting in teaching and learning python. > > Here you go with the first suggestion: remove the need to log in! > (Haven't really watched at the site content, given that I - like 99% of > the Internet users - wouldn't bother to login just to roam around a > site). > > Mac. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ------------------------------ Message: 7 Date: Sat, 27 Nov 2010 10:15:45 -0800 From: "Joel Schwartz" To: Subject: Re: [Tutor] Python Exercise Message-ID: <007201cb8e5f$1d256b60$6501a8c0 at JLAPTOP> Content-Type: text/plain; charset="us-ascii" > -----Original Message----- > On Sat, 27 Nov 2010 22:00:03 +0800 > Kok Cheng Tan wrote: > > > I created this website for practising python online: > > http://www.pyschools.com. Hope to gather feedback from > people here who > > are interesting in teaching and learning python. > I logged in using my google account and the first page that came up was a ranking of competitors in the site's Python Tournament. I would recommend that you bring people to an introductory learning page after their first sign in (if you keep the sign-in requirement, which I also think is a bad idea) rather than a competition page--that is, unless you want to intimidate some (many?) beginning programmers into looking elsewhere. Joel ------------------------------ Message: 8 Date: Sat, 27 Nov 2010 19:41:41 +0100 From: John To: Eike Welk Cc: tutor at python.org Subject: Re: [Tutor] normalize an array Message-ID: Content-Type: text/plain; charset=ISO-8859-1 Thank you both! Broadcasting is a concept I hadn't yet read about, but knew was important for efficient python programming... thanks for the link! On Sat, Nov 27, 2010 at 6:44 PM, Eike Welk wrote: > Hello John! > > On Friday 26.11.2010 23:23:51 Peter Otten wrote: >> John wrote: >> > I know this is a simple problem, but I want to do it the most >> > efficient way (that is vectorized...) >> > >> > import numpy as np >> > >> > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) >> > b = np.sum(a,axis=1) >> > >> > for i,elem in enumerate(a): >> > ? ? a[i,:] = elem/b[i] >> > >> > suggestions? >> >> I'm not a numpy expert, but: >> >> (a.transpose()/np.sum(a, axis=1)).transpose() > > The underlying feature of Peter's solution is called broadcasting. For a > detailed explanation look at: > http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html > > > Eike. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Python 2.6 PIL 1.1.6 Mailman 2.1.9 Postfix 2.4.5 Procmail v3.22 2001/09/10 Basemap: 1.0 Matplotlib: 1.0.0 ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 81, Issue 105 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexandertwin at hotmail.com Sun Nov 28 03:59:59 2010 From: alexandertwin at hotmail.com (Mauricio Alejandro) Date: Sat, 27 Nov 2010 22:59:59 -0400 Subject: [Tutor] Is Python useful for emulating? Message-ID: I never created any emulator before, and i'm learning C++. Let's say i try to write an emulator for... SNES. Would Python be fast enough? Also, any useful advice you can give me? Things i should know about before i start coding? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sun Nov 28 04:05:44 2010 From: python at bdurham.com (python at bdurham.com) Date: Sat, 27 Nov 2010 22:05:44 -0500 Subject: [Tutor] %T as a strftime format identifier In-Reply-To: References: <4CF0BCFB.6010301@pearwood.info> Message-ID: <1290913544.15485.1407476373@webmail.messagingengine.com> 32-bit Python 2.7 for Windows: >>> import time >>> time.strftime("%T") Traceback (most recent call last): File "", line 1, in time.strftime("%T") ValueError: Invalid format string Malcolm From wprins at gmail.com Sun Nov 28 04:26:41 2010 From: wprins at gmail.com (Walter Prins) Date: Sun, 28 Nov 2010 03:26:41 +0000 Subject: [Tutor] Is Python useful for emulating? In-Reply-To: References: Message-ID: On 28 November 2010 02:59, Mauricio Alejandro wrote: > I never created any emulator before, and i'm learning C++. Let's say i try > to write an emulator for... SNES. Would Python be fast enough? > Also, any useful advice you can give me? Things i should know about before > i start coding? > Because of the performance requirements generally applciable to emulating a games console, I would not think to write an emulator in native Python. However you can probably write the main parts that need performance as C based Python modules, and write "the rest" in Python. (Whether "the rest" is substantial enough to warrant it is hard to say.) This is the route taken by any Python modules/applications that have critical performance requirements. As for useful advice, I don't want to put you off but writing a complete console emulator is not a trivial project by any stretch of the imagination, and you'll also need to have very detailed specs about the SNES's hardware (CPU, video hardware, memory and IO maps, sound hardware etc), as well as have copies of its firmware (BIOS/ROMS etc) in order to even be able to begin to work on such a project. Additionally, there's already (or there was several years ago) several SNES emulators and doing another one just for the sake of it, well, is it really worth it? Maybe something a little more accessible might be to implement a MIPS CPU emulator, something like this: http://weblogs.mozillazine.org/roc/archives/2010/11/implementing_a.html or this: http://codu.org/projects/trac/jsmips/ And then see how fast you can make that without resorting to C, like the guy above did in the browser. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranceh at gmail.com Sun Nov 28 05:55:47 2010 From: ranceh at gmail.com (Rance Hall) Date: Sat, 27 Nov 2010 22:55:47 -0600 Subject: [Tutor] string case manipulation in python 3.x Message-ID: I need to do some case manipulation that I don't see in the documented string functions. I want to make sure that user input meets a certain capitalization scheme, for example, if user input is a name, then the first letter of each word in the name is upper case, and the rest are lower. I know how to force the upper and lower cases with string.lower() and friends. and I could even do a string.split() on the spaces in the names to break the name into pieces. I don't see an obvious way to do this. what I've come up with so far is to do something like this. break the name into pieces force each piece to be lower case replace the first letter in each word with a uppercase version of whats there already. Problems with this approach as I see them: The built in split function will create undesirable results for names that contain suffixes like Jr. etc. I'm not entirely sure how to replace the string with an uppercase first letter on a per word basis. Whats the "right" way to do something like this? Thanks Rance From hugo.yoshi at gmail.com Sun Nov 28 06:10:10 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 28 Nov 2010 06:10:10 +0100 Subject: [Tutor] string case manipulation in python 3.x In-Reply-To: References: Message-ID: On Sun, Nov 28, 2010 at 5:55 AM, Rance Hall wrote: > I need to do some case manipulation that I don't see in the documented > string functions. > > I want to make sure that user input meets a certain capitalization > scheme, for example, if user input is a name, then the first letter of > each word in the name is upper case, and the rest are lower. > > I know how to force the upper and lower cases with string.lower() and friends. > > and I could even do a string.split() on the spaces in the names to > break the name into pieces. > > I don't see an obvious way to do this. > > what I've come up with so far is to do something like this. > > break the name into pieces > force each piece to be lower case > replace the first letter in each word with a uppercase version of > whats there already. > > Problems with this approach as I see them: > The built in split function will create undesirable results for names > that contain suffixes like Jr. ?etc. > I'm not entirely sure how to replace the string with an uppercase > first letter on a per word basis. > > Whats the "right" way to do something like this? > I'd say split the string, call the capitalize method on each part, then join back together. Hugo From waynejwerner at gmail.com Sun Nov 28 07:39:36 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 28 Nov 2010 00:39:36 -0600 Subject: [Tutor] string case manipulation in python 3.x In-Reply-To: References: Message-ID: On Sat, Nov 27, 2010 at 10:55 PM, Rance Hall wrote: > I need to do some case manipulation that I don't see in the documented > string functions. > > I want to make sure that user input meets a certain capitalization > scheme, for example, if user input is a name, then the first letter of > each word in the name is upper case, and the rest are lower. > So for instance, something like this? In [3]: badcasename = 'eRic SPAM IDle jr.' In [4]: badcasename.title() Out[4]: 'Eric Spam Idle Jr.' Problems with this approach as I see them: > The built in split function will create undesirable results for names > that contain suffixes like Jr. etc. > If you want it to behave differently for suffixes, I'm not sure how to do that... > I'm not entirely sure how to replace the string with an uppercase > first letter on a per word basis. > mystring = mystring.title() > Whats the "right" way to do something like this? gaining more familiarity with the builtin functions ;) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Nov 28 10:14:01 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 28 Nov 2010 03:14:01 -0600 Subject: [Tutor] Is Python useful for emulating? In-Reply-To: References: Message-ID: It probably won't be fast enough. I wrote an NES emu in python and I ran into a lot of performance issues. If you're new to emu scene, start with David winters' doc and write a chip-8 emu. I will help you learn the structure and process of writing an emulator. Then reimplememt it in c afterward. I'm actually in th midst of writing an introductory emulation ebook that follows a similar course. Another consideration that I will explore myself is languages like rpython or Pyrex that are similar to python but can be compiled down for speed. Might be worth a look for you too. Good luck, and if you need any mentorship or have any questions about starting out writing emulators just drop me a line! ----------------------------- Sent from a mobile device with a bad e-mail client. ----------------------------- On Nov 27, 2010, at 8:59 PM, Mauricio Alejandro wrote: > I never created any emulator before, and i'm learning C++. Let's say i try to write an emulator for... SNES. Would Python be fast enough? > Also, any useful advice you can give me? Things i should know about before i start coding? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From stefan_ml at behnel.de Sun Nov 28 12:43:30 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 28 Nov 2010 12:43:30 +0100 Subject: [Tutor] Is Python useful for emulating? In-Reply-To: References: Message-ID: Mauricio Alejandro, 28.11.2010 03:59: > I never created any emulator before, and i'm learning C++. Let's say i try to write an emulator for... SNES. Would Python be fast enough? > Also, any useful advice you can give me? Things i should know about before i start coding? If you want to write something like this from scratch, I would suggest you look at two tools: pygame and Cython. pygame is a very useful tool for writing graphics games. Cython is a way to speed up performance critical Python code by translating it to fast C code. You shouldn't run into that many performance problems if you use both, but you'd likely be able to write your code a lot quicker than in C or C++. One important advice: write your code in Python first, then benchmark it and move only the performance critical parts of it into Cython. The higher level you stay, the simpler your code will remain. Stefan From steve at pearwood.info Sun Nov 28 14:55:32 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Nov 2010 00:55:32 +1100 Subject: [Tutor] string case manipulation in python 3.x In-Reply-To: References: Message-ID: <4CF25F54.7010502@pearwood.info> Rance Hall wrote: > I need to do some case manipulation that I don't see in the documented > string functions. > > I want to make sure that user input meets a certain capitalization > scheme, for example, if user input is a name, then the first letter of > each word in the name is upper case, and the rest are lower. > > I know how to force the upper and lower cases with string.lower() and friends. Then you should know about str.capitalize and str.title: >>> s = "joHN clEeSE" >>> s.capitalize() 'John cleese' >>> s.title() 'John Cleese' It looks like you want str.title, with the exception that numeric suffixes will need to be handled specially: >>> "fred smith III".title() 'Fred Smith Iii' But see below. > and I could even do a string.split() on the spaces in the names to > break the name into pieces. > > I don't see an obvious way to do this. > > what I've come up with so far is to do something like this. > > break the name into pieces > force each piece to be lower case > replace the first letter in each word with a uppercase version of > whats there already. > > Problems with this approach as I see them: > The built in split function will create undesirable results for names > that contain suffixes like Jr. etc. Why? I don't see how it would, unless people leave out the space between their name and suffix. But then, if they leave out the space between their first name and surname, you have the same problem. > I'm not entirely sure how to replace the string with an uppercase > first letter on a per word basis. The right way is with the capitalize or title methods, but the generic way is illustrated by this similar function: def reverse_capitalize(s): # "abcd" -> "aBCD" if s: return s[0].lower() + s[1:].upper() else: # empty string return s Which brings back to the issue of Roman number suffixes. You can deal with them like this: def capitalize(s): s = s.title() words = s.split() suffixes = 'ii iii iv v vi vii viii ix x xi xii'.split() # Twelve generations should be enough. If not, add more. if words[-1].lower() in suffixes: words[-1] = words[-1].upper() return " ".join(words) return s > Whats the "right" way to do something like this? Another approach would be the old-fashioned way: change the string character by character. # change in place letters = list(name) for i, c in letters: letters[i] = do_something_with(c) name = ''.join(letters) -- Steven From jocjo.s at verizon.net Sun Nov 28 16:55:19 2010 From: jocjo.s at verizon.net (John Smith) Date: Sun, 28 Nov 2010 09:55:19 -0600 Subject: [Tutor] Pyserial and invalid handle Message-ID: <4CF27B67.8000803@verizon.net> Can anybody tell me why the handle below is invalid? I'm running Win7. TIA, John Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import serial >>> ser = serial.Serial('com1', timeout = 5) >>> x = ser.read() Traceback (most recent call last): File "", line 1, in x = ser.read() File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 236, in read raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) SerialException: ReadFile failed ([Error 6] The handle is invalid.) >>> From josep.m.fontana at gmail.com Sun Nov 28 17:27:45 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Sun, 28 Nov 2010 17:27:45 +0100 Subject: [Tutor] A regular expression problem Message-ID: I'm trying to use regular expressions to extract strings that match certain patterns in a collection of texts. Basically these texts are edited versions of medieval manuscripts that use certain symbols to mark information that is useful for filologists. I'm interested in isolating words that have some non alpha-numeric symbol attached to the beginning or the end of the word or inserted in them. Here are some examples: '?de' ,'?orden', '?Don', '?II?', 'que?l', 'Rey?' I'm using some modules from a package called NLTK but I think my problem is related to some misunderstanding of how regular expressions work. Here's what I do. This was just a first attempt to get strings starting with a non alpha-numeric symbol. If this had worked, I would have continued to build the regular expression to get words with non alpha-numeric symbols in the middle and in the end. Alas, even this first attempt didn't work. --------- with open('output_tokens.txt', 'a') as out_tokens: with open('text.txt', 'r') as in_tokens: t = RegexpTokenizer('[^a-zA-Z\s0-9]+\w+\S') output = t.tokenize(in_tokens.read()) for item in output: out_tokens.write(" %s" % (item)) -------- What puzzles me is that I get some results that don't make much sense given the regular expression. Here's some excerpt from the text I'm processing: --------------- " %P?g. 87 &L-[LIBRO VII. DE O?RSINO]&L+ &// ?Comeza el ?VII? libro, que es de O?rsino las b?stias. &// ?Canto F?lix ha tomado prenda del phisoloffo, el [?] ?II? h?mnes, e ellos" ---------------- Here's the relevant part of the output file ('output_tokens.txt'): ---------- " I need a function that will import a module (using __import__) from only one specific location on my filesystem. Name collisions are possible. To avoid this I could *temporarily* modify sys.path for the operation so that it contains only the path that I want to work from. console example: >>> sys_path = sys.path >>> sys.path = ["/cgi-bin/libraries/python"] >>> sys.path ['/cgi-bin/libraries/python'] >>> sys.path = sys_path >>> sys.path ## original sys.path I don't want to create something that could bite me later. Documentation on sys.path that I have found does not address *removing* items from sys.path or completely changing it. Any caveats or comments on this procedure? TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From evert.rol at gmail.com Sun Nov 28 17:53:33 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 28 Nov 2010 17:53:33 +0100 Subject: [Tutor] temporarily modifying sys.path In-Reply-To: <20101128163332.GA1808@johnsons-web.com> References: <20101128163332.GA1808@johnsons-web.com> Message-ID: <43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> > I need a function that will import a module (using __import__) from > only one specific location on my filesystem. Name collisions are > possible. To avoid this I could *temporarily* modify sys.path for > the operation so that it contains only the path that I want > to work from. Just curious, but could the imp module help you? imp.find_module appears to look on a specific path if you specify it, and it seems you have the path available here. From there imp.load_module perhaps. I have very little experience with imp, but I'm wondering if it could help you without the necessity of modifying sys.path. Though I do think you can temporarily make a copy of sys.path, then modify sys.path, then after the import reassign sys.path to your temp variable. But try the above route first. Evert > console example: >>>> sys_path = sys.path >>>> sys.path = ["/cgi-bin/libraries/python"] >>>> sys.path > ['/cgi-bin/libraries/python'] >>>> sys.path = sys_path >>>> sys.path > ## original sys.path > > I don't want to create something that could bite me later. > Documentation on sys.path that I have found does not address > *removing* items from sys.path or completely changing it. > > Any caveats or comments on this procedure? > TIA > -- > Tim > tim at johnsons-web.com or akwebsoft.com > http://www.akwebsoft.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From emile at fenx.com Sun Nov 28 17:57:15 2010 From: emile at fenx.com (Emile van Sebille) Date: Sun, 28 Nov 2010 08:57:15 -0800 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: <4CF27B67.8000803@verizon.net> References: <4CF27B67.8000803@verizon.net> Message-ID: On 11/28/2010 7:55 AM John Smith said... > > Can anybody tell me why the handle below is invalid? I'm running Win7. > > TIA, > John > > > Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] > on win32 > Type "copyright", "credits" or "license()" for more information. > > >>> import serial > >>> ser = serial.Serial('com1', timeout = 5) What do you get when you add 'print ser' here? The docs at http://pyserial.sourceforge.net/shortintro.html show you should get something like Serial(port='COM1', baudrate=19200, bytesize=8, parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) So if you're getting an invalid handle error I'd expect you'd get something different. Emile > >>> x = ser.read() > > Traceback (most recent call last): > File "", line 1, in > x = ser.read() > File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 236, in > read > raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) > SerialException: ReadFile failed ([Error 6] The handle is invalid.) > >>> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From evert.rol at gmail.com Sun Nov 28 18:03:07 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 28 Nov 2010 18:03:07 +0100 Subject: [Tutor] A regular expression problem In-Reply-To: References: Message-ID: <5EDAB9A9-F12D-4519-B812-E8323C0D32ED@gmail.com> > Here's what I do. This was just a first attempt to get strings > starting with a non alpha-numeric symbol. If this had worked, I would > have continued to build the regular expression to get words with non > alpha-numeric symbols in the middle and in the end. Alas, even this > first attempt didn't work. > > --------- > with open('output_tokens.txt', 'a') as out_tokens: > with open('text.txt', 'r') as in_tokens: > t = RegexpTokenizer('[^a-zA-Z\s0-9]+\w+\S') > output = t.tokenize(in_tokens.read()) > for item in output: > out_tokens.write(" %s" % (item)) > > -------- > > What puzzles me is that I get some results that don't make much sense > given the regular expression. Here's some excerpt from the text I'm > processing: > > --------------- > " > > %P?g. 87 > &L-[LIBRO VII. DE O?RSINO]&L+ &// > ?Comeza el ?VII? libro, que es de O?rsino las b?stias. &// > ?Canto F?lix ha tomado prenda del phisoloffo, el [?] ?II? h?mnes, e ellos" > ---------------- > > > Here's the relevant part of the output file ('output_tokens.txt'): > > ---------- > " ?Comenza ?VII? ?stias. ?Canto ?lix ?II? ?mnes" > ----------- > > If you notice, there are some words that have an accented character > that get treated in a strange way: all the characters that don't have > a tilde get deleted and the accented character behaves as if it were a > non alpha-numeric symbol. > > What is going on? What am I doing wrong? I don't know for sure, but I would hazard a guess that you didn't specify unicode for the regular expression: character classes like \w and \s are dependent on your LOCALE settings. A flag like re.UNICODE could help, but I don't know if Regexptokenizer accepts that. It would also appear that you could get a long way with the builtin re.split function, and supply the flag inside that function; no need then or Regexptokenizer. Your tokenizer just appears to split on the tokens you specify. Lastly, an output convenience: output.write(' '.join(list(output))) instead of the for-loop. (I'm casting output to a list here, since I don't know whether output is a list or an iterator.) Let us know how if UNICODE (or other LOCALE settings) can solve your problem. Cheers, Evert From steve at pearwood.info Sun Nov 28 18:14:01 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Nov 2010 04:14:01 +1100 Subject: [Tutor] A regular expression problem In-Reply-To: References: Message-ID: <4CF28DD9.3090808@pearwood.info> Josep M. Fontana wrote: > I'm trying to use regular expressions to extract strings that match > certain patterns in a collection of texts. Basically these texts are > edited versions of medieval manuscripts that use certain symbols to > mark information that is useful for filologists. > > I'm interested in isolating words that have some non alpha-numeric > symbol attached to the beginning or the end of the word or inserted in > them. Here are some examples: > > '?de' ,'?orden', '?Don', '?II?', 'que?l', 'Rey?' Have you considered just using the isalnum() method? >>> '?de'.isalnum() False You will have to split your source text into individual words, then isolate those where word.isalnum() returns False. > I'm using some modules from a package called NLTK but I think my > problem is related to some misunderstanding of how regular expressions > work. The first thing to do is to isolate the cause of the problem. In your code below, you do four different things. In no particular order: 1 open and read an input file; 2 open and write an output file; 3 create a mysterious "RegexpTokenizer" object, whatever that is; 4 tokenize the input. We can't run your code because: 1 we don't have access to your input file; 2 most of us don't have the NLTK package; 3 we don't know what RegexTokenizer does; 4 we don't know what tokenizing does. Makes it hard to solve the problem for you, although I'm willing to make a few wild guesses (see below). The most important debugging skill you can learn is to narrow the problem down to the smallest possible piece of code that gives you the wrong answer. This will help you solve the problem yourself, and it will also help others help you. Can you demonstrate the problem in a couple of lines of code that doesn't rely on external files, packages, or other code we don't have? > Here's what I do. This was just a first attempt to get strings > starting with a non alpha-numeric symbol. If this had worked, I would > have continued to build the regular expression to get words with non > alpha-numeric symbols in the middle and in the end. Alas, even this > first attempt didn't work. > > --------- > with open('output_tokens.txt', 'a') as out_tokens: > with open('text.txt', 'r') as in_tokens: > t = RegexpTokenizer('[^a-zA-Z\s0-9]+\w+\S') > output = t.tokenize(in_tokens.read()) > for item in output: > out_tokens.write(" %s" % (item)) Firstly, it's best practice to write regexes as "raw strings" by preceding them with an r. Instead of '[^a-zA-Z\s0-9]+\w+\S' you should write: r'[^a-zA-Z\s0-9]+\w+\S' Notice that the r is part of the delimiter (r' and ') and not the contents. This instructs Python to ignore the special meaning of backslashes. In this specific case, it won't make any difference, but it will make a big difference in other regexes. Your regex says to match: - one or more characters that aren't letters a...z (in either case), space or any digit (note that this is *not* the same as characters that aren't alphanum); - followed by one or more alphanum character; - followed by exactly one character that is not whitespace. I'm guessing the "not whitespace" is troublesome -- it will match characters like ? because it isn't whitespace. I'd try this: # untested \b.*?\W.*?\b which should match any word with a non-alphanumeric character in it: - \b ... \b matches the start and end of the word; - .*? matches zero or more characters (as few as possible); - \W matches a single non-alphanumeric character. So putting it all together, that should match a word with at least one non-alphanumeric character in it. (Caution: if you try this, you *must* use a raw string, otherwise you will get completely wrong results.) > What puzzles me is that I get some results that don't make much sense > given the regular expression. Well, I don't know how RegexTokenizer is supposed to work, so anything I say will be guesswork :) [...] > If you notice, there are some words that have an accented character > that get treated in a strange way: all the characters that don't have > a tilde get deleted and the accented character behaves as if it were a > non alpha-numeric symbol. Your regex matches if the first character isn't a space, a digit, or a a-zA-Z. Accented characters aren't a-z or A-Z, and therefore will match. -- Steven From jocjo.s at verizon.net Sun Nov 28 18:08:08 2010 From: jocjo.s at verizon.net (John Smith) Date: Sun, 28 Nov 2010 11:08:08 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> Message-ID: <4CF28C78.5050304@verizon.net> On 11/28/2010 10:57 AM, Emile van Sebille wrote: > On 11/28/2010 7:55 AM John Smith said... >> >> Can anybody tell me why the handle below is invalid? I'm running Win7. >> >> TIA, >> John >> >> >> Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] >> on win32 >> Type "copyright", "credits" or "license()" for more information. >> >> >>> import serial >> >>> ser = serial.Serial('com1', timeout = 5) > > What do you get when you add 'print ser' here? The docs at > http://pyserial.sourceforge.net/shortintro.html show you should get > something like > > Serial(port='COM1', baudrate=19200, bytesize=8, > parity='N', stopbits=1, timeout=None, xonxoff=0, rtscts=0) > > So if you're getting an invalid handle error I'd expect you'd get > something different. > > Emile Hi, Emile - Okay. Here it is: >>> print ser Serial(port='COM1', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=5, xonxoff=False, rtscts=False, dsrdtr=False) >>> Thanks. John From tim at johnsons-web.com Sun Nov 28 19:36:36 2010 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 28 Nov 2010 09:36:36 -0900 Subject: [Tutor] temporarily modifying sys.path In-Reply-To: <43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> References: <20101128163332.GA1808@johnsons-web.com> <43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> Message-ID: <20101128183636.GB1808@johnsons-web.com> * Evert Rol [101128 07:56]: > > I need a function that will import a module (using __import__) from > > only one specific location on my filesystem. Name collisions are > > possible. To avoid this I could *temporarily* modify sys.path for > > the operation so that it contains only the path that I want > > to work from. > Just curious, but could the imp module help you? imp.find_module > appears to look on a specific path if you specify it, and it seems > you have the path available here. From there imp.load_module > perhaps. I have very little experience with imp, but I'm > wondering if it could help you without the necessity of modifying > sys.path. > Though I do think you can temporarily make a copy of sys.path, > then modify sys.path, then after the import reassign sys.path to > your temp variable. But try the above route first. I'll be darned. I never even heard of that module, but I just did an import and looked at the docs. I *will* give that a try. Thanks for the tip! cheers -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From alan.gauld at btinternet.com Mon Nov 29 01:05:08 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Nov 2010 00:05:08 -0000 Subject: [Tutor] temporarily modifying sys.path References: <20101128163332.GA1808@johnsons-web.com><43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> <20101128183636.GB1808@johnsons-web.com> Message-ID: "Tim Johnson" wrote >> Just curious, but could the imp module help you? imp.find_module > I'll be darned. I never even heard of that module, but I just > did an import and looked at the docs. I *will* give that a try. I think its new in Python v3... Compare my recent post about reload() - now a part of imp... Alan G. From andrejeyarajan at rogers.com Mon Nov 29 01:50:21 2010 From: andrejeyarajan at rogers.com (Andre Jeyarajan) Date: Sun, 28 Nov 2010 16:50:21 -0800 (PST) Subject: [Tutor] REport Card Question Message-ID: <665845.91144.qm@web88202.mail.re2.yahoo.com> Write a code that will take an input from a user (numerical grade) and convert their numerical grade into a letter grade that is accompanied by a ?smart? statement.?def grade_score(grade): ? ? if grade >=95 and grade <= 100:? ? ? ? ? print 'A+, Excellent'? ? ? elif grade >=85 and grade < 95: ? ? ? ? print 'A, Good Work' ? ? elif grade >=80 and grade < 85: ? ? ? ? print 'A-, Good Work, but you could do better' ? ? elif grade >=75 and grade < 80: ? ? ? ? print 'B, Try Harder' ? ? elif grade >=70 and grade < 75: ? ? ? ? print 'B-, Try Harder' ? ? elif grade >=65 and grade < 70:? ? ? ? ? print 'C, Work Harder' ? ? elif grade >=60 and grade < 65: ? ? ? ? print 'C-, Work Harder'? ? ? elif grade >=55 and grade < 60: ? ? ? ? print 'D, Study Harder' ? ? elif grade >=50 and grade < 55: ? ? ? ? print 'D-, Study Harder' ? ? elif grade >=0 and grade < 50: ? ? ? ? print 'F, You Failed' ? ? else:? ? ? ? ? print "You did not enter an appropriate value, please run the program again!"? grade = raw_input('Put your grade here:?) grade_score() Put your grade here:77 Traceback (most recent call last): ? File "/Users/andre.jeyarajan/Documents/workspace/Chapter 5 Problems/src/ReportCardQuestion.py", line 28, in ? ? grade_score() TypeError: grade_score() takes exactly 1 argument (0 given) Can you help and tell me why it doesn?t work? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Mon Nov 29 02:11:02 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 28 Nov 2010 19:11:02 -0600 Subject: [Tutor] REport Card Question In-Reply-To: <665845.91144.qm@web88202.mail.re2.yahoo.com> References: <665845.91144.qm@web88202.mail.re2.yahoo.com> Message-ID: On Sun, Nov 28, 2010 at 6:50 PM, Andre Jeyarajan wrote: > Write a code that will take an input from a user (numerical grade) and > convert their numerical grade into a letter grade that is accompanied by a > ?smart? statement. > > def grade_score(grade): > > if grade >=95 and grade <= 100: > > print 'A+, Excellent' > > elif grade >=85 and grade < 95: > > print 'A, Good Work' > > elif grade >=80 and grade < 85: > > print 'A-, Good Work, but you could do better' > > elif grade >=75 and grade < 80: > > print 'B, Try Harder' > > elif grade >=70 and grade < 75: > > print 'B-, Try Harder' > > elif grade >=65 and grade < 70: > > print 'C, Work Harder' > > elif grade >=60 and grade < 65: > > print 'C-, Work Harder' > > elif grade >=55 and grade < 60: > > print 'D, Study Harder' > > elif grade >=50 and grade < 55: > > print 'D-, Study Harder' > > elif grade >=0 and grade < 50: > > print 'F, You Failed' > > else: > > print "You did not enter an appropriate value, please run the > program again!" > > > grade = raw_input('Put your grade here:?) > > > grade_score() > > > Put your grade here:77 > > Traceback (most recent call last): > > File "/Users/andre.jeyarajan/Documents/workspace/Chapter 5 > Problems/src/ReportCardQuestion.py", line 28, in > > grade_score() > > This line tells you why it doesn't work: > TypeError: grade_score() takes exactly 1 argument (0 given) > Are you familiar with functions? When you define the function you define it as taking one parameter: def grade_score(grade): # Code here but then when you call it: grade_score() you don't give it any parameters (or arguments). The traceback tells you that you need to provide it 1 argument and that you gave it 0 instead. If you called grade_score(3, 150) you would get a similar error, only it would say (2 given) instead. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrejeyarajan at rogers.com Mon Nov 29 02:33:45 2010 From: andrejeyarajan at rogers.com (Andre Jeyarajan) Date: Sun, 28 Nov 2010 17:33:45 -0800 (PST) Subject: [Tutor] Temperature Scales Message-ID: <471262.24467.qm@web88203.mail.re2.yahoo.com> ?Write two functions that will convert temperatures back and forth from the Celsius and Fahrenheit temperature scales (using raw_input) def C_F(x): ? ? y = (x-32)*(5.0/9) ? ? print y def F_C(x): ? ? y = (x*9.0/5)+32 ? ? print y I have created the two functions but I don?t know what to do from here. Can you help? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Nov 29 03:06:06 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 29 Nov 2010 02:06:06 +0000 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: <4CF27B67.8000803@verizon.net> References: <4CF27B67.8000803@verizon.net> Message-ID: John, On 28 November 2010 15:55, John Smith wrote: > Python 2.7 (r27:82525, Jul 4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] > on win32 > Type "copyright", "credits" or "license()" for more information. > > >>> import serial > >>> ser = serial.Serial('com1', timeout = 5) > >>> x = ser.read() > > Traceback (most recent call last): > File "", line 1, in > x = ser.read() > File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 236, in > read > raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) > SerialException: ReadFile failed ([Error 6] The handle is invalid.) > >>> > Ugh, you're probably not going to like this. I've done some googling and it appears this may be a 64-bit issue with the "ctypes" module... apparently "64-bit ctypes can only import 64-bit libraries". See here: http://ur.ly/vSMQ Then again, it also seems to be an open issue on the PySerial bug tracker: http://ur.ly/vZNL Note, the above ticket suggests that PySerial 2.4 works ok (impliedly even on 64-bit XP, so I imagine also on Windows 7.) You should be able to try this out by downloading the 2.4 version instead and installing it in the same way you did the 2.5 version. In any case, it might be an idea to post a report/add a comment to that bug report as well to maybe help get this issue resolved. Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Mon Nov 29 03:16:42 2010 From: wprins at gmail.com (Walter Prins) Date: Mon, 29 Nov 2010 02:16:42 +0000 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> Message-ID: Also note this link: http://ur.ly/vVU9 It confirms that PySerial 2.4 works fine on Windows 7 64 bit. (I've also just downloaded and checked that installing pyserial 2.4 replaces the existing pyserial and it does on my Python installation.) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Mon Nov 29 03:23:59 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 28 Nov 2010 21:23:59 -0500 Subject: [Tutor] Temperature Scales In-Reply-To: <471262.24467.qm@web88203.mail.re2.yahoo.com> References: <471262.24467.qm@web88203.mail.re2.yahoo.com> Message-ID: <4CF30EBF.9040506@aim.com> On 11/28/2010 8:33 PM, Andre Jeyarajan wrote: > > Write two functions that will convert temperatures back and forth from > the Celsius and Fahrenheit temperature scales (using raw_input) > > > def C_F(x): > > y = (x-32)*(5.0/9) > > print y > > > def F_C(x): > > y = (x*9.0/5)+32 > > print y > > > I have created the two functions but I don?t know what to do from here. > > > Can you help? > > > Thanks > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I get the curious feeling this is homework. You would need to do one of two things: Pass the output of raw_input as an argument or rewrite your functions so that instead of taking the temperature as a parameter, it asks in the body of the function for a temperature. In either case, you will run into a little TypeError, easily fixed however. HTH, ~Corey Richardson -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Mon Nov 29 03:27:19 2010 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 28 Nov 2010 17:27:19 -0900 Subject: [Tutor] temporarily modifying sys.path In-Reply-To: References: <20101128163332.GA1808@johnsons-web.com> <43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> <20101128183636.GB1808@johnsons-web.com> Message-ID: <20101129022719.GD1808@johnsons-web.com> * Alan Gauld [101128 15:17]: > > "Tim Johnson" wrote > >>> Just curious, but could the imp module help you? imp.find_module > >> I'll be darned. I never even heard of that module, but I just >> did an import and looked at the docs. I *will* give that a try. > > I think its new in Python v3... Hello Alan: Actually, I am using 2.6.5 on linux ubuntu 10.04 and imp is provided. > Compare my recent post about reload() - now a part of imp... will do. thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From carroll at tjc.com Mon Nov 29 04:18:59 2010 From: carroll at tjc.com (Terry Carroll) Date: Sun, 28 Nov 2010 19:18:59 -0800 (PST) Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: References: Message-ID: On Thu, 25 Nov 2010, Alan Gauld wrote: > "Yves Dextraze" wrote >> Sent from my iPod > > There is no mention on Amazon of any new editions and they usually announce > several months in advance... > > A pity a new Tkinter book using Tix and ttk instead of PMW would be a really > useful resource! Odd -- Yves's note shows up on my system as a reply in a long-dormant thread from March 2009. From wescpy at gmail.com Mon Nov 29 06:10:48 2010 From: wescpy at gmail.com (wesley chun) Date: Sun, 28 Nov 2010 21:10:48 -0800 Subject: [Tutor] Python and Tkinter Programming by Grayson--New Version? In-Reply-To: References: Message-ID: On Sun, Nov 28, 2010 at 7:18 PM, Terry Carroll wrote: > On Thu, 25 Nov 2010, Alan Gauld wrote: >> "Yves Dextraze" wrote >>> Sent from my iPod >> >> There is no mention on Amazon of any new editions and they usually >> announce several months in advance... >> >> A pity a new Tkinter book using Tix and ttk instead of PMW would be a >> really useful resource! > > Odd -- Yves's note shows up on my system as a reply in a long-dormant thread > from March 2009. i agree with alan's sentiment though. perhaps someone just brought up a server recently (where this msg was in the "outbox")? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 ? ? http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sharky5000 at comcast.net Mon Nov 29 06:57:06 2010 From: sharky5000 at comcast.net (Mary) Date: Mon, 29 Nov 2010 00:57:06 -0500 Subject: [Tutor] noob Message-ID: <572B95FE00A34E9CB35D1C3DE04B482E@toy> Dear Tutors: Thank you for your time.I am trying to do first assignment (ps1a+b) onMIT open study, finding the 1000th prime in part a and doing something with import.math and logs in part b, but I'm not there yet. The little build i did to find primes does fine until, for some reason, 95 shows up, and later other multiples of 5 jump into the mix without being invited.I end up almost 200 primes off by the 1000 count. Is it me? Have uninstalled and reinstalled 2.7 twice. Here is code: per = 25 num = 3 yep = 0 while per > 0: for den in range(2, num): if num % den == 0: num = num + 2 else: yep = (num) print yep per = per - 1 num = num + 2 thank you again, M -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 29 10:27:02 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Nov 2010 09:27:02 -0000 Subject: [Tutor] Temperature Scales References: <471262.24467.qm@web88203.mail.re2.yahoo.com> Message-ID: "Andre Jeyarajan" wrote > Write two functions that will convert temperatures > back and forth from the Celsius and Fahrenheit temperature > scales (using raw_input) If we ignore the raw_input bit you have done what you were asked. > def C_F(x): > y = (x-32)*(5.0/9) > print y Although as a stylistic point it is better to return values from functions rather than print the values inside the functions. You can then print the result of the function like this: print C_F(x) > def F_C(x): > y = (x*9.0/5)+32 > print y > I have created the two functions but I don?t know what to do from > here. I suspect the assignment expects you to provide some code that uses them, to show they work. Given the raw_input hint I'd surmise they want you to ask the user for a temperature in C or F and use your functions to print the corresponding temperature in the other scale. You will need to convert the raw_input value to an integer for the functions to work. Can you do that? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Nov 29 10:44:13 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Nov 2010 09:44:13 -0000 Subject: [Tutor] noob References: <572B95FE00A34E9CB35D1C3DE04B482E@toy> Message-ID: "Mary" wrote > finding the 1000th prime > The little build i did to find primes does fine until, for some > reason, > 95 shows up, and later other multiples of 5 .....Is it me? > Have uninstalled and reinstalled 2.7 twice. It is always tempting when you start programming to assume there must be something wrong with the tool. Sadly, it is virtually never the case, it is the programmer at fault. :-) I've added some questions/comments below... > per = 25 # not sure why you start at 25... > num = 3 # I'm assuming this is the number under test? > yep = 0 # and this is the count of primes? > > while per > 0: > for den in range(2, num): # den is denominator maybe? > if num % den == 0: # this bit puzzles me. > num = num + 2 > else: yep = (num) # what do you think the > parentheses do here? > print yep > per = per - 1 > num = num + 2 I confess I don't follow the algorithm here, I'm not sure where the primes are being stored, I don't know how you detect when you have reached the 1000th. I'm not even sure there is a valid test for a prime. Try searching wikipedia, there are easier ways to find primes and there are also easier ways to find a specific prime. Getting the algorithm right is the first challenge, coding it is the easy bit. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From andreengels at gmail.com Mon Nov 29 12:05:50 2010 From: andreengels at gmail.com (Andre Engels) Date: Mon, 29 Nov 2010 12:05:50 +0100 Subject: [Tutor] noob In-Reply-To: <572B95FE00A34E9CB35D1C3DE04B482E@toy> References: <572B95FE00A34E9CB35D1C3DE04B482E@toy> Message-ID: On Mon, Nov 29, 2010 at 6:57 AM, Mary wrote: > Dear Tutors: > > Thank you for your time.I am trying to do first assignment (ps1a+b) onMIT > open study, finding the 1000th prime in part a and doing something with > import.math and logs in part b, but I'm not there yet. The little build i > did to find primes does fine until, for some reason, 95 shows up, and later > other multiples of 5 jump into the mix without being invited.I end up almost > 200 primes off by the 1000 count. Is it me? Have uninstalled and reinstalled > 2.7 twice.?Here is code: Your primality tester is incorrect. When you find a divisor you go on to check the number that is 2 more, but you start with the same divisor. If the new number you check is not a prime number, but only has divisors smaller than the checked divisor, your program will falsely recognize it as prime. To make it more clear what I mean, I will show how your program finds 95 to be prime: 89 was a prime, and next the program checks 91. 91 is not divisible by 2. 91 is not divisible by 3. 91 is not divisible by 4. 91 is not divisible by 5. 91 is not divisible by 6. 91 is divisible by 7 - not prime! check 93 instead 93 is not divisible by 7. 93 is not divisible by 8. ... 93 is not divisible by 30. 93 is divisible by 31 - not prime! check 95 instead 95 is not divisible by 31. ... 95 is not divisible by 90. Checked all numbers smaller than 91, so 95 is prime. -- Andr? Engels, andreengels at gmail.com From onyxtic at gmail.com Mon Nov 29 12:35:56 2010 From: onyxtic at gmail.com (Evans Anyokwu) Date: Mon, 29 Nov 2010 11:35:56 +0000 Subject: [Tutor] Python Exercise In-Reply-To: References: Message-ID: Providing trial section alone will not make much difference. You should consider removing the need to sign in as well and focus on providing great tutorial content. Good luck On Sun, Nov 28, 2010 at 2:43 AM, Kok Cheng Tan wrote: > Hi, > > Thanks for the feedback. > I will add a trial section that doesn't require login so that new visitors > are able to give the website a try. > > Regards, > Kok Cheng > > ---------- Forwarded message ---------- > From: > Date: Sun, Nov 28, 2010 at 2:41 AM > Subject: Tutor Digest, Vol 81, Issue 105 > To: tutor at python.org > > > 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. Python Exercise (Kok Cheng Tan) > 2. Reload() in v3? WAS Re: IDEs (Alan Gauld) > 3. Re: Reload() in v3? WAS Re: IDEs (Alan Gauld) > 4. Re: Python Exercise (Mac Ryan) > 5. Re: normalize an array (Eike Welk) > 6. Python Exercise (patty at cruzio.com) > 7. Re: Python Exercise (Joel Schwartz) > 8. Re: normalize an array (John) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 27 Nov 2010 22:00:03 +0800 > From: Kok Cheng Tan > To: tutor at python.org > Subject: [Tutor] Python Exercise > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > Hi, > > > I created this website for practising python online: > http://www.pyschools.com. > Hope to gather feedback from people here who are interesting in > teaching and learning python. > > Regards, > Kok Cheng > > > ------------------------------ > > Message: 2 > Date: Sat, 27 Nov 2010 15:04:57 -0000 > From: "Alan Gauld" > To: tutor at python.org > Subject: [Tutor] Reload() in v3? WAS Re: IDEs > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > > "Steven D'Aprano" wrote > > > The other nine times out of ten *wink* I need to do debugging, and I > > swap tabs and work in my interactive Python interpreter. > > > > import filename # first time only > > reload(filename) # all subsequent times > > I'm working on the v3 version of my tutor and while testing some > module code I tried to reload the module in IDLE... I got an error: > > >>> import os > >>> reload(os) > Traceback (most recent call last): > File "", line 1, in > reload(os) > NameError: name 'reload' is not defined > >>> > > Has reload been removed in V3? > Whats the alternative? Does a repeated import auto-reload? > > I'm surprised and confused... > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ------------------------------ > > Message: 3 > Date: Sat, 27 Nov 2010 15:11:53 -0000 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Reload() in v3? WAS Re: IDEs > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > > "Alan Gauld" wrote > > Has reload been removed in V3? > > Whats the alternative? Does a repeated import auto-reload? > > > > I'm surprised and confused... > > Found it, its been moved into the imp module. > > You need to import imp and then do > > imp.reload(foo) > > >>> import os > >>> reload(os) > Traceback (most recent call last): > File "", line 1, in > reload(os) > NameError: name 'reload' is not defined > >>> import imp > >>> imp.reload(os) > > >>> > > I wonder why that was considered "a good idea"? > > Alan G. > > > > ------------------------------ > > Message: 4 > Date: Sat, 27 Nov 2010 18:12:59 +0100 > From: Mac Ryan > To: tutor at python.org > Subject: Re: [Tutor] Python Exercise > Message-ID: <20101127181259.770ea696 at jabbar> > Content-Type: text/plain; charset=US-ASCII > > > On Sat, 27 Nov 2010 22:00:03 +0800 > Kok Cheng Tan wrote: > > > I created this website for practising python online: > > http://www.pyschools.com. Hope to gather feedback from people here > > who are interesting in teaching and learning python. > > Here you go with the first suggestion: remove the need to log in! > (Haven't really watched at the site content, given that I - like 99% of > the Internet users - wouldn't bother to login just to roam around a > site). > > Mac. > > > ------------------------------ > > Message: 5 > Date: Sat, 27 Nov 2010 18:44:25 +0100 > From: Eike Welk > To: tutor at python.org > Subject: Re: [Tutor] normalize an array > Message-ID: <201011271845.38868.eike.welk at gmx.net> > Content-Type: Text/Plain; charset="iso-8859-1" > > Hello John! > > On Friday 26.11.2010 23:23:51 Peter Otten wrote: > > John wrote: > > > I know this is a simple problem, but I want to do it the most > > > efficient way (that is vectorized...) > > > > > > import numpy as np > > > > > > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) > > > b = np.sum(a,axis=1) > > > > > > for i,elem in enumerate(a): > > > a[i,:] = elem/b[i] > > > > > > suggestions? > > > > I'm not a numpy expert, but: > > > > (a.transpose()/np.sum(a, axis=1)).transpose() > > The underlying feature of Peter's solution is called broadcasting. For a > detailed explanation look at: > http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html > > > Eike. > > > ------------------------------ > > Message: 6 > Date: Sat, 27 Nov 2010 09:17:21 -0800 (PST) > From: patty at cruzio.com > To: tutor at python.org > Subject: [Tutor] Python Exercise > Message-ID: > > Content-Type: text/plain;charset=iso-8859-15 > > > Hi - I just wanted to add to Mac's comment. I don't have Google > mail/gmail and don't want to create a mail account with them. I was also > wondering if I should just try clicking on links anyway and changed my > mind and exited. > > Regards, > > Patty > > > > > > On Sat, 27 Nov 2010 22:00:03 +0800 > > Kok Cheng Tan wrote: > > > >> I created this website for practising python online: > >> http://www.pyschools.com. Hope to gather feedback from people here > >> who are interesting in teaching and learning python. > > > > Here you go with the first suggestion: remove the need to log in! > > (Haven't really watched at the site content, given that I - like 99% of > > the Internet users - wouldn't bother to login just to roam around a > > site). > > > > Mac. > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > ------------------------------ > > Message: 7 > Date: Sat, 27 Nov 2010 10:15:45 -0800 > From: "Joel Schwartz" > To: > Subject: Re: [Tutor] Python Exercise > Message-ID: <007201cb8e5f$1d256b60$6501a8c0 at JLAPTOP> > Content-Type: text/plain; charset="us-ascii" > > > > > > -----Original Message----- > > On Sat, 27 Nov 2010 22:00:03 +0800 > > Kok Cheng Tan wrote: > > > > > I created this website for practising python online: > > > http://www.pyschools.com. Hope to gather feedback from > > people here who > > > are interesting in teaching and learning python. > > > I logged in using my google account and the first page that came up was a > ranking of competitors in the site's Python Tournament. I would recommend > that you bring people to an introductory learning page after their first > sign in (if you keep the sign-in requirement, which I also think is a bad > idea) rather than a competition page--that is, unless you want to > intimidate > some (many?) beginning programmers into looking elsewhere. > > Joel > > > > > ------------------------------ > > Message: 8 > Date: Sat, 27 Nov 2010 19:41:41 +0100 > From: John > To: Eike Welk > Cc: tutor at python.org > Subject: Re: [Tutor] normalize an array > Message-ID: > > Content-Type: text/plain; charset=ISO-8859-1 > > Thank you both! Broadcasting is a concept I hadn't yet read about, but > knew was important for efficient python programming... thanks for the > link! > > > On Sat, Nov 27, 2010 at 6:44 PM, Eike Welk wrote: > > Hello John! > > > > On Friday 26.11.2010 23:23:51 Peter Otten wrote: > >> John wrote: > >> > I know this is a simple problem, but I want to do it the most > >> > efficient way (that is vectorized...) > >> > > >> > import numpy as np > >> > > >> > a = np.array(([1,2,3,4],[1,.2,3,4],[1,22,3,4])) > >> > b = np.sum(a,axis=1) > >> > > >> > for i,elem in enumerate(a): > >> > ? ? a[i,:] = elem/b[i] > >> > > >> > suggestions? > >> > >> I'm not a numpy expert, but: > >> > >> (a.transpose()/np.sum(a, axis=1)).transpose() > > > > The underlying feature of Peter's solution is called broadcasting. For a > > detailed explanation look at: > > http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html > > > > > > Eike. > > > _______________________________________________ > > Tutor maillist ?- ?Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Python 2.6 > PIL 1.1.6 > Mailman 2.1.9 > Postfix 2.4.5 > Procmail v3.22 2001/09/10 > Basemap: 1.0 > Matplotlib: 1.0.0 > > > ------------------------------ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 81, Issue 105 > ************************************** > > > _______________________________________________ > 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 Mon Nov 29 13:08:17 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 29 Nov 2010 23:08:17 +1100 Subject: [Tutor] temporarily modifying sys.path In-Reply-To: References: <20101128163332.GA1808@johnsons-web.com><43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> <20101128183636.GB1808@johnsons-web.com> Message-ID: <4CF397B1.6050009@pearwood.info> Alan Gauld wrote: > > "Tim Johnson" wrote > >>> Just curious, but could the imp module help you? imp.find_module > >> I'll be darned. I never even heard of that module, but I just >> did an import and looked at the docs. I *will* give that a try. > > I think its new in Python v3... Nah, it's been around forever: [steve at sylar ~]$ python1.5 Python 1.5.2 (#1, Apr 1 2009, 22:55:54) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import imp >>> imp.find_module('math') (None, 'math', ('', '', 6)) -- Steven From andrejeyarajan at rogers.com Mon Nov 29 15:29:44 2010 From: andrejeyarajan at rogers.com (Andre Jeyarajan) Date: Mon, 29 Nov 2010 06:29:44 -0800 (PST) Subject: [Tutor] age program Message-ID: <592913.57328.qm@web88207.mail.re2.yahoo.com> Write a short program that will perform the following:It will ask the user for his age,it will then present the user with a menu, with 4 choices:Tell the user whether his age is an even or an odd number? Tell the user his age squared? Tell the user how many years until he?s 100 years old, or tell him that he?s alerady over 100!? If the user is exactly 100 years old, congratulate him for being a centurion.? I have tried everything i can. Can you please explain it to me? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Mon Nov 29 16:57:52 2010 From: andreengels at gmail.com (Andre Engels) Date: Mon, 29 Nov 2010 16:57:52 +0100 Subject: [Tutor] age program In-Reply-To: <592913.57328.qm@web88207.mail.re2.yahoo.com> References: <592913.57328.qm@web88207.mail.re2.yahoo.com> Message-ID: We will not make your homework for you. However, we may well give you hints and perhaps solve small parts that you are unable to do yourself. For that, however, we need to know *what* it is that you are having problems with. Thus: You said that you have tried everything you can. What have you tried? What part(s) of the problem are you able to solve? What part(s) of the problem are you not able to solve? On Mon, Nov 29, 2010 at 3:29 PM, Andre Jeyarajan wrote: > Write a short program that will perform the following: > > It will ask the user for his age, > > it will then present the user with a menu, with 4 choices: > > 1. Tell the user whether his age is an even or an odd number > 2. Tell the user his age squared > 3. Tell the user how many years until he?s 100 years old, or tell him > that he?s alerady over 100! If the user is exactly 100 years old, > congratulate him for being a centurion. > > > I have tried everything i can. Can you please explain it to me? > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Andr? Engels, andreengels at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Mon Nov 29 16:59:08 2010 From: mehgcap at gmail.com (Alex Hall) Date: Mon, 29 Nov 2010 10:59:08 -0500 Subject: [Tutor] age program In-Reply-To: <592913.57328.qm@web88207.mail.re2.yahoo.com> References: <592913.57328.qm@web88207.mail.re2.yahoo.com> Message-ID: On 11/29/10, Andre Jeyarajan wrote: > Write a short program that will perform the following:It will ask the user > for his age,it will then present the user with a menu, with 4 choices:Tell > the user whether his age is an even or an odd number > Tell the user his age squared > Tell the user how many years until he?s 100 years old, or tell him that he?s > alerady over 100! If the user is exactly 100 years old, congratulate him > for being a centurion. > I have tried everything i can. Can you please explain it to me? Explain which part exactly? That is, what have you gotten to work so far? If you have not gotten anything yet, I recommend looking up the input() and raw_input() methods for age and menu. After that it is just a couple math operations and some if statements inside a while loop. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Mon Nov 29 20:35:38 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Nov 2010 19:35:38 -0000 Subject: [Tutor] temporarily modifying sys.path References: <20101128163332.GA1808@johnsons-web.com><43FFD8E9-201A-4437-93C0-2DABFAEC4D41@gmail.com> <20101128183636.GB1808@johnsons-web.com> <4CF397B1.6050009@pearwood.info> Message-ID: "Steven D'Aprano" wrote >> I think its new in Python v3... > > Nah, it's been around forever: > > [steve at sylar ~]$ python1.5 Wow, I've never even noticed it before, let alone used it... Its amazing what that battery pack contains :-) Alan G From royhink at gmail.com Mon Nov 29 20:42:14 2010 From: royhink at gmail.com (Roy Hinkelman) Date: Mon, 29 Nov 2010 11:42:14 -0800 Subject: [Tutor] Web Harvesting & AJAX/Javascript Message-ID: All, I am working on a project to automate the harvesting of a site that uses Javascript throughout it's navigation. So, I want to follow onclick and mouseover events that use JS functions, and capture/display the resulting info. My script is activated by an onload event. I just want to make sure that I am headed in the right direction, and not missing something!. Any advise or pointers appreciated. Researching this has led me to PAMIE and Selenium. PAMIE is giving me problems with permissions, and the discussion group appears to be fading away. I have not tried Selenium yet. Both open a browser instance, and PAMIE is quite slow, and I expect Selenium to be quite slow as well. How are you navigating around these Javascript based pages? Is there a library or plugin that I am missing? Thanks in advance. -- Roy Hinkelman **Few people are capable of expressing with equanimity opinions which differ from the prejudices of their social environment. Most people are even incapable of forming such opinions.-- Albert Einstein -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 29 20:42:40 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 29 Nov 2010 19:42:40 -0000 Subject: [Tutor] age program References: <592913.57328.qm@web88207.mail.re2.yahoo.com> Message-ID: "Andre Jeyarajan" wrote > Write a short program that will perform the following:It will ask > the user for his age.... Since you have posted a number of what are obviously homework/assignment type questions it might help if you tell us what course you are studying, what topics you have covered etc? Usually assignments are designed to test what you have just learned. But we don't know what aspect of Python these are supposed to be testing! Also, for homeworks we do expect you to post at least some code to show you tried to solve it yourself. Its usually easier for us to point out where you are going wrong and suggest improvements than to start with a blank sheet. If nothing else the broken code will tell us a lot about how you are thinking about the problem. Alan G. From karim.liateni at free.fr Mon Nov 29 21:15:52 2010 From: karim.liateni at free.fr (Karim) Date: Mon, 29 Nov 2010 21:15:52 +0100 Subject: [Tutor] Package loading Message-ID: <4CF409F8.6010704@free.fr> Hello every one, I created a package with the following structure: * ops/ o __init__.py o tcl/ + __init__.py + pythontcl.py > *python -c "import sys; print sys.path; import ops.tcl.pythontcl"* ['', '/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.5-py2.6.egg', '*/home/karim/build/UML2PDK/lib/python*', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/usr/lib/pymodules/python2.6', '/usr/lib/python2.6/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.6/gtk-2.0', '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', '/usr/local/lib/python2.6/dist-packages'] /*home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:109: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import unittest /home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:110: RuntimeWarning: Parent module 'pythontcl' not found while handling absolute import import sys* At the lines I import standard modules sys and unittest I get these non-sense warning (my consideration) though I added the top package root, namely, */home/karim/build/UML2PDK/lib/python. The programesecute correctly but I alaways get this nerving warning. *Any idea will be welcome!* :-) *Regards Karim* * -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Nov 29 21:37:27 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Nov 2010 12:37:27 -0800 Subject: [Tutor] Web Harvesting & AJAX/Javascript In-Reply-To: References: Message-ID: On 11/29/2010 11:42 AM Roy Hinkelman said... > All, > > I am working on a project to automate the harvesting of a site that uses > Javascript throughout it's navigation. So, I want to follow onclick and > mouseover events that use JS functions, and capture/display the resulting > info. My script is activated by an onload event. > > I just want to make sure that I am headed in the right direction, and not > missing something!. Any advise or pointers appreciated. > > Researching this has led me to PAMIE and Selenium. PAMIE is giving me > problems with permissions, and the discussion group appears to be fading > away. I have not tried Selenium yet. Both open a browser instance, and PAMIE > is quite slow, and I expect Selenium to be quite slow as well. > > How are you navigating around these Javascript based pages? Is there a > library or plugin that I am missing? > Hi Roy, I've had a couple of these types of projects on my ToDo list for a while and haven't researched them yet. I suspect you'll get better traction on the main python list, but I've been surprised before... Looking forward to seeing what direction you get pointed in. Emile From jocjo.s at verizon.net Mon Nov 29 22:44:22 2010 From: jocjo.s at verizon.net (John Smith) Date: Mon, 29 Nov 2010 15:44:22 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> Message-ID: <4CF41EB6.3000802@verizon.net> On 11/28/2010 8:06 PM, Walter Prins wrote: > John, (snip stuff) > Ugh, you're probably not going to like this. I've done some googling > and it appears this may be a 64-bit issue with the "ctypes" module... > apparently "64-bit ctypes can only import 64-bit libraries". See here: > http://ur.ly/vSMQ > > Then again, it also seems to be an open issue on the PySerial bug > tracker: http://ur.ly/vZNL > > Note, the above ticket suggests that PySerial 2.4 works ok (impliedly > even on 64-bit XP, so I imagine also on Windows 7.) You should be able > to try this out by downloading the 2.4 version instead and installing it > in the same way you did the 2.5 version. In any case, it might be an > idea to post a report/add a comment to that bug report as well to maybe > help get this issue resolved. > > Cheers, > > Walter Hi, Walter - Thanks for all the research. This was my second attempt at installing the 2.4 version. I did it thus: E:\Python27\pyserial-2.4>..\python setup.py install standart distutils running install running build running build_py creating build creating build\lib creating build\lib\serial copying serial\serialcli.py -> build\lib\serial copying serial\serialjava.py -> build\lib\serial copying serial\serialposix.py -> build\lib\serial copying serial\serialutil.py -> build\lib\serial copying serial\serialwin32.py -> build\lib\serial copying serial\sermsdos.py -> build\lib\serial copying serial\__init__.py -> build\lib\serial running install_lib running install_egg_info Removing E:\Python27\Lib\site-packages\pyserial-2.4-py2.7.egg-info Writing E:\Python27\Lib\site-packages\pyserial-2.4-py2.7.egg-info E:\Python27\pyserial-2.4> But, when I tried it in Python, I got the same as before: >>> import serial >>> ser = serial.Serial(0, timeout = 1) >>> ser Serial(port='COM1', baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, dsrdtr=False) >>> ser.read() Traceback (most recent call last): File "", line 1, in ser.read() File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 236, in read raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) SerialException: ReadFile failed ([Error 6] The handle is invalid.) >>> Cheers, John From emile at fenx.com Mon Nov 29 23:20:33 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Nov 2010 14:20:33 -0800 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: <4CF41EB6.3000802@verizon.net> References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> Message-ID: On 11/29/2010 1:44 PM John Smith said... > But, when I tried it in Python, I got the same as before: > > > >>> import serial > >>> ser = serial.Serial(0, timeout = 1) out of curiosity, if you change the timeout above to 5.... > >>> ser > Serial(port='COM1', baudrate=9600, bytesize=8, > parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, > dsrdtr=False) > >>> ser.read() ... does the delay before printing the traceback below take about 5 seconds? > > Traceback (most recent call last): > File "", line 1, in > ser.read() > File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 236, in > read > raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) > SerialException: ReadFile failed ([Error 6] The handle is invalid.) > >>> Emile From jocjo.s at verizon.net Tue Nov 30 00:25:04 2010 From: jocjo.s at verizon.net (John Smith) Date: Mon, 29 Nov 2010 17:25:04 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> Message-ID: <4CF43650.7040002@verizon.net> On 11/29/2010 4:20 PM, Emile van Sebille wrote: > On 11/29/2010 1:44 PM John Smith said... >> But, when I tried it in Python, I got the same as before: >> >> >> >>> import serial >> >>> ser = serial.Serial(0, timeout = 1) > > out of curiosity, if you change the timeout above to 5.... > >> >>> ser >> Serial(port='COM1', baudrate=9600, bytesize=8, >> parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, >> dsrdtr=False) >> >>> ser.read() > > ... does the delay before printing the traceback below take about 5 > seconds? > No. There is no delay regardless of the timeout setting. John From emile at fenx.com Tue Nov 30 00:56:06 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 29 Nov 2010 15:56:06 -0800 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: <4CF43650.7040002@verizon.net> References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> <4CF43650.7040002@verizon.net> Message-ID: On 11/29/2010 3:25 PM John Smith said... > > On 11/29/2010 4:20 PM, Emile van Sebille wrote: >> On 11/29/2010 1:44 PM John Smith said... >>> But, when I tried it in Python, I got the same as before: >>> >>> >>> >>> import serial >>> >>> ser = serial.Serial(0, timeout = 1) >> >> out of curiosity, if you change the timeout above to 5.... >> >>> >>> ser >>> Serial(port='COM1', baudrate=9600, bytesize=8, >>> parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, >>> dsrdtr=False) >>> >>> ser.read() >> >> ... does the delay before printing the traceback below take about 5 >> seconds? >> > > > No. There is no delay regardless of the timeout setting. > >> >> Traceback (most recent call last): >> File "", line 1, in >> ser.read() >> File "E:\Python27\lib\site-packages\serial\serialwin32.py", line >> 236, in read >> raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) >> SerialException: ReadFile failed ([Error 6] The handle is invalid.) >> >>> Hmmm... any chance you don't have administrative rights on the account performing this? I never got to Win7 (having stopped at XP) but I know it's got a reputation for excessive permission asking. Otherwise, I'd take this up on the main list. Chris Liechti, the [author|current maintainer|significant contributor] of pyserial monitors that list and would probably be interested in diagnosing what you're describing. You could also ask him as per the 'send me a message' link on his sourceforge page at http://sourceforge.net/sendmessage.php?touser=403744 Emile From karim.liateni at free.fr Tue Nov 30 00:58:18 2010 From: karim.liateni at free.fr (Karim) Date: Tue, 30 Nov 2010 00:58:18 +0100 Subject: [Tutor] Package loading In-Reply-To: <4CF409F8.6010704@free.fr> References: <4CF409F8.6010704@free.fr> Message-ID: <4CF43E1A.5060207@free.fr> On 11/29/2010 09:15 PM, Karim wrote: > > Hello every one, > > I created a package with the following structure: > > * ops/ > o __init__.py > o tcl/ > + __init__.py > + pythontcl.py > > > > > *python -c "import sys; print sys.path; import ops.tcl.pythontcl"* > > ['', > '/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.5-py2.6.egg', > '*/home/karim/build/UML2PDK/lib/python*', '/usr/lib/python2.6', > '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', > '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', > '/usr/lib/python2.6/dist-packages', > '/usr/lib/python2.6/dist-packages/PIL', > '/usr/lib/python2.6/dist-packages/gst-0.10', > '/usr/lib/pymodules/python2.6', > '/usr/lib/python2.6/dist-packages/gtk-2.0', > '/usr/lib/pymodules/python2.6/gtk-2.0', > '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', > '/usr/local/lib/python2.6/dist-packages'] > /*home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:109: > RuntimeWarning: Parent module 'pythontcl' not found while handling > absolute import > import unittest > /home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:110: > RuntimeWarning: Parent module 'pythontcl' not found while handling > absolute import > import sys* > > At the lines I import standard modules sys and unittest I get these > non-sense warning (my consideration) though I added the top package > root, namely, */home/karim/build/UML2PDK/lib/python. The > programesecute correctly but I alaways get this nerving warning. > > *Any idea will be welcome!* :-) > > *Regards > Karim* > * I believed I know why: Traceback (most recent call last): File "", line 1, in File "/home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py", line 119, in print sys.modules[__package__] KeyError: 'pythontcl' It is due to method determine parent in class ModuleImporter. I don't know why sys.modules has the key 'ops.tcl.pythontcl' and this class search for the key module 'pythontcl'. Big mess between relative path or whatever. Any idea to fix that? Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From jocjo.s at verizon.net Tue Nov 30 03:21:56 2010 From: jocjo.s at verizon.net (John Smith) Date: Mon, 29 Nov 2010 20:21:56 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> <4CF43650.7040002@verizon.net> Message-ID: <4CF45FC4.3040706@verizon.net> On 11/29/2010 5:56 PM, Emile van Sebille wrote: (snip) > Hmmm... any chance you don't have administrative rights on the account > performing this? I never got to Win7 (having stopped at XP) but I know > it's got a reputation for excessive permission asking. You're right about that. It's like Win7 is paranoid. But, it tells me when I need to supply administrative permission. Some day I'll find the button that tells the system that nobody else uses this computer and to shut up and get on with it. > Otherwise, I'd take this up on the main list. Chris Liechti, the > [author|current maintainer|significant contributor] of pyserial monitors > that list and would probably be interested in diagnosing what you're > describing. You could also ask him as per the 'send me a message' link > on his sourceforge page at > > http://sourceforge.net/sendmessage.php?touser=403744 > > Emile I'll consider that, Emile. First, though, I would like to hear from Walter again after my last post. Thanks for your suggestions. Cheers, John From robert.sjoblom at gmail.com Tue Nov 30 03:28:19 2010 From: robert.sjoblom at gmail.com (=?ISO-8859-1?Q?Robert_Sj=F6blom?=) Date: Tue, 30 Nov 2010 03:28:19 +0100 Subject: [Tutor] REport Card Question Message-ID: >> ?Write a code that will take an input from a user (numerical grade) and >> convert their numerical grade into a letter grade that is accompanied by a >> ?smart? statement. >> >> ?def grade_score(grade): >> >> ? ? if grade >=95 and grade <= 100: >> >> ? ? ? ? print 'A+, Excellent' >> >> ? ? elif grade >=85 and grade < 95: >> >> ? ? ? ? print 'A, Good Work' >> >> ? ? elif grade >=80 and grade < 85: >> >> ? ? ? ? print 'A-, Good Work, but you could do better' [snip] >> grade = raw_input('Put your grade here:?) >> >> >> grade_score() >> >> >> Put your grade here:77 >> >> Traceback (most recent call last): >> >> ? File "/Users/andre.jeyarajan/Documents/workspace/Chapter 5 >> Problems/src/ReportCardQuestion.py", line 28, in >> >> ? ? grade_score() >> >> > This line tells you why it doesn't work: > > >> TypeError: grade_score() takes exactly 1 argument (0 given) >> > > Are you familiar with functions? When you define the function you define it > as taking one parameter: > > def grade_score(grade): > ? ?# Code here > > but then when you call it: > > grade_score() > > you don't give it any parameters (or arguments). The traceback tells you > that you need to provide it 1 argument and that you gave it 0 instead. > > If you called > > grade_score(3, 150) > > you would get a similar error, only it would say (2 given) instead. > > HTH, > Wayne On a related note, do all functions implicitly contain "return None" in them? Trying out this function (correctly) would get "None" added, such as: Enter grade:76 B, Try Harder None Is there a way to avoid "return None" without explicitly having the function return something? Even an empty string will return a new line. best regards, Robert S. From waynejwerner at gmail.com Tue Nov 30 03:42:42 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 29 Nov 2010 20:42:42 -0600 Subject: [Tutor] REport Card Question In-Reply-To: References: Message-ID: On Mon, Nov 29, 2010 at 8:28 PM, Robert Sj?blom wrote: > > > On a related note, do all functions implicitly contain "return None" > in them? Trying out this function (correctly) would get "None" added, > such as: > Enter grade:76 > B, Try Harder > None > > Is there a way to avoid "return None" without explicitly having the > function return something? Even an empty string will return a new > line. > AFAIK, no. Nor am I sure why you would want to - None is a singleton so there can only be once instance of it at a time. None is only printed when you're working in the interactive interpreter - if you write the program in a .py file and execute it you won't see the 'None' unless you print the result (which would indeed be None!) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ranceh at gmail.com Tue Nov 30 04:41:17 2010 From: ranceh at gmail.com (Rance Hall) Date: Mon, 29 Nov 2010 21:41:17 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: <4CF45FC4.3040706@verizon.net> References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> <4CF43650.7040002@verizon.net> <4CF45FC4.3040706@verizon.net> Message-ID: On Mon, Nov 29, 2010 at 8:21 PM, John Smith wrote: > > On 11/29/2010 5:56 PM, Emile van Sebille wrote: > (snip) >> >> Hmmm... any chance you don't have administrative rights on the account >> performing this? I never got to Win7 (having stopped at XP) but I know >> it's got a reputation for excessive permission asking. > > You're right about that. It's like Win7 is paranoid. But, it tells me when I > need to supply administrative permission. Some day I'll find the button that > tells the system that nobody else uses this computer and to shut up and get > on with it. > Just so you know, Its called User Account Control or UAC. Google for "disabling UAC on Windows 7" and you can find a tutorial or two on how to make your computer "shut up and get on with it." From jocjo.s at verizon.net Tue Nov 30 04:51:16 2010 From: jocjo.s at verizon.net (John Smith) Date: Mon, 29 Nov 2010 21:51:16 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> <4CF43650.7040002@verizon.net> <4CF45FC4.3040706@verizon.net> Message-ID: <4CF474B4.2060307@verizon.net> On 11/29/2010 9:41 PM, Rance Hall wrote: > On Mon, Nov 29, 2010 at 8:21 PM, John Smith wrote: >> >> On 11/29/2010 5:56 PM, Emile van Sebille wrote: >> (snip) >>> >>> Hmmm... any chance you don't have administrative rights on the account >>> performing this? I never got to Win7 (having stopped at XP) but I know >>> it's got a reputation for excessive permission asking. >> >> You're right about that. It's like Win7 is paranoid. But, it tells me when I >> need to supply administrative permission. Some day I'll find the button that >> tells the system that nobody else uses this computer and to shut up and get >> on with it. >> > > Just so you know, Its called User Account Control or UAC. Google for > "disabling UAC on Windows 7" and you can find a tutorial or two on how > to make your computer "shut up and get on with it." Hey, thanks Rance. The info is appreciated. Cheers, John From alan.gauld at btinternet.com Tue Nov 30 09:56:44 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 30 Nov 2010 08:56:44 -0000 Subject: [Tutor] REport Card Question References: Message-ID: "Robert Sj?blom" wrote > On a related note, do all functions implicitly contain "return None" > in them? All functions return a value because thats the definition of what a function does. (Some languages have a construct known as a procedure which is a function with no return value, but Python does not support procedures.) > Trying out this function (correctly) would get "None" added, > such as: > Enter grade:76 > B, Try Harder > None That depends on how you use the function. Functions should ideally have a single clearly defined purpose. In this case the purpose is to determine the grade based on a score. The caller of the function is then responsible for deciding what to do with the resulting grade - including ignoring (or "correcting") a None result. > Is there a way to avoid "return None" without explicitly > having the function return something? Nope, because that's how functions work. > Even an empty string will return a new line. What the function returns doesn't have to be what the program displays. Separating the application logic from presentation is an important design principle in any program. In this case the code should "return" the value to the caller rather than directly printing it. Then the code that calls the function can decide what to do with the result - to print or not to print... As a secondary benefit this also makes the function more reusable, since we may not always want to print the result but rather store it in a database or display it in a GUI. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kliateni at gmail.com Tue Nov 30 11:02:29 2010 From: kliateni at gmail.com (Karim) Date: Tue, 30 Nov 2010 11:02:29 +0100 Subject: [Tutor] Package loading In-Reply-To: <4CF43E1A.5060207@free.fr> References: <4CF409F8.6010704@free.fr> <4CF43E1A.5060207@free.fr> Message-ID: <4CF4CBB5.1020001@gmail.com> On 11/30/2010 12:58 AM, Karim wrote: > On 11/29/2010 09:15 PM, Karim wrote: >> >> Hello every one, >> >> I created a package with the following structure: >> >> * ops/ >> o __init__.py >> o tcl/ >> + __init__.py >> + pythontcl.py >> >> >> >> > *python -c "import sys; print sys.path; import ops.tcl.pythontcl"* >> >> ['', >> '/usr/local/lib/python2.6/dist-packages/pyparsing-1.5.5-py2.6.egg', >> '*/home/karim/build/UML2PDK/lib/python*', '/usr/lib/python2.6', >> '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', >> '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', >> '/usr/lib/python2.6/dist-packages', >> '/usr/lib/python2.6/dist-packages/PIL', >> '/usr/lib/python2.6/dist-packages/gst-0.10', >> '/usr/lib/pymodules/python2.6', >> '/usr/lib/python2.6/dist-packages/gtk-2.0', >> '/usr/lib/pymodules/python2.6/gtk-2.0', >> '/usr/lib/python2.6/dist-packages/wx-2.8-gtk2-unicode', >> '/usr/local/lib/python2.6/dist-packages'] >> /*home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:109: >> RuntimeWarning: Parent module 'pythontcl' not found while handling >> absolute import >> import unittest >> /home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py:110: >> RuntimeWarning: Parent module 'pythontcl' not found while handling >> absolute import >> import sys* >> >> At the lines I import standard modules sys and unittest I get these >> non-sense warning (my consideration) though I added the top package >> root, namely, */home/karim/build/UML2PDK/lib/python. The >> programesecute correctly but I alaways get this nerving warning. >> >> *Any idea will be welcome!* :-) >> >> *Regards >> Karim* >> * > > I believed I know why: > > Traceback (most recent call last): > File "", line 1, in > File "/home/karim/build/UML2PDK/lib/python/ops/tcl/pythontcl.py", > line 119, in > print sys.modules[__package__] > KeyError: 'pythontcl' > > It is due to method determine parent in class ModuleImporter. > I don't know why sys.modules has the key 'ops.tcl.pythontcl' > and this class search for the key module 'pythontcl'. > > Big mess between relative path or whatever. > > Any idea to fix that? > > Karim > Ok fixed. I must not set the special variable __name__. I set it for pydoc docstrings. Now the __name__ is automatically set to 'ops.tcl.pythontcl' and __package__ is set correctly to 'ops.tcl'. Kind Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From josep.m.fontana at gmail.com Tue Nov 30 14:47:20 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Tue, 30 Nov 2010 14:47:20 +0100 Subject: [Tutor] A regular expression problem In-Reply-To: <5EDAB9A9-F12D-4519-B812-E8323C0D32ED@gmail.com> References: <5EDAB9A9-F12D-4519-B812-E8323C0D32ED@gmail.com> Message-ID: Sorry, something went wrong and my message got sent before I could finish it. I'll try again. On Tue, Nov 30, 2010 at 2:19 PM, Josep M. Fontana wrote: > On Sun, Nov 28, 2010 at 6:03 PM, Evert Rol wrote: > >> --------- >> with open('output_tokens.txt', 'a') as out_tokens: >> with open('text.txt', 'r') as in_tokens: >> t = RegexpTokenizer('[^a-zA-Z\s0-9]+\w+\S') >> output = t.tokenize(in_tokens.read()) >> for item in output: >> out_tokens.write(" %s" % (item)) > > I don't know for sure, but I would hazard a guess that you didn't specify unicode for the regular expression: character classes like \w and \s are dependent on your LOCALE settings. > A flag like re.UNICODE could help, but I don't know if Regexptokenizer accepts that. OK, this must be the problem. The text is in ISO-8859-1 not in Unicode. I tried to fix the problem by doing the following: ------------- import codecs [...] with codecs.open('output_tokens.txt', 'a', encoding='iso-8859-1') as out_tokens: with codecs.open('text.txt', 'r', encoding='iso-8859-1') as in_tokens: t = RegexpTokenizer('[^a-zA-Z\s0-9]+\w+\S') output = t.tokenize(in_tokens.read()) for item in output: out_tokens.write(" %s" % (item)) ------------------- Specifying that the encoding is 'iso-8859-1' didn't do anything, though. The output I get is still the same. >> It would also appear that you could get a long way with the builtin re.split function, and supply the flag inside that function; no need then or Regexptokenizer. Your tokenizer just appears to split on the tokens you specify. Yes. This is in fact what Regexptokenizer seems to do. Here's what the little description of the class says: """ A tokenizer that splits a string into substrings using a regular expression. The regular expression can be specified to match either tokens or separators between tokens. Unlike C{re.findall()} and C{re.split()}, C{RegexpTokenizer} does not treat regular expressions that contain grouping parenthases specially. """ source: http://code.google.com/p/nltk/source/browse/trunk/nltk/nltk/tokenize/regexp.py?r=8539 Since I'm using the NLTK package and this module seemed to do what I needed, I thought I might as well use it. I thought (and I still do) the problem I was didn't have to do with the correct use of this module but in the way I constructed the regular expression. I wouldn't have asked the question here if I thought that the problem had to do with this module. If I understand correctly how the re.split works, though, I don't think I would obtain the results I want, though. re.split would allow me to get a list of the strings that occur around the pattern I specify as the first argument in the function, right? But what I want is to match all the words that contain some non alpha-numeric character in them and exclude the rest of the words. Since these words are surrounded by spaces or by line returns or a combination thereof, just as the other "normal" words, I can't think of any pattern that I can use in re.split() that would discriminate between the two types of strings. So I don't know how I would do what I want with re.split. Josep M. From josep.m.fontana at gmail.com Tue Nov 30 15:32:21 2010 From: josep.m.fontana at gmail.com (Josep M. Fontana) Date: Tue, 30 Nov 2010 15:32:21 +0100 Subject: [Tutor] A regular expression problem In-Reply-To: <4CF28DD9.3090808@pearwood.info> References: <4CF28DD9.3090808@pearwood.info> Message-ID: On Sun, Nov 28, 2010 at 6:14 PM, Steven D'Aprano wrote: > Have you considered just using the isalnum() method? > >>>> '?de'.isalnum() > False Mmm. No, I didn't consider it because I didn't even know such a method existed. This can turn out to be very handy but I don't think it would help me at this stage because the texts I'm working with contain also a lot of non alpha-numeric characters that occur in isolation. So I would get a lot of noise. > The first thing to do is to isolate the cause of the problem. In your code > below, you do four different things. In no particular order: > > 1 open and read an input file; > 2 open and write an output file; > 3 create a mysterious "RegexpTokenizer" object, whatever that is; > 4 tokenize the input. > > We can't run your code because: > > 1 we don't have access to your input file; > 2 most of us don't have the NLTK package; > 3 we don't know what RegexTokenizer does; > 4 we don't know what tokenizing does. As I said in my answer to Evert, I assumed the problem I was having had to do exclusively with the regular expression pattern I was using. The code for RegexTokenizer seems to be pretty simple (http://code.google.com/p/nltk/source/browse/trunk/nltk/nltk/tokenize/regexp.py?r=8539) and all it does is: """ Tokenizers that divide strings into substrings using regular expressions that can match either tokens or separators between tokens. """ > you should write: > > r'[^a-zA-Z\s0-9]+\w+\S' Now you can understand why I didn't use r' ' The methods in the module already use this internally and I just need to insert the regular expression as the argument. > Your regex says to match: > > - one or more characters that aren't letters a...z (in either > ?case), space or any digit (note that this is *not* the same as > ?characters that aren't alphanum); > > - followed by one or more alphanum character; > > - followed by exactly one character that is not whitespace. > > I'm guessing the "not whitespace" is troublesome -- it will match characters > like ? because it isn't whitespace. This was my first attempt to match strings like: '&patre--' or '&patre' The "not whitespace" was intended to match the occurrence of non-alphanumeric characters appearing after "regular" characters. I realize I should have added '*' after '\S' since I also want to match words that do not have a non alpha-numeric symbol at the end (i.e '&patre' as opposed to '&patre--' > > I'd try this: > > # untested > \b.*?\W.*?\b > > which should match any word with a non-alphanumeric character in it: > > - \b ... \b matches the start and end of the word; > > - .*? matches zero or more characters (as few as possible); > > - \W matches a single non-alphanumeric character. > > So putting it all together, that should match a word with at least one > non-alphanumeric character in it. But since '.' matches any character except for a newline, this would also yield strings where all the characters are non-alphanumeric. I should have said this in my initial message but the texts I'm working with contain lots of these strings with sequences of non-alphanumeric characters (i.e. '&%+' or '&//'). I'm trying to match only strings that are a mixture of both non-alphanumeric characters and [a-zA-Z]. > [...] >> >> If you notice, there are some words that have an accented character >> that get treated in a strange way: all the characters that don't have >> a tilde get deleted and the accented character behaves as if it were a >> non alpha-numeric symbol. > > Your regex matches if the first character isn't a space, a digit, or a > a-zA-Z. Accented characters aren't a-z or A-Z, and therefore will match. I guess this is because the character encoding was not specified but accented characters in the languages I'm dealing with should be treated as a-z or A-Z, shouldn't they? I mean, how do you deal with languages that are not English with regular expressions? I would assume that as long as you set the right encoding, Python will be able to determine which subset of specific sequences of bytes count as a-z or A-Z. Josep M. From wprins at gmail.com Tue Nov 30 17:37:34 2010 From: wprins at gmail.com (Walter Prins) Date: Tue, 30 Nov 2010 16:37:34 +0000 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: <4CF41EB6.3000802@verizon.net> References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> Message-ID: Hello John On 29 November 2010 21:44, John Smith wrote: > Hi, Walter - > > Thanks for all the research. This was my second attempt at installing the > 2.4 version. I did it thus: > > E:\Python27\pyserial-2.4>..\python setup.py install > standart distutils > running install > running build > running build_py > creating build > creating build\lib > creating build\lib\serial > copying serial\serialcli.py -> build\lib\serial > copying serial\serialjava.py -> build\lib\serial > copying serial\serialposix.py -> build\lib\serial > copying serial\serialutil.py -> build\lib\serial > copying serial\serialwin32.py -> build\lib\serial > copying serial\sermsdos.py -> build\lib\serial > copying serial\__init__.py -> build\lib\serial > running install_lib > running install_egg_info > Removing E:\Python27\Lib\site-packages\pyserial-2.4-py2.7.egg-info > Writing E:\Python27\Lib\site-packages\pyserial-2.4-py2.7.egg-info > > E:\Python27\pyserial-2.4> > > > But, when I tried it in Python, I got the same as before: > > > >>> import serial > >>> ser = serial.Serial(0, timeout = 1) > >>> ser > Serial(port='COM1', baudrate=9600, bytesize=8, > parity='N', stopbits=1, timeout=1, xonxoff=False, rtscts=False, > dsrdtr=False) > > >>> ser.read() > > Traceback (most recent call last): > File "", line 1, in > > ser.read() > File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 236, in > read > raise SerialException("ReadFile failed (%s)" % ctypes.WinError()) > SerialException: ReadFile failed ([Error 6] The handle is invalid.) > >>> > > I've checked and I think it was a mistake to suggest installing pyserial 2.4 on top of 2.5 without first removing 2.5 explicitly. It appears that doing so actually still retains the previous version of serialwin32.py in use, based on the fact that I've manually had a look at serialwin32.py from both pyserial2.4 and pyserial2.5 and that fact that line 236 in pyserial2.5 is where the error is raised, and pySerial2.4 by contrast has "if err: #will be ERROR_IO_PENDING:" on line 236. Consequently this implies that you're still using pyserial2.5 above. (Aside: I originally tested my suggestion for installing pyserial2.4 and tested it by importing the module (e.g. "import serial") and then did a "help(serial)" which gave me the impression of it having done the right thing and using pyserial2.4, but apparently that's not definitve, or I made a mistake somewhere along the line and got the wrong end of the stick.) So. My apologies, but I think that suggestion has added to the confusion. In any case, to fix it let's delete all instances of pySerial and then install it again, as follows: 1.) Open up your Python "site-packages" folder in Windows Explorer, e.g. open up: E:\Python27\lib\site-packages 2.) Delete any folder named "serial" that you may see. 3.) Delete any *file* name pyserial*.* that you may see, probably you'll see "pyserial-2.4-py2.7.egg", there may also be an info file. 4.) Open up a Python shell and confirm that you can't import pyserial anymore (e.g. "import serial" fails with e.g. "ImportError: No module named serial". If it still imports then you still have some vestiges of the existing pyserial installation left over. 5.) After confirming the previous versions are gone, please try reinstalling it again from scratch. (E.g. extract source to some suitable place and run "python setup.py install" from there, which copies the required files into site-packages etc.) 6.) After installing, confirm "import serial" works again, then try your test again. Apologies again for adding to the confusion, and hopefully we're getting closer. :-( Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From jocjo.s at verizon.net Tue Nov 30 17:57:57 2010 From: jocjo.s at verizon.net (John Smith) Date: Tue, 30 Nov 2010 10:57:57 -0600 Subject: [Tutor] Pyserial and invalid handle In-Reply-To: References: <4CF27B67.8000803@verizon.net> <4CF41EB6.3000802@verizon.net> Message-ID: <4CF52D15.7030806@verizon.net> On 11/30/2010 10:37 AM, Walter Prins wrote: > Hello John (snip) > In any case, to fix it let's delete all instances of pySerial and then > install it again, as follows: > > 1.) Open up your Python "site-packages" folder in Windows Explorer, e.g. > open up: > E:\Python27\lib\site-packages > > 2.) Delete any folder named "serial" that you may see. > > 3.) Delete any *file* name pyserial*.* that you may see, probably you'll > see "pyserial-2.4-py2.7.egg", there may also be an info file. > > 4.) Open up a Python shell and confirm that you can't import pyserial > anymore (e.g. "import serial" fails with e.g. "ImportError: No module > named serial". If it still imports then you still have some vestiges of > the existing pyserial installation left over. > > 5.) After confirming the previous versions are gone, please try > reinstalling it again from scratch. (E.g. extract source to some > suitable place and run "python setup.py install" from there, which > copies the required files into site-packages etc.) > > 6.) After installing, confirm "import serial" works again, then try your > test again. > > Apologies again for adding to the confusion, and hopefully we're getting > closer. :-( > > Walter > Hi, Walter - I did the above and then got this: >>> import serial Traceback (most recent call last): File "", line 1, in import serial File "E:\Python27\lib\site-packages\serial\__init__.py", line 18, in from serialwin32 import * File "E:\Python27\lib\site-packages\serial\serialwin32.py", line 9, in import win32file # The base COM port and file IO functions. ImportError: No module named win32file >>> I guess that file was included in 2.5 but not in 2.4? Thanks, John From rdmoores at gmail.com Tue Nov 30 21:00:03 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 30 Nov 2010 12:00:03 -0800 Subject: [Tutor] How to handle exceptions raised inside a function? Message-ID: Please take a look at 2 functions I just wrote to calculate the harmonic and geometric means of lists of positive numbers: . Both Hlist and Glist must contain only positive numbers, so I really need to test for this inside each function. But is there a good way to do this? What should the functions return should a non-positive number be detected? Is there a conventional Pythonic way to do this? Thanks, Dick Moores From malaclypse2 at gmail.com Tue Nov 30 21:18:46 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 30 Nov 2010 15:18:46 -0500 Subject: [Tutor] How to handle exceptions raised inside a function? In-Reply-To: References: Message-ID: On Tue, Nov 30, 2010 at 3:00 PM, Richard D. Moores wrote: > Both Hlist and Glist must contain only positive numbers, so I really > need to test for this inside each function. But is there a good way to > do this? What should the functions return should a non-positive number > be detected? Is there a conventional Pythonic way to do this? If the value passed to the function is illegal, you should raise a ValueError exception. Something like this in your harmonic_mean function, maybe: if not all(x > 0 for x in Hlist): raise ValueError("All items in Hlist must be positive numbers.") -- Jerry From steve at pearwood.info Tue Nov 30 22:23:43 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 01 Dec 2010 08:23:43 +1100 Subject: [Tutor] How to handle exceptions raised inside a function? In-Reply-To: References: Message-ID: <4CF56B5F.3040903@pearwood.info> Richard D. Moores wrote: > Please take a look at 2 functions I just wrote to calculate the > harmonic and geometric means of lists of positive numbers: > . > > Both Hlist and Glist must contain only positive numbers, so I really > need to test for this inside each function. But is there a good way to > do this? What should the functions return should a non-positive number > be detected? Is there a conventional Pythonic way to do this? There are two basic approaches to handling errors in Python: (1) Don't do any error checking at all. If the input is bad, an exception will (hopefully!) be raised. Provided you know that bad input *will* lead to an exception, and not just plausible-looking but incorrect result, this is often the simplest way. (2) If you don't trust that a sensible exception will be raised, then do your own error checking, and raise an exception. For numeric work, another approach is to return a floating point NAN ("Not A Number"). Unfortunately Python doesn't give any standard way to specify *which* NAN is returned, but you can return float("nan") to return one of them. A fourth approach, rare in Python, is to return some sort of magic value to indicate an exceptional case. Just about the only example of this I can think of is string.find(), which returns -1 to indicate "not found". A fifth approach, common in some other languages, is to return some arbitrary value, and set an error flag. The caller then has to write code like this: result = function(arguments) if not last_result_error: # no error occurred print "result is", result If you do this, I will *personally* track you down and beat you to death with a rather large fish. *wink* For what it's worth, I have a module of statistics functions (shameless plug: http://pypi.python.org/pypi/stats and http://code.google.com/p/pycalcstats -- feedback and bug reports welcome) that includes the harmonic and geometric mean. My harmonic mean looks like this: def harmonic_mean(data): try: m = mean(1.0/x for x in data) except ZeroDivisionError: return 0.0 if m == 0.0: return math.copysign(float('inf'), m) return 1/m Notice that if the data includes one or more zeroes, the harmonic mean itself will be zero: limit as x->0 of 1/x -> infinity, and 1/infinity -> 0. If the sum of reciprocals itself cancels to zero, I return the infinity with the appropriate sign. The only exceptions that could occur are: * mean will raise ValueError if the data is empty; * if an argument is non-numeric, TypeError will occur when I take the reciprocal of it. -- Steven From patty at cruzio.com Tue Nov 30 23:02:38 2010 From: patty at cruzio.com (Patty) Date: Tue, 30 Nov 2010 14:02:38 -0800 Subject: [Tutor] How to handle exceptions raised inside a function? References: <4CF56B5F.3040903@pearwood.info> Message-ID: This is very interesting to me - the below excerpt is something I was trying to do for one of my programs and gave up on it: > A fifth approach, common in some other languages, is to return some > arbitrary value, and set an error flag. The caller then has to write code > like this: > > result = function(arguments) > if not last_result_error: > # no error occurred > print "result is", result > > > If you do this, I will *personally* track you down and beat you to death > with a rather large fish. > > *wink* I think I was trying to do something like thius at the end of a function I wrote- return 2 or return my_special_integer_mvar and then do something or other depending on this value once it passes back to calling function or main(). I think I used similar code as you have above. It didn't go well and also there seemed to be a problem related to where I was returning this value _to_ (where I actually placed this snippet of code like you wrote above) - a function or module I wrote or main(). So, could you expand on this for me? I would have to dig around to find the actual program I was working on. Thanks, Patty ----- Original Message ----- From: "Steven D'Aprano" To: Sent: Tuesday, November 30, 2010 1:23 PM Subject: Re: [Tutor] How to handle exceptions raised inside a function? > Richard D. Moores wrote: >> Please take a look at 2 functions I just wrote to calculate the >> harmonic and geometric means of lists of positive numbers: >> . >> >> Both Hlist and Glist must contain only positive numbers, so I really >> need to test for this inside each function. But is there a good way to >> do this? What should the functions return should a non-positive number >> be detected? Is there a conventional Pythonic way to do this? > > There are two basic approaches to handling errors in Python: > > (1) Don't do any error checking at all. If the input is bad, an exception > will (hopefully!) be raised. Provided you know that bad input *will* lead > to an exception, and not just plausible-looking but incorrect result, this > is often the simplest way. > > (2) If you don't trust that a sensible exception will be raised, then do > your own error checking, and raise an exception. > > For numeric work, another approach is to return a floating point NAN ("Not > A Number"). Unfortunately Python doesn't give any standard way to specify > *which* NAN is returned, but you can return float("nan") to return one of > them. > > A fourth approach, rare in Python, is to return some sort of magic value > to indicate an exceptional case. Just about the only example of this I can > think of is string.find(), which returns -1 to indicate "not found". > > A fifth approach, common in some other languages, is to return some > arbitrary value, and set an error flag. The caller then has to write code > like this: > > result = function(arguments) > if not last_result_error: > # no error occurred > print "result is", result > > > If you do this, I will *personally* track you down and beat you to death > with a rather large fish. > > *wink* > > > For what it's worth, I have a module of statistics functions (shameless > plug: http://pypi.python.org/pypi/stats and > http://code.google.com/p/pycalcstats -- feedback and bug reports welcome) > that includes the harmonic and geometric mean. My harmonic mean looks like > this: > > def harmonic_mean(data): > try: > m = mean(1.0/x for x in data) > except ZeroDivisionError: > return 0.0 > if m == 0.0: > return math.copysign(float('inf'), m) > return 1/m > > Notice that if the data includes one or more zeroes, the harmonic mean > itself will be zero: limit as x->0 of 1/x -> infinity, and 1/infinity -> > 0. If the sum of reciprocals itself cancels to zero, I return the infinity > with the appropriate sign. The only exceptions that could occur are: > > * mean will raise ValueError if the data is empty; > * if an argument is non-numeric, TypeError will occur when I take the > reciprocal of it. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > >