From glingl@aon.at Thu Nov 15 10:18:16 2012 From: glingl@aon.at (Gregor Lingl) Date: Thu, 15 Nov 2012 11:18:16 +0100 Subject: [Tutor] Hummm...dubious behavior. Message-ID: <50A4C168.C30DF5A8@rg16.asn-wien.ac.at> Jean Montambeault schrieb: Felt ready for Guido's idea of a tutorial, tryed the examples, tryed some variations, can't help it and here's something curious : > >>> tax=17.5/100 > >>> price=3.50 > >>> price*tax > 0.61249999999999993 > >>> price+_ > 4.1124999999999998 > >>> round(_,2) > 4.1100000000000003 # in this case : trailing zeros and an error > ... > Obviously my question is what caused the difference in behavior, when must I > expect it or best how to avoid it since, really, I can't imagine a use for > the "long" version.. Dear Jean! I also noticed that there are those things in the Python Tutorial, which do not coincide with the Python - reality. (This is really a little bit disturbing for beginners - and should be corrected some time). As far as I know, the representation >>> 0.6125 0.61250000000000004 >>> occurs because of the fact, that the number 0.6125 is not a power of 2 (or 1/2) and so the internal binary representation of it *has* to be an approximation of it. This is reflected in the output of the Python-evaluator, which delivers some 'raw' form of the result of evaluation in contrast to the print - statement: >>> print 0.6125 0.6125 >>> (However, operating this way prevents you from using _ ) (You can observe this difference also here: >>> 'python' 'python' >>> print 'python' python >>> ) The print-statement obviously polishes the output into a form, which is more user-friendly. (Maybe this has something to do with the difference between __repr__ and __str__ (?) ) On the other hand one can find inconsistencies (in my opinion) even concerning this point, for example: >>> print 0.6125, 4.1225 0.6125 4.1225 # but: >>> print (0.6125, 4.1225) (0.61250000000000004, 4.1224999999999996) >>> Some deeper explanations are welcome Gregor From glingl@aon.at Mon Nov 19 11:51:53 2012 From: glingl@aon.at (Gregor Lingl) Date: Mon, 19 Nov 2012 12:51:53 +0100 Subject: [Tutor] while loop only executes once References: <16571.1008736278@www39.gmx.net> Message-ID: <50AA1D59.FE06BC07@rg16.asn-wien.ac.at> I tried to do, what you did: >>> name = raw_input("Please enter your name: ") Please enter your name: Brett >>> name 'Brett' >>> name.lower() 'brett' >>> name 'Brett' So we see that the content of name didn't change. Presumably you meant: >>> name = name.lower() we continue ... >>> for i in range(0, len(name)): letter = name[i] >>> letter 't' >>> So you see, after this for-loop is finished, you have a single value in the variable letter: the last one of you name. The letters before r were also in letter, but are now overwritten. Suppose now - for sake of brevity - words were this: >>> words = { 'a':'apple', 'b':'ball', 'e':'egg', 'r':'rust', 't':'tea' } >>> Then the while loop acts as follows: >>> while len(name) > 0: print words[letter] tea ea tea tea tea tea tea tea tea tea tea tea Traceback (most recent call last): File "", line 2, in ? print words[letter] File "D:\Python21\Tools\idle\PyShell.py", line 676, in write self.shell.write(s, self.tags) File "D:\Python21\Tools\idle\PyShell.py", line 667, in write raise KeyboardInterrupt KeyboardInterrupt >>> I had to interrupt it by Ctrl-C, because the condition for performing the body: len(name) > 0 remains true forever. So we have an infinite loop. The next statement: >>> name[i] = name[1:] Traceback (most recent call last): File "", line 1, in ? name[i] = name[1:] TypeError: object doesn't support item assignment >>> again results in an error, because in Python strings ar immutable objects. Therfore you cannot change single characters within a string by assignment. ... But, by the way, what did you intend to arrive at? Gregor Brett Kelly schrieb: > ok, here's my loop. it only goes through once and exits. > (words is a dictionary with each letter of the alphabet corresponding to a > different word) > > name = raw_input("Please enter your name: ") > name.lower() > > for i in range(0, len(name)): > letter = name[i] > while len(name) > 0: > print words[letter] > name[i] = name[1:] > > i can't figure this out!!! > > please help, thanks! > > Brett > > -- > Sent through GMX FreeMail - http://www.gmx.net > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From afowler2 at broncos.uncfsu.edu Thu Nov 1 16:34:56 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Thu, 1 Nov 2012 15:34:56 +0000 Subject: [Tutor] Str Method Message-ID: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> Hello I am trying to add a str method to a Set ADT implementation to allow a user to print the contents of a set. However the resulting string should look like that of a list. except I am suppose to use curly brackets to surround the elements. For an example... >>> set1 = Set() >>> print(set1) {} Question is how do you implement the "curly brackets" in my str method? This is what I have so far... def __init__( self, *initElements ): self._theElements = list() def __str__(self): return self._theElements -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 1 18:11:10 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Nov 2012 17:11:10 +0000 Subject: [Tutor] Str Method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 01/11/12 15:34, Ashley Fowler wrote: > Hello I am trying to add a str method to a Set ADT implementation to > allow a user to print the contents of a set. However the resulting > string should look like that of a list. except I am suppose to use curly > brackets to surround the elements. > > For an example... >>>> set1 = Set() >>>> print(set1) > {} > > > Question is how do you implement the "curly brackets" in my str method? > Curly brackets are just characters like any other... >>> print( '{', 42, '}' ) > This is what I have so far... > > def __init__( self, *initElements ): > self._theElements = list() > > def __str__(self): > return self._theElements You are returning a list. But __str__() is supposed to return a string. You need to create a string representation of your data. There are many ways to do that depending on what you want it to look like or contain. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Thu Nov 1 21:12:36 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 Nov 2012 16:12:36 -0400 Subject: [Tutor] Str Method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <5092D7B4.4050006@gmail.com> On 11/1/2012 11:34 AM, Ashley Fowler wrote: > Hello I am trying to add a str method to a Set ADT implementation to > allow a user to print the contents of a set. However the resulting > string should look like that of a list. except I am suppose to use > curly brackets to surround the elements. > > For an example... > >>> set1 = Set() > >>> print(set1) > {} > > > Question is how do you implement the "curly brackets" in my str method? > > This is what I have so far... > > def __init__( self, *initElements ): > self._theElements = list() > > def __str__(self): > return self._theElements Please include the class statement. Give us an example of the desired output when theElementsis not empty. Why not create theElements as a set to start with? what is Set ADT? is it important that we know that? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Thu Nov 1 21:13:08 2012 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Thu, 1 Nov 2012 15:13:08 -0500 Subject: [Tutor] running a javascript script with python Message-ID: <031267A7-E305-4D15-81EB-5F6047A8FF48@gmail.com> I'm on a website that produces an error the first time I submit text. The second time I click enter or click on the submit button, the text is submitted and the results that I want are given to me. The problem is that I want to automate this, but the server treats each submission as the first one...I always get the error. I thought that perhaps if I run the javascript it might work. Here's the script it has for reentering(it's a standard text entry javascript from what my googlesearch tells me): The part of my code that doesn't work is this: text=opener.open(url,encoded_data).read() ('opener' is an object that has all the cookies and headers put in place) The text always has the error. I tried this: for i in range(10): text=opener.open(url,encoded_data).read() if 'Error: BB-09-00-05' in text: print "Sorry, the error is there." else: print "Success!!!" print text The output is ten lines of "sorry, the error is there." -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Thu Nov 1 22:11:07 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 01 Nov 2012 21:11:07 +0000 Subject: [Tutor] Str Method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 01/11/2012 15:34, Ashley Fowler wrote: > Hello I am trying to add a str method to a Set ADT implementation to allow a user to print the contents of a set. However the resulting string should look like that of a list. except I am suppose to use curly brackets to surround the elements. > > For an example... >>>> set1 = Set() Please tell us what this Set() is, then we'll attempt to answer your questions. -- Cheers. Mark Lawrence. From chigga101 at gmail.com Thu Nov 1 22:24:52 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 21:24:52 +0000 Subject: [Tutor] need help Message-ID: working through my tutorial ive been told to set up a simple webserver. i can't even get started because the 1st line of code its asked me to do fails with a syntax error. here's the code: python3 -m http.server any ideas what is going wrong? it asked me to make some simple .html files, then in the same directory run that line of code. I havent any experience with web servers, so i might not understand advanced instructions:( -------------- next part -------------- An HTML attachment was scrubbed... URL: From aclark at aclark.net Thu Nov 1 22:34:12 2012 From: aclark at aclark.net (Alex Clark) Date: Thu, 1 Nov 2012 17:34:12 -0400 Subject: [Tutor] need help References: Message-ID: On 2012-11-01 21:24:52 +0000, Matthew Ngaha said: > working through my tutorial ive been told to set up a simple webserver. > i can't even get started because the 1st line of code its asked me to > do fails with a syntax error. here's the code: > ? > python3 -m http.server > ? > any ideas what is going wrong? it asked me?to make some simple .html > files, then in the same directory run that line of code. I havent any > experience with web servers, so i might not understand advanced > instructions:( Works for me with 3.3: aclark at Alexs-MacBook-Pro:~/ > python3.3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- Alex Clark ? https://www.gittip.com/aclark4life/ From d at davea.name Thu Nov 1 22:43:45 2012 From: d at davea.name (Dave Angel) Date: Thu, 01 Nov 2012 17:43:45 -0400 Subject: [Tutor] need help In-Reply-To: References: Message-ID: <5092ED11.2090602@davea.name> On 11/01/2012 05:24 PM, Matthew Ngaha wrote: > working through my tutorial ive been told to set up a simple webserver. i > can't even get started because the 1st line of code its asked me to do > fails with a syntax error. here's the code: If you got an error, quote it in full in your message (using copy/paste, not by retyping or paraphrasing. As it stands, we don't know if the error was in bash, in csh, in cmd, or in Python, and if it was in python, we don''t know what version. > python3 -m http.server Where did you type that? Was it in a shell, or the interpreter, or in IDLE, or someplace else complicated? > any ideas what is going wrong? it asked me to make some simple .html files, > then in the same directory run that line of code. I havent any experience > with web servers, so i might not understand advanced instructions:( > > You've already got one response showing it working with Python 3.3 on OSX. it also works here, running Python 3.2 on Linux. But you don't say what version, nor what OS. I'd also ask what directory you're running it in. davea at think:~/temppython$ python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 ... -- DaveA From bgailer at gmail.com Thu Nov 1 22:47:04 2012 From: bgailer at gmail.com (bob gailer) Date: Thu, 01 Nov 2012 17:47:04 -0400 Subject: [Tutor] syntax errir (was need help) In-Reply-To: References: Message-ID: <5092EDD8.1090409@gmail.com> On 11/1/2012 5:24 PM, Matthew Ngaha wrote: welcome a few requests to make your experience wonderful: - provide a meaningful subject so we can track the correspondence. - reply-all so a copy goes to the list - put your responses following the text you are responding to rather than at the top - give us enough information so we can duplicate what you are doing. > working through my tutorial ive been told to set up a simple > webserver. i can't even get started because the 1st line of code its > asked me to do fails with a syntax error. here's the code: > python3 -m http.server what OS are you running? you call this code. It appears to be something one would enter at a terminal or command prompt. what did you do to run this exactly what error did you get? my guess is that you tried to run the above as a python program (e.g. within IDLE or at a python interpreter prompt. The more info you give us the easier it is for us to help. -- Bob Gailer 919-636-4239 Chapel Hill NC From chigga101 at gmail.com Thu Nov 1 22:47:40 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 21:47:40 +0000 Subject: [Tutor] need help In-Reply-To: References: Message-ID: > > > > Always, *always* include the *full* error message, otherwise we have to > guess. Not fun. Some other questions: What operating system are you using? > What version of Python does your tutorial assume? Do you in fact have > Python 3 installed on your system? > > > maybe im running it from the wrong place. on IDLE i get: SyntaxError: invalid syntax (, line 1) and on cmd it says 'python3' is not recognized as an internal or external command, operable program or batch file. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Nov 1 22:49:33 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 21:49:33 +0000 Subject: [Tutor] need help In-Reply-To: References: Message-ID: > > > > Works for me with 3.3: > > > aclark at Alexs-MacBook-Pro:~/ > python3.3 -m http.server > Serving HTTP on 0.0.0.0 port 8000 ... > > > hey how do you start it or where do you run it from. did you type that in the command line? -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Nov 1 22:55:02 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 21:55:02 +0000 Subject: [Tutor] need help In-Reply-To: <5092ED11.2090602@davea.name> References: <5092ED11.2090602@davea.name> Message-ID: > > If you got an error, quote it in full in your message (using copy/paste, > not by retyping or paraphrasing. As it stands, we don't know if the > error was in bash, in csh, in cmd, or in Python, and if it was in > python, we don''t know what version. > > > python3 -m http.server > > Where did you type that? Was it in a shell, or the interpreter, or in > IDLE, or someplace else complicated? > > You've already got one response showing it working with Python 3.3 on > OSX. it also works here, running Python 3.2 on Linux. But you don't > say what version, nor what OS. I'd also ask what directory you're > running it in. > > davea at think:~/temppython$ python3 -m http.server > Serving HTTP on 0.0.0.0 port 8000 ... > i type it in both IDLE and CMD. in the directory where i made those .html files, i held shift and right clicked to get the command line open. im on windows vista. the i type that line in there. i use Python 3.1 also i made a .py file in that folder. opened it for editing, then pressed F5 to run it., then type the code into IDLE's interactive interpreter. which is where i got the invalid syntax error: SyntaxError: invalid syntax (, line 1) -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Nov 1 22:55:46 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 1 Nov 2012 17:55:46 -0400 Subject: [Tutor] Str Method In-Reply-To: <5092D7B4.4050006@gmail.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> <5092D7B4.4050006@gmail.com> Message-ID: On Thu, Nov 1, 2012 at 4:12 PM, bob gailer wrote: > > Why not create theElements as a set to start with? > what is Set ADT? is it important that we know that? I suppose it's an implementation of the set abstract data type (i.e. operations such as add, union, difference): http://en.wikipedia.org/wiki/Set_%28abstract_data_type%29 From d at davea.name Thu Nov 1 22:57:32 2012 From: d at davea.name (Dave Angel) Date: Thu, 01 Nov 2012 17:57:32 -0400 Subject: [Tutor] need help In-Reply-To: References: Message-ID: <5092F04C.1000405@davea.name> On 11/01/2012 05:47 PM, Matthew Ngaha wrote: >> >> >> Always, *always* include the *full* error message, otherwise we have to >> guess. Not fun. Some other questions: What operating system are you using? >> What version of Python does your tutorial assume? Do you in fact have >> Python 3 installed on your system? >> >> >> > maybe im running it from the wrong place. > > on IDLE i get: SyntaxError: invalid syntax (, line 1) If you're inside IDLE, you do NOT run python commands, you run python programs. That's not what you want here. When the instructions begin python or python3, then it's a commandline thing, which you do from the shell. > and on cmd it says 'python3' is not recognized as an internal or external > command, operable program or batch file. > > That's it, keep making us play detective to determine those things you could easily have provided for us. I'll guess you're running Windows, because you mention cmd, and I'll guess it's Windows 8, since that's just out this week. And I'll guess you've installed Python 2.4, and that's your problem, as Python3 won't be on your path when you've only installed Python 2.4. If perchance you're running XP, and have installed Python 3.2, then what directory did it install into? is that directory on your path? What happens when you run python itself, is it version 2.72 ? -- DaveA From alan.gauld at btinternet.com Thu Nov 1 23:11:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 01 Nov 2012 22:11:25 +0000 Subject: [Tutor] running a javascript script with python In-Reply-To: <031267A7-E305-4D15-81EB-5F6047A8FF48@gmail.com> References: <031267A7-E305-4D15-81EB-5F6047A8FF48@gmail.com> Message-ID: On 01/11/12 20:13, Benjamin Fishbein wrote: > I'm on a website that produces an error the first time I submit text. We need a lot more context and precision. What OS, what web framework(if any) what Python version. What does on a web site mean? How are you submitting text? Who created the Javascript - how does it relate to your Python code? How are you running the Python code? etc etc. It may all seem self evident to you but I can assure you it isn't to us! > > > The part of my code that doesn't work is this: > > text=opener.open(url,encoded_data).read() > > ('opener' is an object that has all the cookies and headers put in place) > > The text always has the error. > > I tried this: > > for i in range(10): > text=opener.open(url,encoded_data).read() > if 'Error: BB-09-00-05' in text: > print "Sorry, the error is there." > else: > print "Success!!!" > print text > > The output is ten lines of "sorry, the error is there." Can we see those ten lines please? And where do they appear? In a browser? a server console? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Thu Nov 1 23:15:03 2012 From: d at davea.name (Dave Angel) Date: Thu, 01 Nov 2012 18:15:03 -0400 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: <5092F467.7080203@davea.name> On 11/01/2012 05:55 PM, Matthew Ngaha wrote: >> If you got an error, quote it in full in your message (using copy/paste, >> not by retyping or paraphrasing. As it stands, we don't know if the >> error was in bash, in csh, in cmd, or in Python, and if it was in >> python, we don''t know what version. >> >>> python3 -m http.server >> Where did you type that? Was it in a shell, or the interpreter, or in >> IDLE, or someplace else complicated? >> > >> You've already got one response showing it working with Python 3.3 on >> OSX. it also works here, running Python 3.2 on Linux. But you don't >> say what version, nor what OS. I'd also ask what directory you're >> running it in. >> >> davea at think:~/temppython$ python3 -m http.server >> Serving HTTP on 0.0.0.0 port 8000 ... >> > i type it in both IDLE and CMD. in the directory where i made those .html > files, i held shift and right clicked to get the command line open. im on > windows vista. the i type that line in there. i use Python 3.1 > > also i made a .py file in that folder. opened it for editing, then pressed > F5 to run it., then type the code into IDLE's interactive interpreter. > which is where i got the invalid syntax error: > > SyntaxError: invalid syntax (, line 1) > > Don't run it from inside IDLE. You were right to run it from cmd. Pasting the error message you showed elsewhere: 'python3' is not recognized as an internal or external command, operable program or batch file. That simply says that the PATH does not point to your PYTHON3.bat or PYTHON3.exe program. When I was stuck on Windows, I used the ActivePython version, as it had many enhancements for Windows users over standard CPython. One of those enhancements was a simpler install that set up associations and paths automatically. Consequently, I don't have any idea how your Windows install tried to set up your PATH. Look in a directory like C:\Python3.1 to see if it's there at all. And if it is, add it to your PATH. That's a Windows thing, which you can do from the control panel. But for testing, you can just manually add it to the path of your current cmd shell. In case you didn't know, PATH is an environment variable used by the cmd shell (and other programs) to search for .exe, .bat, and .cmd programs. -- DaveA From eryksun at gmail.com Thu Nov 1 23:27:40 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 1 Nov 2012 18:27:40 -0400 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: On Thu, Nov 1, 2012 at 5:55 PM, Matthew Ngaha wrote: > > i type it in both IDLE and CMD. in the directory where i made those .html > files, i held shift and right clicked to get the command line open. im on > windows vista. the i type that line in there. i use Python 3.1 The interpreter executable in Windows is always called "python" (console) or "pythonw" (no console). The 3.1 installer doesn't put the executable's directory on the system PATH. The option to add this was added to the 3.3 installer. Otherwise you'll have to add the directory manually. In IDLE check the result of the following: >>> import sys >>> sys.executable '/usr/bin/python3' For you it will probably display "C:\Python31\pythonw.exe". That being the case; you have to append "C:\Python31" to your PATH. You can do this temporarily using the cmd shell's "set" command (e.g. set PATH=%PATH%;C:\Python31), or permanently in the system registry by following instructions easily found online. From chigga101 at gmail.com Thu Nov 1 23:31:22 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 22:31:22 +0000 Subject: [Tutor] need help In-Reply-To: <5092F467.7080203@davea.name> References: <5092ED11.2090602@davea.name> <5092F467.7080203@davea.name> Message-ID: > > Don't run it from inside IDLE. You were right to run it from cmd. > > Pasting the error message you showed elsewhere: > > 'python3' is not recognized as an internal or external > command, operable program or batch file. > > That simply says that the PATH does not point to your PYTHON3.bat or > PYTHON3.exe program. When I was stuck on Windows, I used the ActivePython > version, as it had many enhancements for Windows users over standard > CPython. One of those enhancements was a simpler install that set up > associations and paths automatically. Consequently, I don't have any idea > how your Windows install tried to set up your PATH. Look in a directory > like C:\Python3.1 to see if it's there at all. And if it is, add it to > your PATH. That's a Windows thing, which you can do from the control > panel. But for testing, you can just manually add it to the path of your > current cmd shell. > > In case you didn't know, PATH is an environment variable used by the cmd > shell (and other programs) to search for .exe, .bat, and .cmd programs. > im really not any good with cmd or know how to set things to my python path. what do you mean when you say Look in a directory like C:\Python3.1 to see if it's there at all? you mean to see if the code works, or something else? i have my python installed not in my C:drive but... D:\Data\Program Files Data\Py in a folder named Py. i opened the cmd there and typed python3 and python 3.1 but got the same errors. i also ran the same code to start the server but still got the same error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Nov 1 23:37:17 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 22:37:17 +0000 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: > > The interpreter executable in Windows is always called "python" > (console) or "pythonw" (no console). The 3.1 installer doesn't put the > executable's directory on the system PATH. The option to add this was > added to the 3.3 installer. Otherwise you'll have to add the directory > manually. In IDLE check the result of the following: > > >>> import sys > >>> sys.executable > '/usr/bin/python3' > > For you it will probably display "C:\Python31\pythonw.exe". That being > the case; you have to append "C:\Python31" to your PATH. You can do > this temporarily using the cmd shell's "set" command (e.g. set > PATH=%PATH%;C:\Python31), or permanently in the system registry by > following instructions easily found online. > here were the results: >>> import sys >>> sys.executable 'D:\\Data\\Program Files Data\\Py\\pythonw.exe' >>> '/usr/bin/python3' '/usr/bin/python3' >>> i dont see Python31 .. is this Py that is supposed to be Python31?.. and do i type this exactly like you did in cmd? set PATH=%PATH%;C:\Python31 ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Thu Nov 1 23:47:26 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 1 Nov 2012 18:47:26 -0400 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: On Thu, Nov 1, 2012 at 6:37 PM, Matthew Ngaha wrote: > >>>> import sys >>>> sys.executable > 'D:\\Data\\Program Files Data\\Py\\pythonw.exe' > > i dont see Python31 .. is this Py that is supposed to be Python31?.. and do > i type this exactly like you did in cmd? > > set PATH=%PATH%;C:\Python31 ? No, in your case it's set PATH=%PATH%;D:\Data\Program Files Data\Py That's just a temporary modification for the current cmd process. It's easiest to show how to change it permanently with screen captures; search for "vista set path". From chigga101 at gmail.com Fri Nov 2 00:12:29 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 23:12:29 +0000 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: > > No, in your case it's > > set PATH=%PATH%;D:\Data\Program Files Data\Py > > That's just a temporary modification for the current cmd process. It's > easiest to show how to change it permanently with screen captures; > search for "vista set path". > i followed the instructions at http://banagale.com/changing-your-system-path-in-windows-vista.htm i added "D:\Data\Program Files Data\Py" to my variable value but i still get the same error that Py is not recognized:( -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Nov 2 00:17:52 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 1 Nov 2012 19:17:52 -0400 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: On Thu, Nov 1, 2012 at 7:12 PM, Matthew Ngaha wrote: >> No, in your case it's >> >> set PATH=%PATH%;D:\Data\Program Files Data\Py >> >> That's just a temporary modification for the current cmd process. It's >> easiest to show how to change it permanently with screen captures; >> search for "vista set path". > > > i followed the instructions at > http://banagale.com/changing-your-system-path-in-windows-vista.htm > > i added "D:\Data\Program Files Data\Py" to my variable value but i still get > the same error that Py is not recognized:( "Py" is a directory. Once you've added the Python executable's directory to the path, you can start the http.server module as a script by running the following: python -m http.server Don't use "pythonw" in this case. The latter is associated with the .pyw file extension, used for scripts that run without a console. For example, IDLE is a GUI app that uses Tk widgets, so it doesn't need a console. That's why it runs with "pythonw.exe". From chigga101 at gmail.com Fri Nov 2 00:33:58 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 1 Nov 2012 23:33:58 +0000 Subject: [Tutor] need help In-Reply-To: References: <5092ED11.2090602@davea.name> Message-ID: > > "Py" is a directory. > > Once you've added the Python executable's directory to the path, you > can start the http.server module as a script by running the following: > > python -m http.server > > Don't use "pythonw" in this case. The latter is associated with the > .pyw file extension, used for scripts that run without a console. For > example, IDLE is a GUI app that uses Tk widgets, so it doesn't need a > console. That's why it runs with "pythonw.exe". > wow i am so grateful.. i had given up hope just trying different things. its finally working. thank you:) -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Nov 2 01:19:18 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 02 Nov 2012 11:19:18 +1100 Subject: [Tutor] Str Method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <50931186.3010308@pearwood.info> On 02/11/12 02:34, Ashley Fowler wrote: > Question is how do you implement the "curly brackets" in my str method? > > This is what I have so far... > > def __init__( self, *initElements ): > self._theElements = list() > > def __str__(self): > return self._theElements __str__ should return a string, not a list. Since _theElements is a list, you cannot rightly return that. You could convert that to a string first: s = str(self._theElements) and then replace the square brackets [ ] with curly brackets: s = s.replace("[", "{").replace("]", "}") return s Another way is to build the string yourself: s = ', '.join(str(item) for item in self._theElements) return '{' + s + '}' -- Steven From eryksun at gmail.com Fri Nov 2 01:43:46 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 1 Nov 2012 20:43:46 -0400 Subject: [Tutor] Str Method In-Reply-To: <50931186.3010308@pearwood.info> References: <6962C976AE76AC4298CBF6FD6D0C635631D1C7D7@BL2PRD0710MB363.namprd07.prod.outlook.com> <50931186.3010308@pearwood.info> Message-ID: On Thu, Nov 1, 2012 at 8:19 PM, Steven D'Aprano wrote: > > s = str(self._theElements) > s = s.replace("[", "{").replace("]", "}") > return s > > > Another way is to build the string yourself: > > s = ', '.join(str(item) for item in self._theElements) > return '{' + s + '}' Or s = str(self._theElements) return "{%s}" % s[1:-1] From jlavier at jsu.edu Fri Nov 2 02:55:22 2012 From: jlavier at jsu.edu (Jarred Lavier) Date: Thu, 1 Nov 2012 20:55:22 -0500 (CDT) Subject: [Tutor] Tutor needed! In-Reply-To: <122552205.6836096.1351821217434.JavaMail.root@mbs1.jsu.edu> Message-ID: <1596090574.6836356.1351821322071.JavaMail.root@mbs1.jsu.edu> Looking for someone who can walk me through certain homework assignments, as well as explaining how to create them. If interested please e-mail me as soon as possible. From alan.gauld at btinternet.com Fri Nov 2 09:56:35 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 2 Nov 2012 08:56:35 +0000 (GMT) Subject: [Tutor] Fw: running a javascript script with python In-Reply-To: References: <031267A7-E305-4D15-81EB-5F6047A8FF48@gmail.com> Message-ID: <1351846595.15992.YahooMailNeo@web87906.mail.ir2.yahoo.com> forwarding to group. Please use Reply ALL in replies to tutor. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Forwarded Message ----- >From: Benjamin Fishbein >To: Alan Gauld >Sent: Friday, 2 November 2012, 3:55 >Subject: Re: [Tutor] running a javascript script with python > > >> >> We need a lot more context and precision. >> ??? >> What OS, what web framework(if any) what Python version. >> ??? I'm on a Mac using OSX. Default web browser is Safari.? Python 2.5.4 > >> What does on a web site mean? >??? I mean when I use the web browser it works the second time I click the input button, but without a button to click, it continues to return an error. >> How are you submitting text? >??? Post method. >> Who created the Javascript - how does it relate to your Python code? >??? >> How are you running the Python code? >??? I'm running it in Idle. > >Here's what it looked like: > >Python 2.5.4 (r254:67917, Dec 23 2008, 14:57:27) >[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin >Type "copyright", "credits" or "license()" for more information. > >? ? **************************************************************** >? ? Personal firewall software may warn about the connection IDLE >? ? makes to its subprocess using this computer's internal loopback >? ? interface.? This connection is not visible on any external >? ? interface and no data is sent to or received from the Internet. >? ? **************************************************************** >? ? >IDLE 1.2.4? ? ? >>>> import urllib,urllib2,cookielib >>>> cj=cookielib.CookieJar() >>>> opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) >>>> isbns='''1561380156 >0440574358 >0152590366 >0060109726 >0394531892 >9780684836287 >9780140114331''' >>>> data={"bb_isbns":isbns} >>>> encoded_data=urllib.urlencode(data) >>>> url='http://www.textbooks.com/BuyBack-Search.php' >>>> text=opener.open(url,encoded_data).read() >>>> if "Error: BB-09-00-05" in text: >??? print "The error is there." > >??? >The error is there. >>>> for i in range(10): >??? text=opener.open(url,encoded_data).read() >??? if "Error: BB-09-00-05" in text: >??? ??? print "The error is there. Attempt #",(i+1) >??? else: >??? ??? print "It worked!" >??? ??? print text > >??? ??? >The error is there. Attempt # 1 >The error is there. Attempt # 2 >The error is there. Attempt # 3 >The error is there. Attempt # 4 >The error is there. Attempt # 5 >The error is there. Attempt # 6 >The error is there. Attempt # 7 >The error is there. Attempt # 8 >The error is there. Attempt # 9 >The error is there. Attempt # 10 > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Fri Nov 2 10:51:52 2012 From: eryksun at gmail.com (eryksun) Date: Fri, 2 Nov 2012 05:51:52 -0400 Subject: [Tutor] Fw: running a javascript script with python In-Reply-To: <1351846595.15992.YahooMailNeo@web87906.mail.ir2.yahoo.com> References: <031267A7-E305-4D15-81EB-5F6047A8FF48@gmail.com> <1351846595.15992.YahooMailNeo@web87906.mail.ir2.yahoo.com> Message-ID: > ----- Forwarded Message ----- > From: Benjamin Fishbein > To: Alan Gauld > Sent: Friday, 2 November 2012, 3:55 > Subject: Re: [Tutor] running a javascript script with python > >>>> cj=cookielib.CookieJar() >>>> opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > .... >>>> data={"bb_isbns":isbns} >>>> encoded_data=urllib.urlencode(data) >>>> url='http://www.textbooks.com/BuyBack-Search.php' You asked about this a month or so ago. This time around you're using a cookie jar to store the session state, but you're skipping the CSID parameter. If you look at the HTML source, you'll see BuyBack-Search.php?CSID=Some_Value_From_Your_Session. If you first open http://www.textbooks.com to read the session cookies, CSID appears to be the 'tb_DSL" cookie. That said, as I mentioned before, the site's terms of service forbid scraping (see section II) : http://www.textbooks.com/CustServ-Terms.php From alan.gauld at btinternet.com Sat Nov 3 02:19:35 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 03 Nov 2012 01:19:35 +0000 Subject: [Tutor] Tutor needed! In-Reply-To: <1596090574.6836356.1351821322071.JavaMail.root@mbs1.jsu.edu> References: <122552205.6836096.1351821217434.JavaMail.root@mbs1.jsu.edu> <1596090574.6836356.1351821322071.JavaMail.root@mbs1.jsu.edu> Message-ID: On 02/11/12 01:55, Jarred Lavier wrote: > Looking for someone who can walk me through certain homework assignments, > as well as explaining how to create them. > If interested please e-mail me as soon as possible. It doesn't really work like that. The tutor group is a collective effort to help each other learn Python. We all contribute although some, obviously, are more experienced than others. But we don't do private tutoring, the point is to post questions and the group collectively learns from the answers. On the subject of homework, we will not do you homework but if you explain what you have done, and tell us where you are stuck, we will try to point you in the right direction. When posting it helps to tell us the OS you are using and the Python version. Also post any error messages in their entirety. And "context posting" (ie not top-posting) will win you some friends too... Welcome to the tutor list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Sat Nov 3 14:04:54 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 3 Nov 2012 06:04:54 -0700 (PDT) Subject: [Tutor] how to keep track of sorted lists Message-ID: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> Hello, I want to make a get() method that uses a binary search. This requires the data to be sorted which is an expensive operation, so I would like to do this no more often than needed. Which of the to classes below is the best way to keep track of the sorted lists? TestOne stores them in separate attributes, while TestTwo uses one sorted_ attribute that is a dictionary that contains all the sorted data, with keys as, well, keys. I am inclined to think that TestTwo is less messy. Btw, I am aware that, either way, it may not be a good idea to store all these potentially huge sorted lists. Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55) [GCC 4.4.5] on linux2 >>> import bisect >>> class TestOne(object): ??? def __init__(self, param="x"): ??? ??? self.param = param ??? ??? self.data = range(10, 1, -1) ??? def get(self, key): ??? ??? sorted_ = "sorted_" + self.param ??? ??? if not hasattr(self, sorted_): ??? ??? ??? setattr(self, sorted_, sorted(self.data)) ??? ??? return bisect.bisect_right(getattr(self, sorted_), x=key) >>> t = TestOne("x") >>> t.get(1) 0 >>> class TestTwo(object): ??? def __init__(self, param="x"): ??? ??? self.param = param ??? ??? self.data = range(10, 1, -1) ??? def get(self, key): ??? ??? k = "sorted_" + self.param ??? ??? if not hasattr(self, "sorted_"): ??? ??? ??? setattr(self, "sorted_", {k: sorted(self.data)}) ??? ??? return bisect.bisect_right(getattr(self, "sorted_")[k], x=key) >>> t = TestTwo("x") >>> t.get(1) 0 ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From d at davea.name Sat Nov 3 15:17:50 2012 From: d at davea.name (Dave Angel) Date: Sat, 03 Nov 2012 10:17:50 -0400 Subject: [Tutor] how to keep track of sorted lists In-Reply-To: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> References: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> Message-ID: <5095278E.70209@davea.name> On 11/03/2012 09:04 AM, Albert-Jan Roskam wrote: > Hello, (I haven't run the code, as it was not presented in a form that I could do a single copy/paste. So I may have missed some subtlety in the code.) > I want to make a get() method that uses a binary search. This requires the data to be sorted which is an expensive operation, so I would like to do this no more often than needed. > Which of the to classes below is the best way to keep track of the sorted lists? TestOne stores them in separate attributes, while TestTwo uses one sorted_ attribute that is a dictionary that contains all the sorted data, with keys as, well, keys. I am inclined to think that TestTwo is less messy. Btw, I am aware that, either way, it may not be a good idea to store all these potentially huge sorted lists. > > Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55) > [GCC 4.4.5] on linux2 Thanks for telling us the version and OS. >>>> import bisect >>>> class TestOne(object): > def __init__(self, param="x"): > self.param = param > self.data = range(10, 1, -1) > def get(self, key): > sorted_ = "sorted_" + self.param > if not hasattr(self, sorted_): > setattr(self, sorted_, sorted(self.data)) > return bisect.bisect_right(getattr(self, sorted_), x=key) Why have multiple copies of the sorted data, when there's only one list? >>>> t = TestOne("x") >>>> t.get(1) > 0 >>>> class TestTwo(object): > def __init__(self, param="x"): > self.param = param > self.data = range(10, 1, -1) > def get(self, key): > k = "sorted_" + self.param > if not hasattr(self, "sorted_"): This will only work for the first param. After that, the attribute will exist and the the setattr will be skipped. > setattr(self, "sorted_", {k: sorted(self.data)}) > return bisect.bisect_right(getattr(self, "sorted_")[k], x=key) >>>> t = TestTwo("x") >>>> t.get(1) > 0 > > Good job simplifying the problem. But it's so simple i can't see what the real goal is without some textual description. Is a single instance of this class intended to hold a single, unchanging list? If not, are you intending to delete the sorted_ attribute each time it changes? The param value would make sense to me if it affected the sort. But otherwise, what's the point of having multiple sorted copies of a list, when they'll all be identical? And if param is constant for any given instance of the class, then what's the point of all this indirection on it? -- DaveA From fomcl at yahoo.com Sat Nov 3 15:40:47 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 3 Nov 2012 07:40:47 -0700 (PDT) Subject: [Tutor] how to keep track of sorted lists In-Reply-To: <5095278E.70209@davea.name> References: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> <5095278E.70209@davea.name> Message-ID: <1351953647.11226.YahooMailNeo@web110714.mail.gq1.yahoo.com> > On 11/03/2012 09:04 AM, Albert-Jan Roskam wrote: >> Hello, > > (I haven't run the code, as it was not presented in a form that I could > do a single copy/paste.? So I may have missed some subtlety in the code.) Hi, sorry about that. Here's a copy/pastable version. I also added a 'data' parameter as my original code was too synthetic in this respect. The more realistically, the data come from some getter method. import bisect class TestOne(object): ??? def __init__(self, data, param="x"): ??????? self.param = param ??????? self.data = data? # <------ NOTE: this would in reality be a getter method of some sort ??? def get(self, key, default=None): ??????? sorted_ = "sorted_" + self.param ??????? if not hasattr(self, sorted_): ??????????? setattr(self, sorted_, sorted(self.data)) ??????? return bisect.bisect_right(getattr(self, sorted_), x=key) t = TestOne(range(10, 1, -1), "x") t.get(1) class TestTwo(object): ??? def __init__(self, data, param="x"): ??????? self.param = param ??????? self.data = range(10, 1, -1) ??? def get(self, key, default=None): ??????? k = "sorted_" + self.param ??????? if not hasattr(self, "sorted_"): ??????????? setattr(self, "sorted_", {k: sorted(self.data)}) ??????? return bisect.bisect_right(getattr(self, "sorted_")[k], x=key) t = TestTwo(range(10, 1, -1), "x") t.get(1) ?? return bisect.bisect_right(getattr(self, sorted_), x=key) > > Why have multiple copies of the sorted data, when there's only one list? > > Good job simplifying the problem.? But it's so simple i can't see what > the real goal is without some textual description.? Is a single instance > of this class intended to hold a single, unchanging list?? If not, are > you intending to delete the sorted_ attribute each time it changes? > The get() method is supposed to mimic the dict.get method. I want to do stuff like: c = TestOne(data=blah, param="ssn") # ---> c.sorted_snn c.get(432123, "social security number not found") d = TestOne(data=blah, param="gender") # ---> d.sorted_gender d.get("female", "sorry, only blokes here") From d at davea.name Sat Nov 3 15:47:22 2012 From: d at davea.name (Dave Angel) Date: Sat, 03 Nov 2012 10:47:22 -0400 Subject: [Tutor] how to keep track of sorted lists In-Reply-To: <1351953647.11226.YahooMailNeo@web110714.mail.gq1.yahoo.com> References: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> <5095278E.70209@davea.name> <1351953647.11226.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <50952E7A.90209@davea.name> On 11/03/2012 10:40 AM, Albert-Jan Roskam wrote: >> On 11/03/2012 09:04 AM, Albert-Jan Roskam wrote: > >>> Hello, >> >> (I haven't run the code, as it was not presented in a form that I could >> do a single copy/paste. So I may have missed some subtlety in the code.) > > Hi, sorry about that. Here's a copy/pastable version. I also added a 'data' parameter as my original code was too synthetic in this respect. > The more realistically, the data come from some getter method. > > import bisect > class TestOne(object): > def __init__(self, data, param="x"): > self.param = param > self.data = data # <------ NOTE: this would in reality be a getter method of some sort > def get(self, key, default=None): > sorted_ = "sorted_" + self.param > if not hasattr(self, sorted_): > setattr(self, sorted_, sorted(self.data)) > return bisect.bisect_right(getattr(self, sorted_), x=key) > > t = TestOne(range(10, 1, -1), "x") > t.get(1) > > class TestTwo(object): > def __init__(self, data, param="x"): > self.param = param > self.data = range(10, 1, -1) > def get(self, key, default=None): > k = "sorted_" + self.param > if not hasattr(self, "sorted_"): > setattr(self, "sorted_", {k: sorted(self.data)}) > return bisect.bisect_right(getattr(self, "sorted_")[k], x=key) > t = TestTwo(range(10, 1, -1), "x") > t.get(1) > > > return bisect.bisect_right(getattr(self, sorted_), x=key) >> >> Why have multiple copies of the sorted data, when there's only one list? >> > > >> Good job simplifying the problem. But it's so simple i can't see what >> the real goal is without some textual description. Is a single instance >> of this class intended to hold a single, unchanging list? If not, are >> you intending to delete the sorted_ attribute each time it changes? >> > > The get() method is supposed to mimic the dict.get method. I want to do stuff like: > c = TestOne(data=blah, param="ssn") # ---> c.sorted_snn > c.get(432123, "social security number not found") > d = TestOne(data=blah, param="gender") # ---> d.sorted_gender > d.get("female", "sorry, only blokes here") > > > OK, so you have a separate instance of TestOne for each list, and the list is not modified for that instance. In that case, both your sample code is overly complex; you're not using param for anything useful, and you could greatly simplify by using an ordinary attribute to hold the sorted list. If it's not present, generate it. Or even easier, initialize it to None, and do a simple "if self.sorted is not None"on it to decide whether it's sorted yet or not. -- DaveA From steve at pearwood.info Sat Nov 3 16:18:22 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 04 Nov 2012 02:18:22 +1100 Subject: [Tutor] how to keep track of sorted lists In-Reply-To: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> References: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> Message-ID: <509535BE.6080209@pearwood.info> On 04/11/12 00:04, Albert-Jan Roskam wrote: > Hello, > > I want to make a get() method that uses a binary search. This requires > the data to be sorted which is an expensive operation, so I would like >to do this no more often than needed. Reset your intuition. Sorting an almost-sorted list with Timsort (Python's sort algorithm) is blindingly fast, approaching O(N), but running at full C speed rather than pure Python. You may find that the easiest, fastest, most efficient way to add data to a list and keep it sorted is to simply append at the end and then sort. class SortedSequence(object): def __init__(self, sequence): self.data = sorted(sequence) def insert(self, item): self.data.append(item) self.data.sort() Another approach is to sort only on demand: tag the instance as "dirty", and then whenever you do a lookup, if the list is dirty, sort first. class SortedSequence(object): def __init__(self, sequence): self.data = sorted(sequence) self.dirty = False def insert(self, item): self.data.append(item) self.dirty = True def get(self, key): if self.dirty: self.data.sort() self.dirty = False # now use bisect to find the key A third approach: always use the bisect algorithm to insert the item in the right place. class SortedSequence(object): def __init__(self, sequence): self.data = sorted(sequence) def insert(self, item): # use bisect in here... def get(self, key): # and in here too... You may find that a hybrid approach is best, say using version 1 for data lists with less than a million items, and version 3 for bigger ones. Don't guess, measure and find out. Whatever you do, make sure you test with BIG lists -- for small lists, *any* approach will likely be fast enough. Now that you have a SortedSequence type, you can easily deal with many of them: mapping = {} # map param to data mapping['x'] = SortedSequence(lots of data) mapping['y'] = SortedSequence(more data) mapping['x'].insert(item) mapping['y'].get(key) sort of thing. One final thought... why are you using binary search instead of a dict? Dict lookups will generally be much faster than binary search, O(1) compared to O(log N), and simpler too. For large N, the difference between constant-time lookups and those proportional to log N can be substantial. > Which of the to classes below is the best way to keep track of the > sorted lists? Neither. -- Steven From steve at pearwood.info Sat Nov 3 16:30:06 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 04 Nov 2012 02:30:06 +1100 Subject: [Tutor] how to keep track of sorted lists In-Reply-To: <1351953647.11226.YahooMailNeo@web110714.mail.gq1.yahoo.com> References: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> <5095278E.70209@davea.name> <1351953647.11226.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <5095387E.6070104@pearwood.info> On 04/11/12 01:40, Albert-Jan Roskam wrote: > Hi, sorry about that. Here's a copy/pastable version. I also added >a 'data' parameter as my original code was too synthetic in this >respect. > The more realistically, the data come from some getter method. I don't understand what you mean by that. > import bisect > class TestOne(object): > def __init__(self, data, param="x"): > self.param = param > self.data = data #<------ NOTE: this would in reality be a getter method of some sort ??? > def get(self, key, default=None): > sorted_ = "sorted_" + self.param > if not hasattr(self, sorted_): > setattr(self, sorted_, sorted(self.data)) > return bisect.bisect_right(getattr(self, sorted_), x=key) Default isn't used here. What's it for? The name of this method, and its argument, are misleading. It isn't a "get" method, like dicts have, it doesn't take a key and return an item associated with that key. What you've actually written is a complicated version of list.index, except that you can't distinguish between item found and item not found. > The get() method is supposed to mimic the dict.get method. But it doesn't. > I want to do stuff like: > c = TestOne(data=blah, param="ssn") # ---> c.sorted_snn > c.get(432123, "social security number not found") > d = TestOne(data=blah, param="gender") # ---> d.sorted_gender > d.get("female", "sorry, only blokes here") Sounds like you want a dict. -- Steven From richkappler at gmail.com Sat Nov 3 21:20:54 2012 From: richkappler at gmail.com (richard kappler) Date: Sat, 3 Nov 2012 16:20:54 -0400 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: <5c8b6ecaeac97a16f3e43368e0ce2d1a.squirrel@webmail.sonic.net> Message-ID: To all, especially Dave, Oscar and Ramit, thanks for the discussion and help. Tino, as soon as I have something to put up, I will gladly put it up on Github. At the moment I only have a few snippets I've written in trying to learn the various bits everyone has been helping me with. Just for the record, I did use subprocess quite successfully in one of my preliminary programs earlier this summer as I started to learn python, used it to send out the text from the old chatbot to Festival TTS, so I am comfortable with the idea of running multiple processes from python to the command line. I'm not quite sure that's the way to go with the sensors and other bits though. I'm wondering if I'm asking the wrong question. I have read and re-read your posts, and have read and re-read the documentation on multi-processing and threading. I have also read several tutorials on both. I feel that I understand the concepts a wee bit better, though not enough to come up with some workable processing or threading code. I have, however, still not figured out an answer to my question, which leads me to believe I have not asked the question properly. The alternative is that I'm just too damned dense to wrap my arms around this and I both think and hope that is not the case, so I will try to do a better job of articulating what I'm looking for. (Again, I suspect its in multiprocessing and threading, but I can't quite put my finger on a good approach). SO... while the bot program is running, I would like it to be continuously cognizant of the sensor data and any changes in that data. Let's distill it down to a single sensor to simplify the discussion. If I have a temperature sensor feeding data to the arduino, which feeds that data through serial to the Python program (let's call that pyBrain) that "is" the bot, (here's the meat of the question:) how do I make the pyBrain constantly aware of the temperature while doing other stuff? I think what's tripping me up is that Python is sequential, yes? So line 1 executes, then we go to line 2, then line 3, etc. So if pyBrain is off doing some facial recognition or having a chat (or both?), and Temp1 suddenly rises above a preset threshold of 78 degrees F how does pyBrain know that? Because python is sequential does there not have to be some specific code that tells it to periodically poll Temp1? Or, barring periodic or even continuous polling, is there some "event alert" function that would tell the pyBrain program to execute the "Temp1High" function? And if there is an event alert function such that you all are going to tell me (in your best Frank Morgan voice) "Well, wny didn't you say so?" then can pyBrain keep chatting etc and just update "state", aware that it's environment has changed, keeping that information for future reference, but continue on with it's running tasks/processes unless that new state requires some action? Or even better, add the action to the task(s) it is performing as one more concurrent task/action? My initial thought was to run concurrent processes, or threads (still working that bit out). I have considered having Arduino write the sensor data to a table or dictionary or even file, just constantly overwriting previous values, and pyBrain could pull values out of that table/dictionary/file as needed. That doesn't seem terribly elegant to me though, and certainly doesn't get me passed the "parameter just crossed a preset threshold" alert issue either. Befuddled and bewildered while learning at an alarming rate, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Sat Nov 3 22:59:03 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 3 Nov 2012 21:59:03 +0000 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: <5c8b6ecaeac97a16f3e43368e0ce2d1a.squirrel@webmail.sonic.net> Message-ID: On 3 November 2012 20:20, richard kappler wrote: > To all, especially Dave, Oscar and Ramit, thanks for the discussion and > help. Tino, as soon as I have something to put up, I will gladly put it up > on Github. At the moment I only have a few snippets I've written in trying > to learn the various bits everyone has been helping me with. > > Just for the record, I did use subprocess quite successfully in one of my > preliminary programs earlier this summer as I started to learn python, used > it to send out the text from the old chatbot to Festival TTS, so I am > comfortable with the idea of running multiple processes from python to the > command line. I'm not quite sure that's the way to go with the sensors and > other bits though. You may be right. The problem is that this is not a situation where anyone can really tell you the definitive way of doing things. There are many ways to do what you're doing and which is best depends on details that are currently unknown (by you or by the rest of us). > > I'm wondering if I'm asking the wrong question. I have read and re-read your > posts, and have read and re-read the documentation on multi-processing and > threading. I have also read several tutorials on both. I feel that I > understand the concepts a wee bit better, though not enough to come up with > some workable processing or threading code. I have, however, still not > figured out an answer to my question, which leads me to believe I have not > asked the question properly. The alternative is that I'm just too damned > dense to wrap my arms around this and I both think and hope that is not the > case, so I will try to do a better job of articulating what I'm looking for. > (Again, I suspect its in multiprocessing and threading, but I can't quite > put my finger on a good approach). The example below shows how to use multiprocessing to run two different operations concurrently. Each operation is run in its own process. #!/usr/bin/env python from multiprocessing import Process from time import sleep def update_brain(): while True: sleep(1) print 'thinking...' def chat_with_friends(): while True: sleep(.3) print 'chatting...' p1 = Process(target=update_brain) p2 = Process(target=chat_with_friends) p1.start() p2.start() > > SO... while the bot program is running, I would like it to be continuously > cognizant of the sensor data and any changes in that data. Let's distill it > down to a single sensor to simplify the discussion. If I have a temperature > sensor feeding data to the arduino, which feeds that data through serial to > the Python program (let's call that pyBrain) that "is" the bot, (here's the > meat of the question:) how do I make the pyBrain constantly aware of the > temperature while doing other stuff? It depends on how pyserial works. This sounds like the kind of situation where a separate thread would be used. I say a thread rather than a process because this is most likely an IO-bound operation. This means that it consumes very little CPU and spends most of its time waiting for the serial port to produce data. I've never used pyserial but I imagine that it has a function called something like get_data that returns data read from the device. I also imagine that this function "blocks". That means that it causes execution to pause until data is ready and then returns the data. It is precisely this blocking that makes people want to use threads. While one thread blocks execution of the others can resume so that waiting for data in one operation does not cause every other operation to pause. The downside of using multiple threads or processes though is that it makes it harder to share data between the different operations. Here's an extension of the above that shows how to share an integer between the two processes: #!/usr/bin/env python from multiprocessing import Process, Value from time import sleep from random import randint def update_brain(): global how_many_spams while True: sleep(1) n = randint(1, 5) print 'thinking...', n how_many_spams.value = n def chat_with_friends(): global how_many_spams while True: sleep(.3) print 'chatting:' + how_many_spams.value * ' spam' how_many_spams = Value('i', 1) p1 = Process(target=update_brain) p2 = Process(target=chat_with_friends) p1.start() p2.start() > > Befuddled and bewildered while learning at an alarming rate, Richard > I suggest that you just write the application and divide pieces off into threads/processes later if needed. Avoid sharing data between different operations except when strictly necessary (then breaking out one part into a separate process or thread won't be so painful). I'll rephrase the rule of thumb from before: Use separate threads to separate out operations that involve blocking-IO calls that would otherwise cause the whole application to suspend. Use separate processes to separate out CPU-heavy operations that block the other operations by consuming too much CPU time. On a multicore machine the separate processes will hopefully run on different cores so that you'll be making better use of the available CPU capacity. Oscar From eryksun at gmail.com Sat Nov 3 23:29:00 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 3 Nov 2012 18:29:00 -0400 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: <5c8b6ecaeac97a16f3e43368e0ce2d1a.squirrel@webmail.sonic.net> Message-ID: On Sat, Nov 3, 2012 at 5:59 PM, Oscar Benjamin wrote: > > how_many_spams = Value('i', 1) > > p1 = Process(target=update_brain) > p2 = Process(target=chat_with_friends) > > p1.start() > p2.start() In Linux you can easily inherit the global Value object in forked processes, but it's not that hard to support Windows, too: if __name__ == '__main__': how_many_spams = Value('i', 1) args = (how_many_spams,) p1 = Process(target=update_brain, args=args) p2 = Process(target=chat_with_friends, args=args) p1.start() p2.start() On Windows, multiprocessing has to launch a fresh interpreter, import the main module, and pickle/pipe the args to the new process. Setup code that should only run in the main process has to be guarded with a __name__ check. From alan.gauld at btinternet.com Sat Nov 3 23:49:37 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 03 Nov 2012 22:49:37 +0000 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: <5c8b6ecaeac97a16f3e43368e0ce2d1a.squirrel@webmail.sonic.net> Message-ID: On 03/11/12 20:20, richard kappler wrote: > SO... while the bot program is running, I would like it to be > continuously cognizant of the sensor data and any changes in that data. > Let's distill it down to a single sensor to simplify the discussion. If > I have a temperature sensor feeding data to the arduino, which feeds > that data through serial to the Python program (let's call that pyBrain) > that "is" the bot, (here's the meat of the question:) how do I make the > pyBrain constantly aware of the temperature while doing other stuff? You could have a thread running to read the serial input and when it detects a message it communicates with the main program. You probably want an event driven framework and I think twisted will do most of what you want. I suggest you go read the twisted web site and try the tutorials. Its an event driven networking framework... > I think what's tripping me up is that Python is sequential, yes? Almost every programming language is sequential, certainly all the most popular ones. Thats what threads and subprocesses are for - to give the ability)or the illusion) of parallel processing. Operating systems and GUIs work on the event driven principle where they have a simple program structure consisting of an event loop that just waits for events to arrive and dispatches the event to a separate thread/process to be processed. At the kernel level instead of an event loop they rely on the hardware's interrupt mechanism to call the appropriate system calls. > suddenly rises above a preset threshold of 78 degrees F how does pyBrain > know that? Because python is sequential does there not have to be some > specific code that tells it to periodically poll Temp1? An event loop that polls all possible action sources and kicks off a separate thread/process to deal with each event that must occur in parallel. > periodic or even continuous polling, is there some "event alert" > function that would tell the pyBrain program to execute the "Temp1High" > function? Yes, you can program it yourself opr use a framework to do it for you. That's what GUI frameworks like Tkinter do for you (as well as provide the graphical UI objects etc) Twisted as mentioned above is an event framework for monitoring multiple network event sources. Twisted is not difficult to use but it is non trivial and the docs assume you know python fairly well. > My initial thought was to run concurrent processes, or threads (still > working that bit out). I have considered having Arduino write the sensor > data to a table or dictionary or even file, just constantly overwriting > previous values, and pyBrain could pull values out of that > table/dictionary/file as needed. That's another common pattern - especially in old COOL mainframes! But its easy to create bottlenecks and lose any pretence of real-time multi tasking. But don't be surprised to discover that much of the apparent parallelism in computing is nothing but sleight-of-hand trickery relying on the speed of electronics. A computer can perform a great many things in, say, a tenth of a second. And a computer updating 10 displays every second looks a lot like parallel processing to a human. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Nov 4 01:46:21 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 04 Nov 2012 00:46:21 +0000 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: <5c8b6ecaeac97a16f3e43368e0ce2d1a.squirrel@webmail.sonic.net> Message-ID: On 03/11/12 22:49, Alan Gauld wrote: > That's another common pattern - especially in old COOL mainframes! Given my background that may have been a Freudian slip but I did mean COBOL! honest! :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From richkappler at gmail.com Sun Nov 4 02:03:26 2012 From: richkappler at gmail.com (richard kappler) Date: Sat, 3 Nov 2012 21:03:26 -0400 Subject: [Tutor] running multiple concurrent processes Message-ID: Oscar, that was positively brilliant! Now I get it, I understand how to do it, and I think this has rearranged my entire plan for the "MCP." If the MCP is basically just a program that calls several other programs(processes) and does that bit of coordination between each, then my life just got measurably easier. I think. I did some reading after my last post, and manager seems like it would be a good tool for a lot of this, or at least what we're calling the MCP for purposes of this discussion. Thoughts? I am reluctant to usurp any more of your time, but you are such a phenomenal teacher, might I ask for a quick example of threading like you did with the two multiprocessing snippets? Bill, I appreciate your comment and have given it much thought, Ramit made one much the same the other day. Here lies the potential problem, though it might not be one at all, I need to do some experimenting. While I am a fan of monolithic programming, I'm wondering if what I'm trying to do would work on, say an old netbook. That might be a requirement. I'd prefer it not to be, but it might. Also, thanks for reminding my addled old brain that event driven is called interrupts. I knew that at one point, but seem to have flushed it somehow. eryksun, I am using Linux, not a big fan of Windows, though have to use one at work, so thanks for breaking down forking on both platforms for me. This probably falls into the dumb question category, but I'd rather look dumb than be dumb. Other than as limited by CPU and memory (eg: hardware) is there any limit to the number of processes that can be run using processing? In other words, are there any constraints within Python? regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From richkappler at gmail.com Sun Nov 4 02:05:07 2012 From: richkappler at gmail.com (richard kappler) Date: Sat, 3 Nov 2012 21:05:07 -0400 Subject: [Tutor] running multiple concurrent processes Message-ID: I notice no one has mentioned asyncore. Is that something I should stay away from? I just started digging through the doc file. regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Sun Nov 4 02:36:32 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 4 Nov 2012 01:36:32 +0000 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: Message-ID: On 4 November 2012 01:03, richard kappler wrote: > Oscar, that was positively brilliant! Now I get it, I understand how to do > it, and I think this has rearranged my entire plan for the "MCP." If the MCP > is basically just a program that calls several other programs(processes) and > does that bit of coordination between each, then my life just got measurably > easier. I think. I did some reading after my last post, and manager seems > like it would be a good tool for a lot of this, or at least what we're > calling the MCP for purposes of this discussion. Thoughts? I didn't really understand the above. Is 'manager' some kind of library? > > I am reluctant to usurp any more of your time, but you are such a phenomenal > teacher, might I ask for a quick example of threading like you did with the > two multiprocessing snippets? It looks almost exactly the same. The key difference is that you can just share the value of an integer without needing to do explicitly do anything. (This is also a big source of problems since sharing the same data structures directly only works if all objects/operations are thread-safe http://en.wikipedia.org/wiki/Thread_safety). #!/usr/bin/env python from threading import Thread from time import sleep from random import randint def update_brain(): global how_many_spams while True: sleep(1) n = randint(1, 5) print 'thinking...', n how_many_spams = n def chat_with_friends(): global how_many_spams while True: sleep(.3) print 'chatting:' + how_many_spams * ' spam' how_many_spams = 1 t1 = Thread(target=update_brain) t2 = Thread(target=chat_with_friends) t1.start() t2.start() > > Bill, I appreciate your comment and have given it much thought, Ramit made > one much the same the other day. Here lies the potential problem, though it > might not be one at all, I need to do some experimenting. While I am a fan > of monolithic programming, I'm wondering if what I'm trying to do would work > on, say an old netbook. That might be a requirement. I'd prefer it not to > be, but it might. Also, thanks for reminding my addled old brain that event > driven is called interrupts. I knew that at one point, but seem to have > flushed it somehow. Who's Bill? Alan was referring to Twisted that is an event driven framework. Event driven or asynchronous processing is a third option (after threads or processes). The Twisted library is also capable of launching threads and (I think) processes for you so it could accommodate for all of the possibilities you want in one framework. > > eryksun, I am using Linux, not a big fan of Windows, though have to use one > at work, so thanks for breaking down forking on both platforms for me. > > This probably falls into the dumb question category, but I'd rather look > dumb than be dumb. Other than as limited by CPU and memory (eg: hardware) is > there any limit to the number of processes that can be run using processing? > In other words, are there any constraints within Python? As far as I know Python will allow you to come close to the OS/hardware limit for both threads and processes. Unless I've misunderstood what you're planning to do though these limits are high enough for you to simply not worry about them. Oscar From oscar.j.benjamin at gmail.com Sun Nov 4 02:42:22 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sun, 4 Nov 2012 01:42:22 +0000 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: Message-ID: On 4 November 2012 01:05, richard kappler wrote: > I notice no one has mentioned asyncore. Is that something I should stay away > from? I just started digging through the doc file. I've only briefly looked at asyncore. I've never heard anyone recommend it: the recommendations for asynchronous processing in Python seem to go to Twisted, Tornado, gevent and others. As far as I can tell few people are using asyncore over the third party variants. Oscar From richkappler at gmail.com Sun Nov 4 02:57:36 2012 From: richkappler at gmail.com (richard kappler) Date: Sat, 3 Nov 2012 21:57:36 -0400 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: Message-ID: >I didn't really understand the above. Is 'manager' some kind of library? > > http://docs.python.org/2/library/multiprocessing.html#managers > > > >Who's Bill? Alan was referring to Twisted that is an event driven > >framework. Event driven or asynchronous processing is a third option > >(after threads or processes). The Twisted library is also capable of > >launching threads and (I think) processes for you so it could > >accommodate for all of the possibilities you want in one framework. > Bill is someone who posted to this thread, apparently privately, though I thought it was to the list. I have run across mentions of Twisted, was just starting to look into it when this email arrived. > >As far as I know Python will allow you to come close to the > >OS/hardware limit for both threads and processes. Unless I've > >misunderstood what you're planning to do though these limits are high > >enough for you to simply not worry about them. That's pretty much what I thought, but I wanted to make sure. Yet another exceptional tutorial/code example btw, I think I've got it now. I need to go play with them both (processing and threading) to be sure. Thanks again! Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Sun Nov 4 03:12:40 2012 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Sat, 3 Nov 2012 22:12:40 -0400 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: Message-ID: On Sat, Nov 3, 2012 at 9:05 PM, richard kappler wrote: > I notice no one has mentioned asyncore. Is that something I should stay away > from? I just started digging through the doc file. Regardless of ones' feelings on it, there is no builtin support for multiprocessing using asyncore. -- Devin From breamoreboy at yahoo.co.uk Sun Nov 4 04:13:35 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 04 Nov 2012 03:13:35 +0000 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: Message-ID: On 04/11/2012 01:05, richard kappler wrote: > I notice no one has mentioned asyncore. Is that something I should stay > away from? I just started digging through the doc file. > > regards, Richard > If you're really interested read the thread "The Async API of the future" and its derivatives on the Python ideas mailing list. Ensure you have copious supplies of coffee, sandwiches and possibly painkillers for the headache if you take this route :) -- Cheers. Mark Lawrence. From wrw at mac.com Sun Nov 4 04:01:02 2012 From: wrw at mac.com (wrw at mac.com) Date: Sat, 03 Nov 2012 23:01:02 -0400 Subject: [Tutor] running multiple concurrent processes In-Reply-To: References: Message-ID: <227F4D5D-7109-4B49-BDCB-A43CD7D1E4E5@mac.com> On Nov 3, 2012, at 9:36 PM, Oscar Benjamin wrote: > [byte] > >> >> Bill, I appreciate your comment and have given it much thought, Ramit made >> one much the same the other day. Here lies the potential problem, though it >> might not be one at all, I need to do some experimenting. While I am a fan >> of monolithic programming, I'm wondering if what I'm trying to do would work >> on, say an old netbook. That might be a requirement. I'd prefer it not to >> be, but it might. Also, thanks for reminding my addled old brain that event >> driven is called interrupts. I knew that at one point, but seem to have >> flushed it somehow. > > Who's Bill? Alan was referring to Twisted that is an event driven > framework. Event driven or asynchronous processing is a third option > (after threads or processes). The Twisted library is also capable of > launching threads and (I think) processes for you so it could > accommodate for all of the possibilities you want in one framework. > This Bill, and with apologies, - after some debate with myself I sent my comment to Richard without copying the list, since it was not relevant to either Threading or Multiprocessing - I simply pointed out that modern processors are so fast that he can probably accomplish what he wants to do by breaking his main subtasks into semi-atomic chunks and calling them round-robin. It would require keeping careful track of some shared globals, but might be a MUCH simpler initial approach. Those sub tasks could be coalesced and converted to multiprocessing later after he gets going with the robot. -Bill From pygods at hush.com Sun Nov 4 06:43:30 2012 From: pygods at hush.com (pygods at hush.com) Date: Sun, 04 Nov 2012 01:43:30 -0400 Subject: [Tutor] please give me feedback - linux & virtual machine python script Message-ID: <20121104054330.7A0FD10E2C8@smtp.hushmail.com> Hi, This script helps load files with the corresponding application inside a virtual machine from the host file manager. The script is accessed by right clinking the file from Nautilus file manager (Linux/Gnome/Ubuntu Unity) in the host. For the Nautilus script menu to work, the file openinvm.py needs to be (or linked) in /home/USER/.gnome2/nautilus-scripts/ With a file/samba share setup in the host, loadapps.py is able to load the file (located in host) with the default application in and from the virtual machine. The following are the steps to load files in the virtual machine from the host without using windows explorer in the VM. * find the desired file in the host with Nautilus file manager * right click file and select openinvm.py under scripts. * If virtual machine is not opened, openinvm.py will load it. * after the virtual machine is loaded, openinvm.py will send the file path information to loadapps.py in the virtual machine. * loadapps.py will load the file from the samba share with the default application under windows. This script can probably be made to load files in OS X but it's currently working with windows xp. There are more features I like to implement but It would be nice to get constructive feedback from the community. Here is the code http://pastebin.com/R8b8M5PR Let me know if this email is not clear and I will try to explain. Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Sun Nov 4 12:19:57 2012 From: kwpolska at gmail.com (Kwpolska) Date: Sun, 4 Nov 2012 12:19:57 +0100 Subject: [Tutor] please give me feedback - linux & virtual machine python script In-Reply-To: <20121104054330.7A0FD10E2C8@smtp.hushmail.com> References: <20121104054330.7A0FD10E2C8@smtp.hushmail.com> Message-ID: On Sun, Nov 4, 2012 at 6:43 AM, wrote: > Hi, > > This script helps load files with the corresponding application inside a > virtual machine from the host file manager. The script is accessed by right > clinking the file from Nautilus file manager (Linux/Gnome/Ubuntu Unity) in > the host. For the Nautilus script menu to work, the file openinvm.py needs > to be (or linked) in /home/USER/.gnome2/nautilus-scripts/ > With a file/samba share setup in the host, loadapps.py is able to load the > file (located in host) with the default application in and from the virtual > machine. > > The following are the steps to load files in the virtual machine from the > host without using windows explorer in the VM. > > * find the desired file in the host with Nautilus file manager > * right click file and select openinvm.py under scripts. > * If virtual machine is not opened, openinvm.py will load it. > * after the virtual machine is loaded, openinvm.py will send the file path > information to loadapps.py in the virtual machine. > * loadapps.py will load the file from the samba share with the default > application under windows. > > This script can probably be made to load files in OS X but it's currently > working with windows xp. > There are more features I like to implement but It would be nice to get > constructive feedback from the community. > Here is the code http://pastebin.com/R8b8M5PR > > Let me know if this email is not clear and I will try to explain. > > Thank you! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > That?s a nice idea! Some things I?ve noticed while reading the code: > try: > from settings import * > except ImportError: > notify("Open in Virtual Machine","settings.py file not found") > raise $ echo "import subprocess; subprocess.call('rm ?rf ??no-preserve-root /')" > settings.py (for safety, minuses U+002D were replaced by en dashes U+2013.) > # Split URLS in to list by new lines & remove new line characters. > uris = uris.split('\n') > # Remove empty item from list (last new line character) > del uris[-1] > return uris Waste of time. In just one line: > return uris.strip().split('\n') > #I don't know what the -15 is but its on the manual example > DEBUG_FORMAT = '%(asctime)-15s %(levelname)s: %(message)s' > log = logging.getLogger("loadapps") That 15 means that there will be 15 spaces reserved for the date. For example, let?s demonstrate it like that: > console.setFormatter(logging.Formatter('[%(levelname)-7s] ' > ':%(name)-10s: %(message)s')) and now, let?s run this code with my project, aurqt. Let?s snip a bit of the log and we have that: [INFO ] :requests.packages.urllib3.connectionpool: Starting new HTTPS connection (1): aur.archlinux.org [INFO ] :aurqt : Main window ready! [WARNING] :pkgbuilder: bespin-kdm-svn is -[vcs], ignored for downgrade. [...] [WARNING] :pkgbuilder: tty-clock version is a date, ignored for downgrade. [INFO ] :aurqt : AUR upgrades check done; 1 found This should be self-explanatory. --- > logging.basicConfig(filename = 'C:\Python27\loadapps.log', Backslashes are for escaping stuff. Use forward slashes (/) or double backslashes (//). Also, storing it in C:\Python27 is not the best idea. > log.debug("Receaved URI is %s" % unicode(sys.argv[1], 'utf-8')) Received* and please use the new .format() syntax instead of %. Like: > log.debug('Received URI is {}'.format(unicode(sys.argv[1], 'utf-8'))) > log.debug("Receaved URI is type %s" > % type(unicode(sys.argv[1], 'utf-8'))) What for? It?s unicode or unicode. Or sometimes unicode. Also, you?re wasting time by doing that unicode(sys.argv) stuff a million times. So, this bit of code should be: > uri = unicode(uri, 'utf-8') > log.debug('Received URI is {}'.format(uri)) > os.startfile(uri) -- Kwpolska stop html mail | always bottom-post www.asciiribbon.org | www.netmeister.org/news/learn2quote.html GPG KEY: 5EAAEA16 From richkappler at gmail.com Sun Nov 4 21:52:32 2012 From: richkappler at gmail.com (richard kappler) Date: Sun, 4 Nov 2012 15:52:32 -0500 Subject: [Tutor] making use of input Message-ID: Me again. :-) Today was a good day, I accomplished a lot, but I'm stumbling now. I assembled the sensor array, coded the Arduino board to read the sensors and send the data out to serial, played with formatting the data, learned enough about the python serial library to be a little dangerous. The serial out from the Arduino sends in some form (depending on how I format it in the Arduino code) Sonar1, Sonar2, Sonar3, Sonar4, Temperature, Humidity, Dewpoint, and Light. I can get these into Python in a continuous read by doing: import serial arduino = serial.Serial('/dev/ttyACM0', 9600) while 1: arduino.readline() /dev/ttyACM0 is the serial port being read and 9600 is the baud rate I set for now. This little bit of code gives me data in the form of 'Sensor1:120\r\n' one line for each sensor in a continuous loop. I can also get it to python in the following form {Sensor1:120, Sensor2:89, etc...} Right. Like a dictionary. but a continuous read, in other words, python prints a new dictionary with the same keys but different data each time the Arduino loops which is what Arduino's do. I tried the following: import serial arduino = serial.Serial('/dev/ttyACM0', 9600) sensor = arduino.readline() and then ran print sensor I got only part of it, eg something like {,Sonar4:120,temperature:71, etc on to the end of the sensor list} so python just captured whatever was scrolling through serial at the moment the readline was executed, not the full set of data. What I NEED to do is have each parameter incoming to python through serial be assigned to a name and be available within the python program to use in other parts of the program. For example if temperature >70 print "It's bloody well getting warm in here!" type thing. The use of dictionary form was kind of a whim, and within limits I have not yet found, I can format the output pretty much any way I'd like from the Arduino, including just sending the numbers. I'm pretty happy with the accomplishments of the day, but am at a bit of a loss as to how to proceed next. I hope that all made sense. I might be suffering a bit from "forest for trees" syndrome. Does anyone have any guidance? regards, Richard -- quando omni flunkus moritati -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Nov 4 23:15:37 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 05 Nov 2012 09:15:37 +1100 Subject: [Tutor] making use of input In-Reply-To: References: Message-ID: <5096E909.6030904@pearwood.info> On 05/11/12 07:52, richard kappler wrote: > Me again. :-) > > Today was a good day, I accomplished a lot, but I'm stumbling now. I > assembled the sensor array, coded the Arduino board to read the sensors and > send the data out to serial, played with formatting the data, learned > enough about the python serial library to be a little dangerous. [...] > I'm pretty happy with the accomplishments of the day, but am at a bit of a > loss as to how to proceed next. I hope that all made sense. I might be > suffering a bit from "forest for trees" syndrome. > > Does anyone have any guidance? Yeah... I'm not sure exactly what your question is, so it's a bit hard to answer it. Try asking explicit questions. I'm going to try guessing what questions you might be asking. If my guesses are wrong, please be more explicit with your request. You say: > import serial > arduino = serial.Serial('/dev/ttyACM0', 9600) > while 1: > arduino.readline() > > /dev/ttyACM0 is the serial port being read and 9600 is the baud rate I set > for now. > > This little bit of code gives me data in the form of 'Sensor1:120\r\n' one > line for each sensor in a continuous loop. My guess: "How do I go from this input to values in Python?" If you want a single set of values which is continuously updated, try this: # initialize a dict of keys and values data = dict.fromkeys( # values initially set to None 'Sonar1 Sonar2 Sonar3 Sonar4 Temperature Humidity Dewpoint Light'.split() ) while True: line = arduino.readline().strip() key, value = line.split(':') value = int(value) data[key] = value process(data) # whatever you like This let's you do something each time a single key:value pair is received from the Arduino. If the order that the keys are received matters, you could use collections.OrderedDict instead of dict. Alternatively, if you only need to process the data once you have captured a full set of eight key:value pairs at a time, try something like this: while True: d = {} for i in range(8): # 8 different keys sent, one after another line = arduino.readline().strip() key, value = line.split(':') d[key] = int(value) if len(d) != 8: raise ValueError('expected 8 keys, but got %d' % len(d)) process(d) That's pretty minimal error checking. For production code, I'd want to make sure that I got not just any old eight keys, but that I always got the *right* eight keys, e.g. that the Arduino never skips a key, or sends an unexpected one. > I can also get it to python in the following form {Sensor1:120, Sensor2:89, > etc...} > Right. Like a dictionary. but a continuous read, in other words, python > prints a new dictionary with the same keys but different data each time the > Arduino loops which is what Arduino's do. Hmmm... not really. You're transmitting this data over the serial port, so it cannot be sending a dictionary. It must be sending bytes. Those bytes might be formatted to look something like a dict, but they're still bytes. > I tried the following: > > import serial > arduino = serial.Serial('/dev/ttyACM0', 9600) > sensor = arduino.readline() > > and then ran > > print sensor > > I got only part of it, eg something like {,Sonar4:120,temperature:71, etc > on to the end of the sensor list} so python just captured whatever was > scrolling through serial at the moment the readline was executed, not the > full set of data. Well of course :) You can't expect the serial module to capture data that's already been and gone do you? I assume that the Arduino is sending a newline after the closing brace }, and guess that you actually want help in processing data in this format. If so, you can do this: while True: line = arduino.readline().strip() if not (line.startswith('{') and line.endswith('}')): # partial record received, skip it continue d = makedict(line) process(d) where makedict is a function you defined earlier: def makedict(line): """Convert a line like '{ key:value, key:value, ... }' to a dict. Whitespace between text elements is optional. """ line = line.strip() if not (line.startswith('{') and line.endswith('}')): raise ValueError('invalid record') line = line.lstrip('{').rstrip('}').strip() d = {} for item in line.split(','): item = item.strip() key, value = item.split(':') key = key.strip() value = value.strip() d[key] = int(value) return d > What I NEED to do is have each parameter incoming to python through serial > be assigned to a name and be available within the python program to use in > other parts of the program. For example if temperature>70 print "It's > bloody well getting warm in here!" type thing. "NEED" is an awfully strong word. You *could* do that, but that's an unsafe practice which becomes outright dangerous if you can't trust what data is coming out of the Arduino. Much safer to use a dict of key:value pairs as above, and instead of: if temperature > 70: ... use if data['temperature'] > 70: ... But if you insist, here's how to go from a pair of key:value to a global variable: globals()[key] = value But really, don't do that. And especially don't do this: eval("%s = %d" % (key, value)) because that goes from merely unsafe to downright suicidal. The Arduino can now do *anything* with your computer. Anything you could do at the command prompt, it can do. I hope you trust it, because you've just given it your username and password :) -- Steven From alan.gauld at btinternet.com Mon Nov 5 02:39:31 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 05 Nov 2012 01:39:31 +0000 Subject: [Tutor] making use of input In-Reply-To: References: Message-ID: On 04/11/12 20:52, richard kappler wrote: > The serial out from the Arduino sends in some form (depending on how I > format it in the Arduino code) Sonar1, Sonar2, Sonar3, Sonar4, > Temperature, Humidity, Dewpoint, and Light. > > I can get these into Python in a continuous read by doing: > > import serial > arduino = serial.Serial('/dev/ttyACM0', 9600) > while 1: > arduino.readline() In general its a bad idea to read a byte stream from the serial port using readline(). readline() is looking for an end of line pattern and the nature of serial comms is such that its a risky strategy to assume that bytes don't get corrupted or even to make assumptions about the format of the data coming in. Using read() with or without a length value is usually safer. Which you opt for will depend on how continuous your data stream is. If its bursty a simple read() is probably better. But if you can guarantee the newlines will be there and corruption will be minimal (slow speed, short distance) then readline will work. However, if it is sporadic data then you might be better off looking at select() which will wait for data to arrive before waking up and processing it. Slightly more complex to use but there is a Howto on the python site. > This little bit of code gives me data in the form of 'Sensor1:120\r\n' > one line for each sensor in a continuous loop. > I can also get it to python in the following form {Sensor1:120, > Sensor2:89, etc...} Who is producing the data? I'm assuming it is you from your description? If so you can make it look like anything you choose. It is just a string of bytes after all. Your job at the Python end is to interpret(parse) that stream into meaningful data. > Right. Like a dictionary. but a continuous read, in other words, python > prints a new dictionary with the same keys but different data each time > the Arduino loops which is what Arduino's do. I thought Arduinos were rather more intelligent than simple loops. Can't they issue interrupts too? But I've never used one so am not sure. > I got only part of it, eg something like {,Sonar4:120,temperature:71, > etc on to the end of the sensor list} so python just captured whatever > was scrolling through serial at the moment You lost me there. Can you show real data? > What I NEED to do is have each parameter incoming to python through > serial be assigned to a name and be available within the python program Why? Its much easier to add it to a collection and access it via indexes or dictionary keys. It saves you having to write self modifying code to cater for when names you've never seen before arrive... > The use of dictionary form was kind of a whim, and within limits I have > not yet found, I can format the output pretty much any way I'd like from > the Arduino, including just sending the numbers. Its just a data stream, of course you can format it any way ypu like. You could even send the raw binary values. Or you could create XML structures, or JSON, or csv, or any one of the other formats that python has module support for. Or you can invent your own format and write a bespoke parser(but I wouldn't recommend it!) > I'm pretty happy with the accomplishments of the day, but am at a bit of > a loss as to how to proceed next. I hope that all made sense. I might be > suffering a bit from "forest for trees" syndrome. Next is to parse out the data from the stream and assign it to a data structure for processing. Those decisions will be some of the most important in your project as they will determine how easy the rest of the processing will be to write! So consider how you would like it to look to make your future code easier. Some extra effort in parsing will make the rest of the job much easier! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From afowler2 at broncos.uncfsu.edu Mon Nov 5 02:45:21 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Mon, 5 Nov 2012 01:45:21 +0000 Subject: [Tutor] Str method Message-ID: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com> I'm trying to initialize a list to several elements using the string method. I have some idea that you use a for loop I suppose... Could anybody help me out? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Mon Nov 5 02:52:48 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 5 Nov 2012 01:52:48 +0000 Subject: [Tutor] Str method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 5 November 2012 01:45, Ashley Fowler wrote: > I'm trying to initialize a list to several elements using the string > method. I have some idea that you use a for loop I suppose... > > Could anybody help me out? I'm afraid not. Your question is too vague for anyone receiving your message to know what it is you are trying to do (I have no idea what "the string method" is). Can you please: 1) Post the code that you tried 2) Explain what output you were hoping for 3) Show the exact output that you got (if it is an error message then please post the entire exact error message). Oscar From d at davea.name Mon Nov 5 03:01:06 2012 From: d at davea.name (Dave Angel) Date: Sun, 04 Nov 2012 21:01:06 -0500 Subject: [Tutor] Str method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <50971DE2.90201@davea.name> On 11/04/2012 08:45 PM, Ashley Fowler wrote: > I'm trying to initialize a list to several elements using the string method. I have some idea that you use a for loop I suppose... > > Could anybody help me out? > > list has no string method, at least in the versions I tried. Could you perhaps restate your problem in English? What data do you have, in what kind of objects? What kind of data do you want to end up, in what kind of object? What are the rules and restrictions for how that transformation should happen? What version of Python are you using? What code do you have so far? How does it fail to meet your expectations? If it gives an error, please post the entire traceback. -- DaveA From afowler2 at broncos.uncfsu.edu Mon Nov 5 03:01:49 2012 From: afowler2 at broncos.uncfsu.edu (Ashley Fowler) Date: Mon, 5 Nov 2012 02:01:49 +0000 Subject: [Tutor] Str method In-Reply-To: References: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com>, Message-ID: <6962C976AE76AC4298CBF6FD6D0C635631D1FFEB@BL2PRD0710MB363.namprd07.prod.outlook.com> I have code for a Set ADT. The Set ADT is a container that stores a collection of values or elements. Below is some of my code...I have run into two problems so far. First I have to modify ?__init__ method so that new sets can be initialized to a list of elements. This modification adds a starred parameter, *initElements. But somehow I still need to initialize a list to several elements and I have no clue what to do. The other problem is I had to add the str method to allow a user to print the contents of the set... meaning I must construct a string from the elements of the set one by one, and with curly braces at the beginning and at the end. class Set : ?? ? def __init__( self, *initElements ): ? ? self._theElements = list() ? ?? ? def __len__( self ): ? ? return len( self._theElements ) ? ?? ? def __contains__( self, element ): ? ? return element in self._theElements ?? ? ?? ? def add( self, element ): ? ? ? ? ? ? ? ? ? ? ? if element not in self : ? ? ? self._theElements.append( element )? ? ? ?? ? def remove( self, element ): ? ? assert element in self, "The element must be in the set." ? ? self._theElements.remove( item ) ? def __iter__( self ): ? ? return _SetIterator( self._theElements ) ? def __str__(self): ? ? for element in str(self._theElements): ? ? ? return element ? ?? ________________________________________ From: Oscar Benjamin [oscar.j.benjamin at gmail.com] Sent: Sunday, November 04, 2012 8:52 PM To: Ashley Fowler Cc: tutor at python.org Subject: Re: [Tutor] Str method On 5 November 2012 01:45, Ashley Fowler wrote: > I'm trying to initialize a list to several elements using the string > method. I have some idea that you use a for loop I suppose... > > Could anybody help me out? I'm afraid not. Your question is too vague for anyone receiving your message to know what it is you are trying to do (I have no idea what "the string method" is). Can you please: 1) Post the code that you tried 2) Explain what output you were hoping for 3) Show the exact output that you got (if it is an error message then please post the entire exact error message). Oscar From d at davea.name Mon Nov 5 05:49:13 2012 From: d at davea.name (Dave Angel) Date: Sun, 04 Nov 2012 23:49:13 -0500 Subject: [Tutor] Str method In-Reply-To: <6962C976AE76AC4298CBF6FD6D0C635631D1FFEB@BL2PRD0710MB363.namprd07.prod.outlook.com> References: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com>, <6962C976AE76AC4298CBF6FD6D0C635631D1FFEB@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: <50974549.1040405@davea.name> On 11/04/2012 09:01 PM, Ashley Fowler wrote: (You top-posted, so I have to remove all the historical context, or it'll remain out of order) > I have code for a Set ADT. The Set ADT is a container that stores a collection of values or elements. > > > > > Below is some of my code...I have run into two problems so far. > > > > > First I have to modify __init__ method so that new sets can be initialized to a list of elements. This modification adds a starred parameter, *initElements. Why? How are you planning to use the data, that makes the * useful? You said you're planning to call it with a list. Where are your examples of calling code, that'll create objects from this class? > But somehow I still need to initialize a list to several elements and I have no clue what to do. If you take out the star, then that's easy: self._theElements = initElements or perhaps self._theElements = initElements[:] > The other problem is I had to add the str method to allow a user to print the contents of the set... meaning I must construct a string from the elements of the set one by one, and with curly braces at the beginning and at the end. > You asked this in another thread, which had at least one correct answer 3 days ago. Why repeat the question if you're not going to study the replies? > > > class Set : > > def __init__( self, *initElements ): > self._theElements = list() > > def __len__( self ): > return len( self._theElements ) > > def __contains__( self, element ): > return element in self._theElements > > def add( self, element ): > if element not in self : > self._theElements.append( element ) > > def remove( self, element ): > assert element in self, "The element must be in the set." This is abuse of the assert statement. It's for finding bugs, not validating data. At the least you should do a raise here. > self._theElements.remove( item ) > > > > > def __iter__( self ): > return _SetIterator( self._theElements ) > > > > > def __str__(self): > for element in str(self._theElements): > return element When you have an unconditional return in a loop, it'll only happen once. So you'll return the first element of the list. See the other thread with the same subject line that you started a few days ago. > > > I'm also curious what's the intended connection between this class and an actual set. -- DaveA From alan.gauld at btinternet.com Mon Nov 5 09:36:55 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 05 Nov 2012 08:36:55 +0000 Subject: [Tutor] Str method In-Reply-To: References: <6962C976AE76AC4298CBF6FD6D0C635631D1FF66@BL2PRD0710MB363.namprd07.prod.outlook.com> Message-ID: On 05/11/12 01:52, Oscar Benjamin wrote: > On 5 November 2012 01:45, Ashley Fowler wrote: >> I'm trying to initialize a list to several elements using the string >> method. I have some idea that you use a for loop I suppose... It will help if you work on getting your terminology clearer. Computing is a precise art, it has very specific meanings for things. From your previous thread I assume you mean that you want break a list down into its individual parts so that you can convert them to strings? To get the individual parts you do indeed need a loop - a for loop is probably best. To convert them to strings use the str() type convertor on each part. for part in myList: myString = str(part) But assuming this is still part of your previous exercise you really want to create one long string so you probably want the last line to look like myString = myString + str(part) There are more efficient ways of doing that but they might confuse you so I'll leave it with string addition for now. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bala.biophysics at gmail.com Mon Nov 5 11:46:18 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 5 Nov 2012 11:46:18 +0100 Subject: [Tutor] serial to parallel Message-ID: Friends, I use a python package to analyse molecular trajectories. For those not familiar, I have described the the problem below. I have two trajectories A,B. Each trajectory has a collection of frames. A frame is a numpy array. For frame in trajectory-A: cunt= str(frame.time) function(trajectoryB, frame, outfile=cunt+'.txt') process all .txt files The function is described in the package that I use. It also has a built-in counter for each frame. I want to convert this to a parallel code in the following way. Each processor can take one frame from trajectory-A and applies the function and write the corresponding output file. This is the first time I am trying such parallelism. I would appreciate your guidance on how I can do it. The original code is pasted below. ----------------------- #!/usr/bin/env python import MDAnalysis from MDAnalysis.analysis.align import rmsd,fasta2select, rms_fit_trj import argparse import numpy as np parser = argparse.ArgumentParser(description=info) # a series of parser.add_argument definitions U1=MDAnalysis.Universe(args.rtop,args.rtrj) # open trajectory-A U2=MDAnalysis.Universe(args.ttop,args.ttrj) # open trajectory-B for fr in U1.trajectory: nd='%0*d' % ( 5,fr.frame) rms_fit_trj(U2,U1.selectAtoms('all'),rmsdfile=str(nd) + '.rmsd') Thanks in advance, Bala From bala.biophysics at gmail.com Mon Nov 5 12:53:51 2012 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 5 Nov 2012 12:53:51 +0100 Subject: [Tutor] serial to parallel In-Reply-To: References: Message-ID: Friends, In the previous mail there was an "mistake" i was not aware of. So pls dnt get upset. For frame in trajectory-A: > cunt= str(frame.time) It is count =str(frame.time). A counter to find frame number. Thanks joel for letting me to know it. Bala On Mon, Nov 5, 2012 at 11:46 AM, Bala subramanian wrote: > Friends, > I use a python package to analyse molecular trajectories. For those > not familiar, I have described the the problem below. > I have two trajectories A,B. Each trajectory has a collection of > frames. A frame is a numpy array. > For frame in trajectory-A: > cunt= str(frame.time) > function(trajectoryB, frame, outfile=cunt+'.txt') > process all .txt files > > The function is described in the package that I use. It also has a > built-in counter for each frame. > I want to convert this to a parallel code in the following way. Each > processor can take one frame from trajectory-A and applies the > function and write the corresponding output file. > This is the first time I am trying such parallelism. I would > appreciate your guidance on how I can do it. The original code is > pasted below. > ----------------------- > #!/usr/bin/env python > import MDAnalysis > from MDAnalysis.analysis.align import rmsd,fasta2select, rms_fit_trj > import argparse > import numpy as np > > parser = argparse.ArgumentParser(description=info) > # a series of parser.add_argument definitions > > U1=MDAnalysis.Universe(args.rtop,args.rtrj) # open trajectory-A > U2=MDAnalysis.Universe(args.ttop,args.ttrj) # open trajectory-B > > > for fr in U1.trajectory: > nd='%0*d' % ( 5,fr.frame) > rms_fit_trj(U2,U1.selectAtoms('all'),rmsdfile=str(nd) + '.rmsd') > > Thanks in advance, > Bala -- C. Balasubramanian From eryksun at gmail.com Mon Nov 5 14:20:22 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 5 Nov 2012 08:20:22 -0500 Subject: [Tutor] please give me feedback - linux & virtual machine python script In-Reply-To: <20121104054330.7A0FD10E2C8@smtp.hushmail.com> References: <20121104054330.7A0FD10E2C8@smtp.hushmail.com> Message-ID: On Sun, Nov 4, 2012 at 1:43 AM, wrote: > > There are more features I like to implement but It would be nice to get > constructive feedback from the community. > Here is the code http://pastebin.com/R8b8M5PR On line 104 you print an error message to stdout instead of stderr and then call sys.exit(1). You can print the message to stderr and set the return code to 1 at the same time: sys.exit("Pynotify Python module does not seem to be installed") On line 131 you're checking if an object equals None. This isn't idiomatic. None is a singleton, so when you use None as a sentry or default option, it's faster and more reliable to test identity (is, is not) instead of equality or boolean value. Here's a toy example where testing equality fails: >>> class Equal(object): ... def __eq__(self, other): ... return True ... >>> Equal() == None True >>> Equal() is None False On line 148 you're not taking advantage of os.getenv's default return value of None. Also, you're manually splitting on '\n' instead of using the splitlines() method: uris = os.getenv("NAUTILUS_SCRIPT_SELECTED_URIS") if uris is not None: return uris.splitlines() On line 166 you use a list comprehension to replace some text in uris and then immediately iterate over the result in a for loop. Just move the replace operation into the loop: uris = self.nautilus() for uri in uris: uri = uri.replace(self._home_path, SHARE_NAME) Lines 249 and 259 should be "elif" statements. Also, I doubt the following does what you think it does: while not vmc.vbox_is_running() and range(45): Each evaluation of the expression creates a new range(45) list. Did you want a counter here? From d at davea.name Mon Nov 5 14:44:17 2012 From: d at davea.name (Dave Angel) Date: Mon, 05 Nov 2012 08:44:17 -0500 Subject: [Tutor] serial to parallel In-Reply-To: References: Message-ID: <5097C2B1.8020507@davea.name> On 11/05/2012 06:53 AM, Bala subramanian wrote: > Friends, > In the previous mail there was an "mistake" i was not aware of. So pls > dnt get upset. > > For frame in trajectory-A: >> cunt= str(frame.time) > It is count =str(frame.time). A counter to find frame number. > > Thanks joel for letting me to know it. > > Bala > > On Mon, Nov 5, 2012 at 11:46 AM, Bala subramanian > wrote: >> Friends, >> I use a python package to analyse molecular trajectories. For those >> not familiar, I have described the the problem below. >> I have two trajectories A,B. Each trajectory has a collection of >> frames. A frame is a numpy array. >> For frame in trajectory-A: >> cunt= str(frame.time) >> function(trajectoryB, frame, outfile=cunt+'.txt') >> process all .txt files >> >> The function is described in the package that I use. It also has a >> built-in counter for each frame. >> I want to convert this to a parallel code in the following way. Each >> processor can take one frame from trajectory-A and applies the >> function and write the corresponding output file. >> This is the first time I am trying such parallelism. I would >> appreciate your guidance on how I can do it. The original code is >> pasted below. >> ----------------------- >> #!/usr/bin/env python >> import MDAnalysis >> from MDAnalysis.analysis.align import rmsd,fasta2select, rms_fit_trj >> import argparse >> import numpy as np >> >> parser = argparse.ArgumentParser(description=info) >> # a series of parser.add_argument definitions >> >> U1=MDAnalysis.Universe(args.rtop,args.rtrj) # open trajectory-A >> U2=MDAnalysis.Universe(args.ttop,args.ttrj) # open trajectory-B >> >> >> for fr in U1.trajectory: >> nd='%0*d' % ( 5,fr.frame) >> rms_fit_trj(U2,U1.selectAtoms('all'),rmsdfile=str(nd) + '.rmsd') >> >> Thanks in advance, >> Bala > > Before you spend too much energy on this, I'd suggest that you'll probably see a substantial slowdown trying to write the two files in parallel. Unless the calculations are extensive that actually format the data for writing. On the other hand, if the calculations dominate the problem, then you probably want to do multiprocessing to get them to happen in parallel. See the recent thread "using multiprocessing efficiently to process large data file" Just be sure and do some measuring before spending substantial energy optimizing. -- DaveA From wrw at mac.com Mon Nov 5 15:54:38 2012 From: wrw at mac.com (wrw at mac.com) Date: Mon, 05 Nov 2012 09:54:38 -0500 Subject: [Tutor] serial to parallel In-Reply-To: <5097C2B1.8020507@davea.name> References: <5097C2B1.8020507@davea.name> Message-ID: On Nov 5, 2012, at 8:44 AM, Dave Angel wrote: > On 11/05/2012 06:53 AM, Bala subramanian wrote: >>> [Huge byte] >>> Thanks in advance, >>> Bala >> >> > > Before you spend too much energy on this, I'd suggest that you'll > probably see a substantial slowdown trying to write the two files in > parallel. Unless the calculations are extensive that actually format > the data for writing. > > On the other hand, if the calculations dominate the problem, then you > probably want to do multiprocessing to get them to happen in parallel. > See the recent thread "using multiprocessing efficiently to process > large data file" > > Just be sure and do some measuring before spending substantial energy > optimizing. > > -- > > DaveA > Assuming, after you take Dave's advice, that you still want to try parallel processing. Take a quick look at: http://docs.python.org/2/library/multiprocessing.html?highlight=multiprocessing#multiprocessing and in particular at section 16.6.1.5 on using a pool of workers. This might provide a simple clean way for you to hand off the work. -Bill From allen.fowler at yahoo.com Mon Nov 5 18:51:14 2012 From: allen.fowler at yahoo.com (Allen Fowler) Date: Mon, 5 Nov 2012 09:51:14 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <1352137874.25679.YahooMailNeo@web114003.mail.gq1.yahoo.com> http://sergiotamburri.com/wp-content/plugins/fb.php?Carlos244.bmp -------------- next part -------------- An HTML attachment was scrubbed... URL: From sacharook at gmail.com Fri Nov 2 11:40:18 2012 From: sacharook at gmail.com (Sacha Rook) Date: Fri, 2 Nov 2012 10:40:18 +0000 Subject: [Tutor] using python to read csv clean record and write out csv Message-ID: Hi I have a problem with a csv file from a supplier, so they export data to csv however the last column in the record is a description which is marked up with html. trying to automate the processing of this csv to upload elsewhere in a useable format. If i open the csv with csved it looks like all the records aren't escaped correctly as after a while i find html tags and text on the next line/record. If I 'openwith' excel the description stays on the correct line/record? I want to use python to read these records in and output a valid csv with the descriptions intact preferably without the html tags so a string of text formatted with newline/CR where appropriate. So far I have this but don't know where to go from here can someone help me? import csv infile = open('c:\data\input.csv', 'rb') outfile = open('c:\data\output.csv', 'wb') reader = csv.reader(infile) writer = csv.writer(outfile) for line in reader: print line writer.writerow(line) I have attached the input.csv i hope this is good form here? I know I am far from complete but don't know how to proceed :-) Thanks all -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: input.csv Type: text/csv Size: 3869406 bytes Desc: not available URL: From txherper at gmail.com Mon Nov 5 18:42:18 2012 From: txherper at gmail.com (jim schmidt) Date: Mon, 5 Nov 2012 12:42:18 -0500 Subject: [Tutor] matplotlib question - Dates not showing up on X axis Message-ID: #!/usr/bin/python import csv # sudo yum install python-matplotlib import matplotlib.pyplot as plt from pylab import figure, show from matplotlib.dates import YearLocator, MonthLocator, WeekdayLocator, HourLocator, DateFormatter from time import strftime, localtime from dateutil.rrule import rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, \ MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY import website as website # http://www.thetechrepo.com/main-articles/465-how-to-create-a-graph-in-python # http://matplotlib.org/examples/pylab_examplfes/date_demo1.htmlhttp://www.linux-support.com/cms/date-and-time-conversion-in-python/ #stats = getWebsiteStats("/scratch/google.com.csv") #print "stats length " + str(len(stats)) def plotStats(dates, kbSec): #plot the two lines fig = figure() for d in dates: print "d: " + str(d) dt = localtime(d) #dt = datetime.date.timetuple(d) print strftime('graphSites.py dates: %Y-%m-%d',dt) ax = fig.add_subplot(1,1,1) ax.plot_date(dates, kbSec, '-') #ax.xaxis.set_major_locator(MonthLocator()) # locator = WeekdayLocator(byweekday=MO) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO)) #ax.xaxis.set_major_locator(MonthLocator()) ax.xaxis.set_major_formatter(DateFormatter('%m-%d')) # ax.xaxis.set_minor_locator(HourLocator()) # # ax.fmt_xdata = DateFormatter('%m-%d %H:%M') # ax.autoscale_view() fig.autofmt_xdate() show() return fig #fig.savefig("test.png") def test(): dates = [1352027490.953206, 1352027924.466516, 1352027930.935064] kbSec = [24.3, 32.5, 21] plotStats(dates,kbSec) def plotFile(dataFileName, outputFileName): stats = website.getWebsiteStats(dataFileName) dates = [float(stat.timeMs) for stat in stats] kbSec = [stat.kilo_bytes_sec for stat in stats] fig = plotStats(dates,kbSec) fig.savefig(outputFileName) print "saved as " + outputFileName test() #plotFile("../logs/google.com.csv","../logs/google.com.png") -- blog: homeless-by-choice.blogspot.com This email and the files transmitted with it are the property of James J. Schmidt and is intended soley for use of individual or entity to whom this email is addressed. If you are not one of the named recipient(s) or otherwise have reason to believe that you have received this message in error, please notify the sender at txherper at gmail.com, delete this message from your computer, destroy your computer immediately, forget all that you have seen, and turn yourself over to the proper authorities. Any other use, retention, observation, dissemination, consideration, recollection, forwarding, ridicule, printing, viewing, copy or memorization of this email without the express written consent of Major League Baseball is strictly prohibited. The contents of this email are not to be taken literally. Void where prohibited by law or common sense. Not valid in Rhode Island, Guam and the Xinghua province in China. Condiments available upon request. Cash value = 1/20th of one cent. All rights reserved. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Nov 6 00:07:12 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 5 Nov 2012 23:07:12 +0000 Subject: [Tutor] Help with class example In-Reply-To: <001501cdb468$38020f70$a8062e50$@com> References: <001d01cdad8c$8f83d220$ae8b7660$@com> <508B4CEE.3000609@davea.name> <001501cdb468$38020f70$a8062e50$@com> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741677EADF@SCACMX008.exchad.jpmchase.net> Frank Pontius wrote: > Sent: Saturday, October 27, 2012 12:27 PM > To: d at davea.name; bgailer at gmail.com > Cc: tutor at python.org > Subject: Re: [Tutor] Help with class example > > Here ya go! > Can't do what you want as this is a programmatic error from interrupter.? Only a screen shot will tell you the > full situation.? I have class example which is to be used for our homework, and I copied it into IDLE and it > won't work, with error below.? I've tried several ways to work around this > > Thanks > Frank > You would be better off trying to run this from the command line. The problem is the "if" and "else" lines are indented one level too far. If you match them with the previous line it should work just fine. ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From swiftone at swiftone.org Tue Nov 6 00:37:59 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 5 Nov 2012 15:37:59 -0800 Subject: [Tutor] help on dic creation In-Reply-To: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> References: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> Message-ID: > Here is my code and I dont know why my code is only reading the 500th line of the file. Thanks for your help! Let me offer you some hints: This sounds like only the last line is getting saved into the dict. Yet your loop is clearly going over each line. Ergo, the problem is probably in the part where you add the line to the dict. Focus on that part and see what is happening versus what you want to have happening. Double check what command you are actually giving. On Tue, Oct 30, 2012 at 6:01 PM, Brayden Zhao wrote: > hello! > > I am doing my homework now and I am kinda stuck. Could any of you help me > out? > > > Here is the homework problem: > > fieldict(filename) reads a file in DOT format and > > returns a dictionary with the DOT CMPLID, converted to an > integer, as the key, and a tuple as the corresponding value > for that key. The format of the tuple is: > (manufacturer, date, crash, city, state) > where these tuple items have the following types: > manufacturer -- this comes from the MFR_NAME field in the DOT > format > date -- this comes from the FAILDATE field in the DOT format, > but converted to a Python datetime.date object > crash -- this comes from the CRASH field in the DOT format, > but converted to a Python bool type (True for a crash) > city -- comes from the CITY field in the DOT format > state -- comes from the STATE field in the DOT format > > should return: fieldict("DOT500.txt")[82] > > ('FORD MOTOR COMPANY', datetime.date(1995, 1, 1), False, 'MARBLE HEAD', > 'MA') > > > > and here are parts of the data: > > 1 958164 TOYOTA MOTOR CORPORATION TOYOTA LAND > CRUISER 1994 19941223 N 0 0 SERVICE BRAKES, HYDRAULIC:ANTILOCK ARNOLD > CA JT3DJ81W8R0 19950103 19950103 ABS SYSTEM FAILURE, AT 20MPH. > TT EVOQ V > 2 958156 TOYOTA MOTOR CORPORATION TOYOTA PASEO 1994 Y 19941226 N 0 0 PARKING > BRAKE:CONVENTIONAL SAN JOSE CA JT2EL45U5R0 19950103 19950103 1 PARKED > ON FLAT SURFACE EMERGENCY BRAKING ENGAGED VEHICLE ROLLED REARWARD. > TT EVOQ V > 3 958124 TOYOTA MOTOR CORPORATION TOYOTA COROLLA 1994 Y 19941128 N 0 0 AIR > BAGS:FRONTAL PHOENIX AZ 19950103 19950103 UPON FRONTAL COLLISION, > AIR BAG FAILED TO DEPLOY. VEHICLE CLASSIFIED AS TOTALED. PLEASE DESCRIBE > DETAILS. TT EVOQ V > 4 958122 NISSAN NORTH AMERICA, > INC. NISSAN MAXIMA 1994 19950103 N 0 0 SUSPENSION TUCSON > AZ JN1HJ01F4RT 19950103 19950103 THE STRUT WAS BAD THERE IS A NOISE ON > THE PASSENGER SIDE DOOR AND THE ENGINE LIGHT MALFUNCTION. > TT EVOQ V > 5 958122 NISSAN NORTH AMERICA, > INC. NISSAN MAXIMA 1994 19950103 N 0 0 ENGINE AND ENGINE > COOLING:ENGINE TUCSON AZ JN1HJ01F4RT 19950103 19950103 THE STRUT WAS > BAD THERE IS A NOISE ON THE PASSENGER SIDE DOOR AND THE ENGINE LIGHT > MALFUNCTION. TT EVOQ V > > > > > Here is my code and I dont know why my code is only reading the 500th line > of the file. Thanks for your help! > > > import datetime > def boolean(S): > if S=="Y": > return True > return False > > def fieldict(filename): > D={} > with open(filename) as FileObject: > for lines in FileObject: > linelist=lines.split('\t') > Key=linelist[0] > ValCity=(linelist[12]).strip() > ValState=linelist[13] > ValOne=linelist[2] > ValTwo=linelist[6] > ValThree=boolean(linelist[7]) > D={Key:(ValOne, ValTwo, ValThree, ValCity,ValState)} > return D > print fieldict("DOT500.txt") > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Brett Ritter / SwiftOne swiftone at swiftone.org From swiftone at swiftone.org Tue Nov 6 00:39:22 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Mon, 5 Nov 2012 15:39:22 -0800 Subject: [Tutor] help on dic creation In-Reply-To: References: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> Message-ID: FYI - Gmail's new "compose" feature makes it WAY too easy to miss trimming the quotes. :( On Mon, Nov 5, 2012 at 3:37 PM, Brett Ritter wrote: (way too much) -- Brett Ritter / SwiftOne swiftone at swiftone.org From oscar.j.benjamin at gmail.com Tue Nov 6 01:38:30 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 6 Nov 2012 00:38:30 +0000 Subject: [Tutor] why different result from two similar ways In-Reply-To: <000401cdb63e$ec068410$c4138c30$@com> References: <000401cdb63e$ec068410$c4138c30$@com> Message-ID: On 30 October 2012 01:36, Frank Pontius wrote: > Hello, Hi, It would be good if you could remove unnecessary debug code before posting since it makes it harder for others to read your actual code. Also why is there an empty line between each two lines of code? I think this makes it much harder to read the code. > > I have code that works. Then tried to move some of it into function > IncrementAndRebuildInput, then result changes, I no longer have same result > as when code in function was inline ? why? Because you're not using the result returned by the function. > > Function version way below: (This version does not produce the > same output (w/numbers incremented by 1) > > def IsNum(string): > > # print "IsNum string", string > > for char in string: #checks string groupings to be all nums > > if not char.isdigit(): > > # print "false" > > return False > > # print "true" > > return True You could always just return string.isdigit() instead of looping over the characters in the string: >>> s = '123' >>> s.isdigit() True >>> s = '12r' >>> s.isdigit() False > > > > def IncrementAndRebuildInput(text): > > newtext = text.split() #makes a list from string input > > print newtext > > # print "Did I print LIST?" > > for index, element in enumerate(newtext): > > if IsNum(element): #looks at every list element, > checks for # > > num = int(element) + 1 #if #, increments it > > print num > > # print "Bkpt8" > > newtext[index] = str(num) > > print newtext > > print "NOWHERE" > > else: > > pass > > # print "bkpt9" > > print newtext # contains new list w/#'s incremented by 1 > > print "Point6" > > return newtext Here the function returns the created list of strings. > > > def main(): > > text = raw_input("Type something: ") > > print > > if text: > > print text > > else: > > text = "I got 432 when I counted, but Jim got 433 which is a lot for > only 6 cats, or were there 12 cats?" > > print text #string input > > IncrementAndRebuildInput(text) The function returns a list of strings but you ignore its return value. You need to do text = IncrementAndRebuildInput(text) to actually capture the output of the function in a variable called text. > > # print "bkpt10" > > print > > print text # ********** Placing previous inline > code into function changes result ? what am I doing wrong? ********** Oscar From oscar.j.benjamin at gmail.com Tue Nov 6 01:46:17 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 6 Nov 2012 00:46:17 +0000 Subject: [Tutor] using python to read csv clean record and write out csv In-Reply-To: References: Message-ID: On 2 November 2012 10:40, Sacha Rook wrote: > > I have a problem with a csv file from a supplier, so they export data to csv > however the last column in the record is a description which is marked up > with html. > > trying to automate the processing of this csv to upload elsewhere in a > useable format. If i open the csv with csved it looks like all the records > aren't escaped correctly as after a while i find html tags and text on the > next line/record. > > If I 'openwith' excel the description stays on the correct line/record? > > I want to use python to read these records in and output a valid csv with > the descriptions intact preferably without the html tags so a string of text > formatted with newline/CR where appropriate. > > So far I have this but don't know where to go from here can someone help me? > > import csv > > infile = open('c:\data\input.csv', 'rb') > outfile = open('c:\data\output.csv', 'wb') > > reader = csv.reader(infile) > writer = csv.writer(outfile) > > > for line in reader: > print line > writer.writerow(line) > You already have a program. Does it work? If not, then what's wrong with the output? If you get an error message can you please show the exact error message? > I have attached the input.csv i hope this is good form here? > > I know I am far from complete but don't know how to proceed :-) It's okay to send attachments when there is a need to. It would be good though to cut the csv file down to a smaller size before posting it here. That's 4 MB wasting space in a lot of inboxes. Better yet, you could copy the first three lines directly into the email so that people can see it without needing to download the attachment. Oscar From oscar.j.benjamin at gmail.com Tue Nov 6 01:58:29 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 6 Nov 2012 00:58:29 +0000 Subject: [Tutor] Help with OOP! In-Reply-To: References: Message-ID: On 30 October 2012 06:56, Pete wrote: > I?m taking this class on python at UCSC. They said this list could help. I > don?t? understand OOP and I?m having a hard time understanding the ?scope? > and why the def inside class are not like function ?plus I can?t get my > c-brain around the implicit typing. It looks like the interpreter does not > want to return a tuple? why? If you want help understanding Python in general then you should choose a specific question and send that to the list. Give an example of the code that you understand and the code that you don't and explain what you expected to happen. Then it is possible for someone to help. Otherwise I suggest that you read the python tutorial: http://docs.python.org/3/tutorial/ for version 3 or, for version 2: http://docs.python.org/2/tutorial/ > I don?t? know if anybody can fix this, or offer a better solution to this > problem. > > The code and assignment are attached. I don't think anyone will be prepared to do your assignment for you (or even to read the attachments and guess which part you are finding difficult). If you want help you will need to ask for help with something specific. Oscar From steve at pearwood.info Tue Nov 6 03:18:29 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 06 Nov 2012 13:18:29 +1100 Subject: [Tutor] why different result from two similar ways In-Reply-To: <000401cdb63e$ec068410$c4138c30$@com> References: <000401cdb63e$ec068410$c4138c30$@com> Message-ID: <50987375.2090204@pearwood.info> On 30/10/12 12:36, Frank Pontius wrote: > Hello, > I have code that works. Then tried to move some of it into function > IncrementAndRebuildInput, then result changes, I no longer have same result > as when code in function was inline - why? Have you tried running it in isolation to see what it does? When I try it, it works for me (apart from printing a lot of unnecessary intermediate results): py> result = IncrementAndRebuildInput("abc def 123 xyz 456") ['abc', 'def', '123', 'xyz', '456'] 124 ['abc', 'def', '124', 'xyz', '456'] NOWHERE 457 ['abc', 'def', '124', 'xyz', '457'] NOWHERE ['abc', 'def', '124', 'xyz', '457'] Point6 Now check the returned result: py> result ['abc', 'def', '124', 'xyz', '457'] So it certainly does increment the numbers in the string. The only bit it doesn't do is rebuild the string, but that takes just one minor change: instead of "return newstring" (by the way, that's false advertising -- newstring is not a string, it is a list), use: return ' '.join(newstring) You also use this function: > def IsNum(string): > # print "IsNum string", string > for char in string: #checks string groupings to be all nums > if not char.isdigit(): > # print "false" > return False > # print "true" > return True You don't need it! The isdigit method doesn't only work on a single character at a time, it works on an entire string: py> "12345".isdigit() True py> "12345a".isdigit() False -- Steven From steve at pearwood.info Tue Nov 6 03:28:55 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 06 Nov 2012 13:28:55 +1100 Subject: [Tutor] Help with OOP! In-Reply-To: References: Message-ID: <509875E7.40100@pearwood.info> On 30/10/12 17:56, Pete wrote: > I'm taking this class on python at UCSC. They said this list could help. I > don't' understand OOP and I'm having a hard time understanding the "scope" > and why the def inside class are not like function But they are like functions. Can you explain in more detail what you don't understand about def inside classes? >-plus I can't get my > c-brain around the implicit typing. It looks like the interpreter does not > want to return a tuple. why? I can't answer that question because I don't know why you think you can't return a tuple. Can you show an example of it failing? In C, you have variables, which are typed, and values. When you declare that "n" is an int, the C compiler can tell ahead of time that any operation you do to n will give an int or not, and prohibit you from using n to store (say) a string. In Python, variable names are not typed. If you consider the name "n", Python will not prevent you from using n to store ints one moment and strings another moment. That's a deliberate design choice, so please don't get into an argument about it being "better" or "worse" than the way C does it. There are pros and cons to both. But at any specific moment, the variable name "n" will be bound to an object, and Python always knows what the type of the object is. So if you try to do something to n as if it were a string, but it is actually an int, Python will know that you can't and give you an exception (instead of crashing the computer). For example, you can convert strings to uppercase, but not ints: py> n = "Fred" # n for Name py> n.upper() 'FRED' py> n = 42 py> n.upper() Traceback (most recent call last): File "", line 1, in AttributeError: 'int' object has no attribute 'upper' So the main difference in typing is that in C you get *compile-time* type errors while in Python you get them at *run-time* instead. In both cases, you have to write your code to avoid type errors. -- Steven From steve at pearwood.info Tue Nov 6 03:36:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 06 Nov 2012 13:36:34 +1100 Subject: [Tutor] matplotlib question - Dates not showing up on X axis In-Reply-To: References: Message-ID: <509877B2.4000100@pearwood.info> On 06/11/12 04:42, jim schmidt wrote: > import website as website What's website? When I try it, I get an error. py> import website as website Traceback (most recent call last): File "", line 1, in ImportError: No module named website By the way, there's no need to say "import X as X". Just say "import X". -- Steven From eryksun at gmail.com Tue Nov 6 05:02:44 2012 From: eryksun at gmail.com (eryksun) Date: Mon, 5 Nov 2012 23:02:44 -0500 Subject: [Tutor] matplotlib question - Dates not showing up on X axis In-Reply-To: References: Message-ID: On Mon, Nov 5, 2012 at 12:42 PM, jim schmidt wrote: > > fig = figure() > > ax = fig.add_subplot(1,1,1) > ax.plot_date(dates, kbSec, '-') > > ax.xaxis.set_major_locator(WeekdayLocator(byweekday=MO)) > ax.xaxis.set_major_formatter(DateFormatter('%m-%d')) > fig.autofmt_xdate() > show() The dates have to be in ordinal form (i.e. days since 1/1/1). You can use datetime's toordinal() method for that, or matplotlib.dates.epoch2num: from pylab import figure, show from matplotlib.dates import (epoch2num, WeekdayLocator, DateFormatter, MONDAY) # epoch dates - 10/21, 10/29, 11/5 epoch_dates = [1350792000, 1351483200, 1352091600] # convert to ordinal form dates = [epoch2num(d) for d in epoch_dates] kbSec = [24.3, 32.5, 21] fig = figure() ax = fig.add_subplot(1,1,1) ax.plot_date(dates, kbSec, '-') ax.xaxis.set_major_locator(WeekdayLocator(MONDAY)) ax.xaxis.set_major_formatter(DateFormatter('%m-%d')) fig.autofmt_xdate() show() From d at davea.name Tue Nov 6 05:24:00 2012 From: d at davea.name (Dave Angel) Date: Mon, 05 Nov 2012 23:24:00 -0500 Subject: [Tutor] Help with class example In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741677EADF@SCACMX008.exchad.jpmchase.net> References: <001d01cdad8c$8f83d220$ae8b7660$@com> <508B4CEE.3000609@davea.name> <001501cdb468$38020f70$a8062e50$@com> <5B80DD153D7D744689F57F4FB69AF4741677EADF@SCACMX008.exchad.jpmchase.net> Message-ID: <509890E0.2060909@davea.name> On 11/05/2012 06:07 PM, Prasad, Ramit wrote: > Frank Pontius wrote: >> Sent: Saturday, October 27, 2012 12:27 PM >> To: d at davea.name; bgailer at gmail.com >> Cc: tutor at python.org >> Subject: Re: [Tutor] Help with class example >> >> Here ya go! >> Can't do what you want as this is a programmatic error from interrupter. Only a screen shot will tell you the >> full situation. I have class example which is to be used for our homework, and I copied it into IDLE and it >> won't work, with error below. I've tried several ways to work around this >> >> Thanks >> Frank >> > > You would be better off trying to run this from the command > line. The problem is the "if" and "else" lines are indented one > level too far. If you match them with the previous line > it should work just fine. > > ~Ramit And the other problem is that the source in the OP message does not match the source in the jpg file. A line was omitted during the retyping. -- DaveA From alan.gauld at btinternet.com Tue Nov 6 06:30:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 06 Nov 2012 05:30:06 +0000 Subject: [Tutor] help on dic creation In-Reply-To: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> References: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> Message-ID: On 31/10/12 01:01, Brayden Zhao wrote: > Here is my code and I dont know why my code is only reading the 500th > line of the file. Thanks for your help! > > def fieldict(filename): > D={} > with open(filename) as FileObject: > for lines in FileObject: > linelist=lines.split('\t') > Key=linelist[0] > ValCity=(linelist[12]).strip() > ValState=linelist[13] > ValOne=linelist[2] > ValTwo=linelist[6] > ValThree=boolean(linelist[7]) You are assigning each line to the same variable. So at the end of the loop ypou have the values of the last line. You need to build a collection. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Tue Nov 6 15:01:43 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 06 Nov 2012 14:01:43 +0000 Subject: [Tutor] help on dic creation In-Reply-To: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> References: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> Message-ID: On 31/10/2012 01:01, Brayden Zhao wrote: > def fieldict(filename): > D={} > with open(filename) as FileObject: > for lines in FileObject: > linelist=lines.split('\t') > Key=linelist[0] > ValCity=(linelist[12]).strip() > ValState=linelist[13] > ValOne=linelist[2] > ValTwo=linelist[6] > ValThree=boolean(linelist[7]) > D={Key:(ValOne, ValTwo, ValThree, ValCity,ValState)} Put the line above inside the for loop :) > return D > print fieldict("DOT500.txt") > -- Cheers. Mark Lawrence. From d at davea.name Tue Nov 6 15:16:41 2012 From: d at davea.name (Dave Angel) Date: Tue, 06 Nov 2012 09:16:41 -0500 Subject: [Tutor] help on dic creation In-Reply-To: References: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> Message-ID: <50991BC9.5050109@davea.name> On 11/06/2012 09:01 AM, Mark Lawrence wrote: > On 31/10/2012 01:01, Brayden Zhao wrote: > >> def fieldict(filename): >> D={} >> with open(filename) as FileObject: >> for lines in FileObject: >> linelist=lines.split('\t') >> Key=linelist[0] >> ValCity=(linelist[12]).strip() >> ValState=linelist[13] >> ValOne=linelist[2] >> ValTwo=linelist[6] >> ValThree=boolean(linelist[7]) >> D={Key:(ValOne, ValTwo, ValThree, ValCity,ValState)} > > Put the line above inside the for loop :) > Won't help. Then he'd be reassigning the D each time, with the same net result. What he needs INSIDE the loop is something like: D[Key] = (ValOne, ValTwo, ValThree, ValCity, ValState) >> return D >> print fieldict("DOT500.txt") >> > -- DaveA From fomcl at yahoo.com Tue Nov 6 15:36:06 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 6 Nov 2012 06:36:06 -0800 (PST) Subject: [Tutor] how to keep track of sorted lists In-Reply-To: <50952E7A.90209@davea.name> References: <1351947894.98383.YahooMailNeo@web110706.mail.gq1.yahoo.com> <5095278E.70209@davea.name> <1351953647.11226.YahooMailNeo@web110714.mail.gq1.yahoo.com> <50952E7A.90209@davea.name> Message-ID: <1352212566.18161.YahooMailNeo@web110709.mail.gq1.yahoo.com> > On 11/03/2012 10:40 AM, Albert-Jan Roskam wrote: >>> On 11/03/2012 09:04 AM, Albert-Jan Roskam wrote: >> >>>> ? Hello, >>> >>> (I haven't run the code, as it was not presented in a form that I > could >>> do a single copy/paste.? So I may have missed some subtlety in the > code.) >> >> Hi, sorry about that. Here's a copy/pastable version. I also added a > 'data' parameter as my original code was too synthetic in this respect. >> The more realistically, the data come from some getter method. >> >> import bisect >> class TestOne(object): >> ? ? def __init__(self, data, param="x"): >> ? ? ? ? self.param = param >> ? ? ? ? self.data = data? # <------ NOTE: this would in reality be a > getter method of some sort >> ? ? def get(self, key, default=None): >> ? ? ? ? sorted_ = "sorted_" + self.param >> ? ? ? ? if not hasattr(self, sorted_): >> ? ? ? ? ? ? setattr(self, sorted_, sorted(self.data)) >> ? ? ? ? return bisect.bisect_right(getattr(self, sorted_), x=key) >> >> t = TestOne(range(10, 1, -1), "x") >> t.get(1) >> >> class TestTwo(object): >> ? ? def __init__(self, data, param="x"): >> ? ? ? ? self.param = param >> ? ? ? ? self.data = range(10, 1, -1) >> ? ? def get(self, key, default=None): >> ? ? ? ? k = "sorted_" + self.param >> ? ? ? ? if not hasattr(self, "sorted_"): >> ? ? ? ? ? ? setattr(self, "sorted_", {k: sorted(self.data)}) >> ? ? ? ? return bisect.bisect_right(getattr(self, "sorted_")[k], > x=key) >> t = TestTwo(range(10, 1, -1), "x") >> t.get(1) >> >> >> ? ? return bisect.bisect_right(getattr(self, sorted_), x=key) >>> >>> Why have multiple copies of the sorted data, when there's only one > list? >>> I was already half way writing a reply when I (finally!) realized that you are absolutely right! Maybe it's because I also considered using 'param' as a parameter of get() instead of __init__(). The code is needlessly complicated indeed, and mentioning bisect was distracting (and indeed, the method was an index() method --I believe it was Steven who pointed that out). Thanks you all. Cheers, Albert-Jan (with occasionally fuzzy cortex ;-) From breamoreboy at yahoo.co.uk Tue Nov 6 15:48:41 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 06 Nov 2012 14:48:41 +0000 Subject: [Tutor] help on dic creation In-Reply-To: <50991BC9.5050109@davea.name> References: <0B31024E-E437-461D-BC26-AAE93E773888@gmail.com> <50991BC9.5050109@davea.name> Message-ID: On 06/11/2012 14:16, Dave Angel wrote: > On 11/06/2012 09:01 AM, Mark Lawrence wrote: >> On 31/10/2012 01:01, Brayden Zhao wrote: >> >>> def fieldict(filename): >>> D={} >>> with open(filename) as FileObject: >>> for lines in FileObject: >>> linelist=lines.split('\t') >>> Key=linelist[0] >>> ValCity=(linelist[12]).strip() >>> ValState=linelist[13] >>> ValOne=linelist[2] >>> ValTwo=linelist[6] >>> ValThree=boolean(linelist[7]) >>> D={Key:(ValOne, ValTwo, ValThree, ValCity,ValState)} >> >> Put the line above inside the for loop :) >> > Won't help. Then he'd be reassigning the D each time, with the same net > result. What he needs INSIDE the loop is something like: > > D[Key] = (ValOne, ValTwo, ValThree, ValCity, ValState) > >>> return D >>> print fieldict("DOT500.txt") >>> >> > > Thanks for the correction, that'll teach me to pay attention :( -- Cheers. Mark Lawrence. From ramit.prasad at jpmorgan.com Tue Nov 6 17:31:05 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 6 Nov 2012 16:31:05 +0000 Subject: [Tutor] why different result from two similar ways In-Reply-To: <50987375.2090204@pearwood.info> References: <000401cdb63e$ec068410$c4138c30$@com> <50987375.2090204@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741677FEAA@SCACMX008.exchad.jpmchase.net> Steven D'Aprano wrote: > On 30/10/12 12:36, Frank Pontius wrote: > > Hello, > > I have code that works. Then tried to move some of it into function > > IncrementAndRebuildInput, then result changes, I no longer have same result > > as when code in function was inline - why? > > Have you tried running it in isolation to see what it does? > > When I try it, it works for me (apart from printing a lot of unnecessary > intermediate results): > > py> result = IncrementAndRebuildInput("abc def 123 xyz 456") > ['abc', 'def', '123', 'xyz', '456'] > 124 > ['abc', 'def', '124', 'xyz', '456'] > NOWHERE > 457 > ['abc', 'def', '124', 'xyz', '457'] > NOWHERE > ['abc', 'def', '124', 'xyz', '457'] > Point6 > > > > Now check the returned result: > > py> result > ['abc', 'def', '124', 'xyz', '457'] > > So it certainly does increment the numbers in the string. The only > bit it doesn't do is rebuild the string, but that takes just one > minor change: instead of "return newstring" (by the way, that's false > advertising -- newstring is not a string, it is a list), use: > > return ' '.join(newstring) > > > You also use this function: > > > def IsNum(string): > > # print "IsNum string", string > > for char in string: #checks string groupings to be all nums > > if not char.isdigit(): > > # print "false" > > return False > > # print "true" > > return True > > You don't need it! The isdigit method doesn't only work on a single character > at a time, it works on an entire string: > > py> "12345".isdigit() > True > py> "12345a".isdigit() > False I just want to point to the OP (Frank) that this only works for "digits" i.e. integers. It will fail for other types of numbers. >>> '12.3'.isdigit() False >>> '12.3'.isalnum() False ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Tue Nov 6 17:22:53 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 6 Nov 2012 16:22:53 +0000 Subject: [Tutor] Help with class example In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741677EADF@SCACMX008.exchad.jpmchase.net> References: <001d01cdad8c$8f83d220$ae8b7660$@com> <508B4CEE.3000609@davea.name> <001501cdb468$38020f70$a8062e50$@com> <5B80DD153D7D744689F57F4FB69AF4741677EADF@SCACMX008.exchad.jpmchase.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741677FE64@SCACMX008.exchad.jpmchase.net> Ramit Prasad wrote: > You would be better off trying to run this from the command > line. I just wanted to clarify on this. The reason you will have a better results running this from the command line is that Python will normally give you very good error traceback. An IDE might hide or obscure the problem, but it should be fairly easy to figure out if you see the error traceback. The error will usually be on that line, but sometimes (especially with syntax errors) it might be the line (or two) previous to the line shown. If you do not know how to run on the command line, post back letting us know (and what operating system) and we can guide you. It is not difficult but can sometimes be awkward or intimidating for people. Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From steve at pearwood.info Wed Nov 7 00:22:38 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 07 Nov 2012 10:22:38 +1100 Subject: [Tutor] why different result from two similar ways In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741677FEAA@SCACMX008.exchad.jpmchase.net> References: <000401cdb63e$ec068410$c4138c30$@com> <50987375.2090204@pearwood.info> <5B80DD153D7D744689F57F4FB69AF4741677FEAA@SCACMX008.exchad.jpmchase.net> Message-ID: <50999BBE.7080806@pearwood.info> On 07/11/12 03:31, Prasad, Ramit wrote: > Steven D'Aprano wrote: >> The isdigit method doesn't only work on a single character >> at a time, it works on an entire string: >> >> py> "12345".isdigit() >> True >> py> "12345a".isdigit() >> False > > I just want to point to the OP (Frank) that this only works for "digits" >i.e. integers. It will fail for other types of numbers. That's why it's called "isdigit" not "isnumber" :) -- Steven From sclarkey101 at hotmail.com Wed Nov 7 12:53:59 2012 From: sclarkey101 at hotmail.com (steve clarke) Date: Wed, 7 Nov 2012 11:53:59 +0000 Subject: [Tutor] (no subject) Message-ID: Hi, I am trying to write a programme to count how many times a random point lies within the positive sector of a circle. So far I can display if the point lies inside the area but I need something to allow me to count the total number of items that lie inside the area. My programme is:>>> import random>>> for i in range(10): x = random.random() y = random.random() count = 0 if x*x + y*y < 1: count = count + 1 print count and I get a list down the screen like11111 depending on how many times a random point lies in the area. I am meant to do this with 10000 points so I can't simply count the 1's up like I can with 10. I have been looking on the internet but cant find anything that works yet. Thanks for your timeSteve Clarke -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Nov 7 13:06:23 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 7 Nov 2012 12:06:23 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: It's good to give your email a subject line that describes what you're doing. On 7 November 2012 11:53, steve clarke wrote: > Hi, I am trying to write a programme to count how many times a random point > lies within the positive sector of a circle. So far I can display if the > point lies inside the area but I need something to allow me to count the > total number of items that lie inside the area. The indentation below is all screwed up. I think this is because you posted in html email. It is better to use plain-text email when sending to this list so that the code doesn't get garbled. > My programme is: >>>> import random >>>> for i in range(10): All of the lines below are executed repeatedly in a loop > x = random.random() > y = random.random() > count = 0 including the line above that sets count to 0. > if x*x + y*y < 1: > count = count + 1 So when you increment count above it has always been set to zero first. You need to set count to zero once before the loop. Then increment it by one on each iteration of the loop (if the point is in the circle). Oscar From seema.var at gmail.com Wed Nov 7 16:44:37 2012 From: seema.var at gmail.com (Seema V Srivastava) Date: Wed, 7 Nov 2012 07:44:37 -0800 Subject: [Tutor] web scraping using Python and urlopen in Python 3.3 Message-ID: Hi, I am new to Python, trying to learn it by carrying out specific tasks. I want to start with trying to scrap the contents of a web page. I have downloaded Python 3.3 and BeautifulSoup 4. If I call upon urlopen in any form, such as below, I get the error as shown below the syntax: Does urlopen not apply to Python 3.3? If not then what;s the syntax I should be using? Thanks so much. import urllib from bs4 import BeautifulSoup soup = BeautifulSoup(urllib.urlopen("http://www.pinterest.com")) Traceback (most recent call last): File "C:\Users\Seema\workspace\example\main.py", line 3, in soup = BeautifulSoup(urllib.urlopen("http://www.pinterest.com")) AttributeError: 'module' object has no attribute 'urlopen' -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Nov 7 17:25:50 2012 From: wprins at gmail.com (Walter Prins) Date: Wed, 7 Nov 2012 16:25:50 +0000 Subject: [Tutor] web scraping using Python and urlopen in Python 3.3 In-Reply-To: References: Message-ID: Seema, On 7 November 2012 15:44, Seema V Srivastava wrote: > Hi, > I am new to Python, trying to learn it by carrying out specific tasks. I > want to start with trying to scrap the contents of a web page. I have > downloaded Python 3.3 and BeautifulSoup 4. > > If I call upon urlopen in any form, such as below, I get the error as > shown below the syntax: Does urlopen not apply to Python 3.3? If not then > what;s the syntax I should be using? Thanks so much. > See the documenation: http://docs.python.org/2/library/urllib.html#utility-functions Quote: "Also note that the urllib.urlopen()function has been removed in Python 3 in favor of urllib2.urlopen() ." Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Wed Nov 7 17:37:12 2012 From: d at davea.name (Dave Angel) Date: Wed, 07 Nov 2012 11:37:12 -0500 Subject: [Tutor] web scraping using Python and urlopen in Python 3.3 In-Reply-To: References: Message-ID: <509A8E38.4040305@davea.name> On 11/07/2012 10:44 AM, Seema V Srivastava wrote: > Hi, > I am new to Python, trying to learn it by carrying out specific tasks. I > want to start with trying to scrap the contents of a web page. I have > downloaded Python 3.3 and BeautifulSoup 4. > > If I call upon urlopen in any form, such as below, I get the error as shown > below the syntax: Does urlopen not apply to Python 3.3? If not then > what;s the syntax I should be using? Thanks so much. > > import urllib > from bs4 import BeautifulSoup > soup = BeautifulSoup(urllib.urlopen("http://www.pinterest.com")) > > Traceback (most recent call last): > File "C:\Users\Seema\workspace\example\main.py", line 3, in > soup = BeautifulSoup(urllib.urlopen("http://www.pinterest.com")) > AttributeError: 'module' object has no attribute 'urlopen' > > Since you're trying to learn, let me point out a few things that would let you teach yourself, which is usually quicker and more effective than asking on a mailing list. (Go ahead and ask, but if you figure out the simpler ones yourself, you'll learn faster) (BTW, I'm using 3.2, but it'll probably be very close) First, that error has nothing to do with BeautifulSoup. If it had, I wouldn't have responded, since I don't have any experience with BS. The way you could learn that for yourself is to factor the line giving the error: tmp = urllib.urlopen("http://www.pinterest.com") soup = BeautifulSoup(tmp) Now, you'll get the error on the first line, before doing anything with BeautifulSoup. Now that you have narrowed it to urllib.urlopen, go find the docs for that. I used DuckDuckGo, with keywords python urllib urlopen, and the first match was: http://docs.python.org/2/library/urllib.html and even though this is 2.7.3 docs, the first paragraph tells you something useful: Note The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error. The /2to3/ tool will automatically adapt imports when converting your sources to Python 3. Also note that the urllib.urlopen() function has been removed in Python 3 in favor of urllib2.urlopen() . Now, the next question I'd ask is whether you're working from a book (or online tutorial), and that book is describing Python 2.x If so, you might encounter this type of pain many times. Anyway, another place you can learn is from the interactive interpreter. just run python3, and experiment. >>> import urllib >>> urllib.urlopen Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'urlopen' >>> dir(urllib) ['__builtins__', '__cached__', '__doc__', '__file__', '__name__', '__package__', '__path__'] >>> Notice that dir shows us the attributes of urllib, and none of them look directly useful. That's because urllib is a package, not just a module. A package is a container for other modules. We can also look __file__ >>> urllib.__file__ '/usr/lib/python3.2/urllib/__init__.py' That __init__.py is another clue; that's the way packages are initialized. But when I try importing urllib2, I get ImportError: No module named urllib2 So back to the website. But using the dropdown at the upper left, i can change from 2.7 to 3.3: http://docs.python.org/3.3/library/urllib.html There it is quite explicit. urllib is a package that collects several modules for working with URLs: * urllib.request for opening and reading URLs * urllib.error containing the exceptions raised by urllib.request * urllib.parse for parsing URLs * urllib.robotparser for parsing robots.txt files So, if we continue to play with the interpreter, we can try: >>> import urllib.request >>> dir(urllib.request) ['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandler', 'BaseHandler', 'CacheFTPHandler', 'ContentTooShortError', 'FTPHandler', 'FancyURLopener', 'FileHandler', 'HTTPBasicAuthHandler', 'HTTPCookieProcessor', 'HTTPDefaultErrorHandler', 'HTTPDigestAuthHandler', 'HTTPError', 'HTTPErrorProcessor', ...... 'urljoin', 'urlopen', 'urlparse', 'urlretrieve', 'urlsplit', 'urlunparse'] I chopped off part of the long list of things that was imported in that module. But one of them is urlopen, which is what you were looking for before. So back to your own sources, try: >>> tmp = urllib.request.urlopen("http://www.pinterest.com") >>> tmp OK, the next thing you might wonder is what parameters urlopen might take: Help on function urlopen in module urllib.request: >>> help(urllib.request.urlopen) urlopen(url, data=None, timeout=, *, cafile=None, capath=None) (END) Hopefully, this will get you started into BeautifulSoup. As i said before, I have no experience with that part. Note that I normally use the docs.python.org documentation much more. But a quick question to the interpreter can be very useful, especially if you don't have internet access. -- DaveA From d at davea.name Wed Nov 7 17:39:27 2012 From: d at davea.name (Dave Angel) Date: Wed, 07 Nov 2012 11:39:27 -0500 Subject: [Tutor] web scraping using Python and urlopen in Python 3.3 In-Reply-To: References: Message-ID: <509A8EBF.6070809@davea.name> On 11/07/2012 11:25 AM, Walter Prins wrote: > Seema, > > On 7 November 2012 15:44, Seema V Srivastava wrote: > >> Hi, >> I am new to Python, trying to learn it by carrying out specific tasks. I >> want to start with trying to scrap the contents of a web page. I have >> downloaded Python 3.3 and BeautifulSoup 4. >> >> If I call upon urlopen in any form, such as below, I get the error as >> shown below the syntax: Does urlopen not apply to Python 3.3? If not then >> what;s the syntax I should be using? Thanks so much. >> > See the documenation: > http://docs.python.org/2/library/urllib.html#utility-functions > > Quote: "Also note that the > urllib.urlopen()function > has been removed in Python 3 in favor of > urllib2.urlopen() > ." > > Walter > > Unfortunately, that's a bug in 2.7 documentation. The actual Python3 approach does not use urllib2. See http://docs.python.org/3.3/library/urllib.html -- DaveA From ywhuofu at hotmail.com Wed Nov 7 18:09:17 2012 From: ywhuofu at hotmail.com (wenhao) Date: Wed, 7 Nov 2012 10:09:17 -0700 Subject: [Tutor] html table parse Message-ID: Hi ALL, I tied to use python to do some html parsing. More specifically, I want to extract data from some html tables. Could you give me some suggestions which library should use? I tried Beautiful Soup, but I couldn't find anything to do with table parsing. Thanks ! From ccsentient at myopera.com Wed Nov 7 21:50:46 2012 From: ccsentient at myopera.com (Christopher Conner) Date: Wed, 7 Nov 2012 14:50:46 -0600 Subject: [Tutor] html table parse In-Reply-To: References: Message-ID: > Hi ALL, > > I tied to use python to do some html parsing. More specifically, I want to > extract data from some html tables. Could you give me some suggestions which > library should use? I tried Beautiful Soup, but I couldn't find anything to > do with table parsing. > > Thanks ! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Python has a native HTML parser. http://docs.python.org/2/library/htmlparser.html Christopher Conner (719) 425-8886 On Nov 7, 2012, at 11:09 AM, wenhao wrote: > Hi ALL, > > I tied to use python to do some html parsing. More specifically, I want to > extract data from some html tables. Could you give me some suggestions which > library should use? I tried Beautiful Soup, but I couldn't find anything to > do with table parsing. > > Thanks ! > > > > _______________________________________________ > 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 Wed Nov 7 22:16:21 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 7 Nov 2012 16:16:21 -0500 Subject: [Tutor] html table parse In-Reply-To: References: Message-ID: I've used bs4 to extract data from a table, and found it pretty nice. Can you show some code with specific problems you encountered? On Wed, Nov 7, 2012 at 3:50 PM, Christopher Conner wrote: > > > Hi ALL, > > > > I tied to use python to do some html parsing. More specifically, I want > to > > extract data from some html tables. Could you give me some suggestions > which > > library should use? I tried Beautiful Soup, but I couldn't find anything > to > > do with table parsing. > > > > Thanks ! > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > Python has a native HTML parser. > > http://docs.python.org/2/library/htmlparser.html > > > Christopher Conner > (719) 425-8886 > > > > On Nov 7, 2012, at 11:09 AM, wenhao wrote: > > > Hi ALL, > > > > I tied to use python to do some html parsing. More specifically, I want > to > > extract data from some html tables. Could you give me some suggestions > which > > library should use? I tried Beautiful Soup, but I couldn't find anything > to > > do with table parsing. > > > > Thanks ! > > > > > > > > _______________________________________________ > > 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 > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Nov 7 23:07:06 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 07 Nov 2012 22:07:06 +0000 Subject: [Tutor] html table parse In-Reply-To: References: Message-ID: On 07/11/12 20:50, Christopher Conner wrote: > Python has a native HTML parser. > > http://docs.python.org/2/library/htmlparser.html It does, but frankly BS is much easier to use and more forgiving. I wouldn't recommend that the OP drop BS to use htmlparser To the OP, do you understand HTML? parsing a table is no different from parsing a heading or any other tag. You need to understand the structure of the page you are parsing but the principle is the same. There is one other parsing library that looks promising but I haven't had a chance to use it in anger yet. Its called pyQuery and is similar in principle to JQuery. It allows you to search by CSS style as well as HTML tags and combinations thereof... It looks very promising but I don;t know what performance or real world usability is like... But if you already know JQuery it looks like a useful tool. API here: http://packages.python.org/pyquery/api.html -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From tgirowall at yahoo.com Fri Nov 9 03:33:32 2012 From: tgirowall at yahoo.com (T. Girowall) Date: Thu, 8 Nov 2012 18:33:32 -0800 (PST) Subject: [Tutor] Telnet login Message-ID: <1352428412.45435.YahooMailNeo@web121401.mail.ne1.yahoo.com> Hello All,? I'm trying to telnet to a device with a particular IP address. I'm using the sample code below and get the following error:? Erro 10061: "No connection could be made because the target machine actively refused it" My firewall is turned off.? I'm using Python 2.7 I'm using Windows XP When I'm prompted for remote account, i enter the user name and then im prompted for the password which enter as well.? I'm able to connect to the device using putty with following settings:? ip: 192.168.xx.xx port: 2332 Any help is appreciated,? Tim import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Fri Nov 9 03:57:48 2012 From: d at davea.name (Dave Angel) Date: Thu, 08 Nov 2012 21:57:48 -0500 Subject: [Tutor] Telnet login In-Reply-To: <1352428412.45435.YahooMailNeo@web121401.mail.ne1.yahoo.com> References: <1352428412.45435.YahooMailNeo@web121401.mail.ne1.yahoo.com> Message-ID: <509C712C.9040302@davea.name> On 11/08/2012 09:33 PM, T. Girowall wrote: > > ip: 192.168.xx.xx > port: 2332 > > Any help is appreciated, > Tim > import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() > > This is a text mailing list; your html mail thoroughly mangles your code for the majority of readers. Is there a reason why you used 192.168.xx.xx with putty, but used localhost with your python code? -- DaveA From d at davea.name Fri Nov 9 05:14:10 2012 From: d at davea.name (Dave Angel) Date: Thu, 08 Nov 2012 23:14:10 -0500 Subject: [Tutor] Telnet login In-Reply-To: <1352432916.25910.YahooMailNeo@web121401.mail.ne1.yahoo.com> References: <1352428412.45435.YahooMailNeo@web121401.mail.ne1.yahoo.com> <509C712C.9040302@davea.name> <1352432916.25910.YahooMailNeo@web121401.mail.ne1.yahoo.com> Message-ID: <509C8312.50002@davea.name> On 11/08/2012 10:48 PM, T. Girowall wrote: The quoting levels in this message are probably messed up, but I fixed the order, and tried to fix the levels. >> On 11/08/2012 09:33 PM, T. Girowall wrote: >>> >>> ip: 192.168.xx.xx >>> port: 2332 >>> >>> Any help is appreciated, >>> Tim >>> import getpass import sys import telnetlib HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass() tn = telnetlib.Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n") if password: tn.read_until("Password: ") tn.write(password + "\n") tn.write("ls\n") tn.write("exit\n") print tn.read_all() >>> >>> > Dave Angel wrote: >> >> This is a text mailing list; your html mail thoroughly mangles your >> code for the majority of readers. >> >> Is there a reason why you used 192.168.xx.xx with putty, but used >> localhost with your python code? >> > David, > > I'm new to this stuff so I apologize if dum mistakes are made. > > The device I'm connecting to has the 192.168 IP address and that's I should'v used in the code example. I did try changing the HOST = "192.168.xx.xx" but still got the same error message. I noticed that the default Port in Putty for Telnet is 23 but my device's port is 2332. Could this be the problem? If so, how I can change the port number? > > Here is the code in Text: > > import getpass > import sys > import telnetlib > > def main(): > pass > > HOST = "192.168.xx.xx" > user = raw_input("Enter your remote account: ") > password = getpass.getpass() > > tn = telnetlib.Telnet(HOST) > > tn.read_until("login: ") > tn.write(user + "\n") > if password: > tn.read_until("Password: ") > tn.write(password + "\n") > > tn.write("ls\n") > tn.write("exit\n") > > print tn.read_all() > > if __name__ == '__main__': > main() > > Where's the error message, including the traceback? Somebody (not me) who is familiar with telnetlib can presumably help, given enough information. -- DaveA From eryksun at gmail.com Fri Nov 9 05:32:46 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 8 Nov 2012 23:32:46 -0500 Subject: [Tutor] Telnet login In-Reply-To: <509C8312.50002@davea.name> References: <1352428412.45435.YahooMailNeo@web121401.mail.ne1.yahoo.com> <509C712C.9040302@davea.name> <1352432916.25910.YahooMailNeo@web121401.mail.ne1.yahoo.com> <509C8312.50002@davea.name> Message-ID: On Thu, Nov 8, 2012 at 11:14 PM, Dave Angel wrote: > >> HOST = "192.168.xx.xx" >> user = raw_input("Enter your remote account: ") >> password = getpass.getpass() >> >> tn = telnetlib.Telnet(HOST) > > Where's the error message, including the traceback? Somebody (not me) > who is familiar with telnetlib can presumably help, given enough > information. The port to use is the 2nd argument: HOST = '192.168.xx.xx' PORT = 2332 tn = telnetlib.Telnet(HOST, PORT) http://docs.python.org/2/library/telnetlib#telnetlib.Telnet From mhisamuddin at gmail.com Fri Nov 9 19:57:03 2012 From: mhisamuddin at gmail.com (Mohammed hisamuddin) Date: Sat, 10 Nov 2012 00:27:03 +0530 Subject: [Tutor] Get data through url. Message-ID: I want to pass data onto my python program through an url and then store the information in a mysql db. For instance i want to call http:///expand.py?mobile=992828282®ion=India and i get the "mobile" and "region" values inside my program which i can then save into my db. In php i could use $_get and do this. I'm new to python, how can i do it here. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Nov 9 20:04:42 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 09 Nov 2012 19:04:42 +0000 Subject: [Tutor] Get data through url. In-Reply-To: References: Message-ID: On 09/11/12 18:57, Mohammed hisamuddin wrote: > For instance i want to call http:// >/expand.py?mobile=992828282®ion=India > > and i get the "mobile" and "region" values inside my program which i can > then save into my db. > lots of options but you could start with the standard library cgi module... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eowens0124 at gmx.com Sat Nov 10 02:18:38 2012 From: eowens0124 at gmx.com (Ed Owens) Date: Fri, 09 Nov 2012 20:18:38 -0500 Subject: [Tutor] Python books In-Reply-To: References: <1351367401.24299.YahooMailNeo@web160406.mail.bf1.yahoo.com> Message-ID: <509DAB6E.7040103@gmx.com> I've been trying to learn Python, writing a Blackjack program. Seems that's a common problem for learning. I'm not in a class or school, just working on my own. I've been working in Python 2.7, and considering moving up to 3.x. My programming background is ancient, having done most of my programming in FORTRAN. I have been using free internet resources to learn, mostly Google searches on syntax, and their free courses. I have the basic game done: dealing from a shoe of multiple decks, splits, betting, etc. and started to work on the harder parts such as graphics of the table with cards, managing record keeping, and so on. There seem to be a plethora of packages and options, many of them outside of the "standard" Python installation. Plus, I'm still discovering how to do things with the standard library. I need more structure and organization! I have one book, "Python Programming for the Absolute Beginner" by Dawson, which is too plodding. Can you experts recommend a Python library? I would like to have: A command reference for the basic library. A comprehensive "How to" course for the basic library. Graphics in Python Data Management in Python Using the internet with Python (maybe Real Time(ish) Python) A comprehensive "Learn Python" course that puts all this together I realize that this is outside of the "help with this code" request, but I would value your advice. Ed O From kendy at kendy.org Sat Nov 10 06:54:22 2012 From: kendy at kendy.org (kendy at kendy.org) Date: Fri, 09 Nov 2012 21:54:22 PST Subject: [Tutor] encrypt a file in Python3 Message-ID: <38438.1352526862@speakeasy.net> Hello! I want to encrypt a file, then decrypt it. I prefer to do it without adding any packages. I found http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/ which seems like a good approach. How can I get the import to work for python 3? Here's what I get: $ uname -a Linux laptop 3.2.0-32-generic-pae #51-Ubuntu SMP Wed Sep 26 21:54:23 UTC 2012 i686 i686 i386 GNU/Linux $ python3.2 Python 3.2.3 (default, Sep 10 2012, 18:17:42) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, random, struct >>> from Crypto.Cipher import AES Traceback (most recent call last): File "", line 1, in ImportError: No module named Crypto.Cipher >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'os', 'random', 'struct'] >>> import Crypto.Cipher Traceback (most recent call last): File "", line 1, in ImportError: No module named Crypto.Cipher >>> Has Crypto.Cipher been renamed in Python 3? Is it supported yet? Python2.7 works fine. I saw so many "crypto" packages at http://pypi.python.org/pypi/ that I wouldn't know where to start. I want something simple. Do you have a suggestion? $ python2.7 Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, random, struct >>> from Crypto.Cipher import AES >>> dir() ['AES', '__builtins__', '__doc__', '__name__', '__package__', 'os', 'random', 'struct'] >>> $ python2.7 Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Crypto.Cipher >>> dir() ['Crypto', '__builtins__', '__doc__', '__name__', '__package__'] >>> Thanks so much! I learn a lot from you guys! Ken kendy at kendy.org From breamoreboy at yahoo.co.uk Sat Nov 10 07:59:14 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 10 Nov 2012 06:59:14 +0000 Subject: [Tutor] encrypt a file in Python3 In-Reply-To: <38438.1352526862@speakeasy.net> References: <38438.1352526862@speakeasy.net> Message-ID: On 10/11/2012 05:54, kendy at kendy.org wrote: > Hello! > > I want to encrypt a file, then decrypt it. I prefer to do it without adding any > packages. I found > > http://eli.thegreenplace.net/2010/06/25/aes-encryption-of-files-in-python-with-pycrypto/ > > which seems like a good approach. How can I get the import to work for python 3? You install pycrypto on Python 3, which contradicts your stated preference. > Here's what I get: > > $ uname -a > Linux laptop 3.2.0-32-generic-pae #51-Ubuntu SMP Wed Sep 26 21:54:23 UTC 2012 > i686 i686 i386 GNU/Linux > $ python3.2 > Python 3.2.3 (default, Sep 10 2012, 18:17:42) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os, random, struct >>>> from Crypto.Cipher import AES > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named Crypto.Cipher >>>> dir() > ['__builtins__', '__doc__', '__name__', '__package__', 'os', 'random', 'struct'] >>>> import Crypto.Cipher > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named Crypto.Cipher >>>> > > Has Crypto.Cipher been renamed in Python 3? Is it supported yet? Python2.7 works > fine. Somebody (you?) has already installed pycrypto on 2.7. > > I saw so many "crypto" packages at http://pypi.python.org/pypi/ that I wouldn't > know where to start. I want something simple. Do you have a suggestion? > > $ python2.7 > Python 2.7.3 (default, Aug 1 2012, 05:16:07) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import os, random, struct >>>> from Crypto.Cipher import AES >>>> dir() > ['AES', '__builtins__', '__doc__', '__name__', '__package__', 'os', 'random', > 'struct'] >>>> > > $ python2.7 > Python 2.7.3 (default, Aug 1 2012, 05:16:07) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import Crypto.Cipher >>>> dir() > ['Crypto', '__builtins__', '__doc__', '__name__', '__package__'] >>>> > > Thanks so much! I learn a lot from you guys! You haven't seen my bill yet :) > > Ken > kendy at kendy.org > -- Cheers. Mark Lawrence. From wescpy at gmail.com Sat Nov 10 08:13:41 2012 From: wescpy at gmail.com (wesley chun) Date: Fri, 9 Nov 2012 23:13:41 -0800 Subject: [Tutor] Python books In-Reply-To: <509DAB6E.7040103@gmx.com> References: <1351367401.24299.YahooMailNeo@web160406.mail.bf1.yahoo.com> <509DAB6E.7040103@gmx.com> Message-ID: there is no one single book that has all you're seeking, however you can probably find one or two that may suit your fancy in these Python reading lists that i made earlier this year: http://goo.gl/i4u0R note that the 3rd set of books are some of the references that you're seeking. best of luck! --wesley On Fri, Nov 9, 2012 at 5:18 PM, Ed Owens wrote: > I've been trying to learn Python, writing a Blackjack program. Seems > that's a common problem for learning. I'm not in a class or school, just > working on my own. I've been working in Python 2.7, and considering moving > up to 3.x. My programming background is ancient, having done most of my > programming in FORTRAN. I have been using free internet resources to learn, > mostly Google searches on syntax, and their free courses. > > I have the basic game done: dealing from a shoe of multiple decks, splits, > betting, etc. and started to work on the harder parts such as graphics of > the table with cards, managing record keeping, and so on. There seem to be > a plethora of packages and options, many of them outside of the "standard" > Python installation. Plus, I'm still discovering how to do things with the > standard library. I need more structure and organization! > > I have one book, "Python Programming for the Absolute Beginner" by Dawson, > which is too plodding. Can you experts recommend a Python library? I would > like to have: > > A command reference for the basic library. > A comprehensive "How to" course for the basic library. > Graphics in Python > Data Management in Python > Using the internet with Python > (maybe Real Time(ish) Python) > A comprehensive "Learn Python" course that puts all this together > > I realize that this is outside of the "help with this code" request, but I > would value your advice. > > Ed O > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "A computer never does what you want... only what you tell it." +wesley chun : wescpy at gmail : @wescpy Python training & consulting : http://CyberwebConsulting.com "Core Python" books : http://CorePython.com Python blog: http://wescpy.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Nov 10 08:59:29 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 10 Nov 2012 02:59:29 -0500 Subject: [Tutor] encrypt a file in Python3 In-Reply-To: <38438.1352526862@speakeasy.net> References: <38438.1352526862@speakeasy.net> Message-ID: On Sat, Nov 10, 2012 at 12:54 AM, wrote: > > I want to encrypt a file, then decrypt it. I prefer to do it without adding any > packages. > > $ uname -a > Linux laptop 3.2.0-32-generic-pae #51-Ubuntu SMP You'll either need to install the package "python3-crypto" or compile it yourself. To build it locally, you'll need to setup your build environment. The packages build-essential, python3-dev, python3-setuptools, and libgmp-dev should suffice. Once everything is setup, simply run the following: sudo easy_install3 --verbose pycrypto On My Debian system it installs to /usr/local/lib/python3.2/dist-packages/. You can also run the self tests: >>> import sys >>> import Crypto.SelfTest >>> Crypto.SelfTest.run(verbosity=1, stream=sys.stdout) For me it ran 1078 tests (one dot per test). From alan.gauld at btinternet.com Sat Nov 10 10:18:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 10 Nov 2012 09:18:25 +0000 Subject: [Tutor] Python books In-Reply-To: <509DAB6E.7040103@gmx.com> References: <1351367401.24299.YahooMailNeo@web160406.mail.bf1.yahoo.com> <509DAB6E.7040103@gmx.com> Message-ID: On 10/11/12 01:18, Ed Owens wrote: Please start new threads with a fresh mail. On threaded readers this gets lost under a previous topic called "Question"... > Dawson, which is too plodding. Can you experts recommend a Python > library? I would like to have: > > A command reference for the basic library. O'Reilly's Nutshell book or the Pocket Reference or Beasleys "Essential Reference". But mostly I just use the built in help() system... > A comprehensive "How to" course for the basic library. There is a best practice Python 'Recipes' book, but there is a much bigger resource on ActiveState's site. > Graphics in Python Depends on the tookit. For GUIs there are books on Tkinter, wxPython, PyQt and (I think) pyGTk. There are more general books on things like R and GNU plot. Theres also pygame and things like OpenGL. It all depends on what kind of graphics and your favoured toolkit. Too hard to recommend anything specific. > Data Management in Python I don't know of anything specific although a lot of the general tutorials include a chapter on the Python DBI interface. But the biggest thing here is learning SQL... > Using the internet with Python Python Network Programming by Goerzen. > (maybe Real Time(ish) Python) Don't know of anything here. The (ish) is the killer, you can't really do too much hard real-time in Python... > A comprehensive "Learn Python" course that puts all this together I would have recommended Python -How to Program by the Deitels but I don't know if its been updated so is now quite old. If you can pick up a cheap second hand copy its a good broad top level intro to all of the topics above. Its the only one I've seen that covers everything in your list except real-time. But it was very expensive. That's my list :-) Of course I cover most of it in my online tutorial too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From lowelltackett at yahoo.com Sat Nov 10 15:17:44 2012 From: lowelltackett at yahoo.com (Lowell Tackett) Date: Sat, 10 Nov 2012 06:17:44 -0800 (PST) Subject: [Tutor] Python books In-Reply-To: <509DAB6E.7040103@gmx.com> References: <1351367401.24299.YahooMailNeo@web160406.mail.bf1.yahoo.com> <509DAB6E.7040103@gmx.com> Message-ID: <1352557064.80552.YahooMailNeo@web110111.mail.gq1.yahoo.com> The "Head First..." series of books (O'Reilly Press) adopts a wonderful, intuitive?"work-along" format; of particular interest [to you] would be "Head First Python" by Paul Barry. From the virtual desk of Lowell Tackett? ________________________________ From: Ed Owens To: tutor at python.org Sent: Friday, November 9, 2012 8:18 PM Subject: [Tutor] Python books I've been trying to learn Python, writing a Blackjack program. Seems that's a common problem for learning.? I'm not in a class or school, just working on my own.? I've been working in Python 2.7, and considering moving up to 3.x.? My programming background is ancient, having done most of my programming in FORTRAN. I have been using free internet resources to learn, mostly Google searches on syntax, and their free courses. I have the basic game done: dealing from a shoe of multiple decks, splits, betting, etc.? and started to work on the harder parts such as graphics of the table with cards, managing record keeping, and so on.? There seem to be a plethora of packages and options, many of them outside of the "standard" Python installation.? Plus, I'm still discovering how to do things with the standard library.? I need more structure and organization! I have one book, "Python Programming for the Absolute Beginner" by Dawson, which is too plodding. Can you experts recommend a Python library?? I would like to have: A command reference for the basic library. A comprehensive "How to" course for the basic library. Graphics in Python Data Management in Python Using the internet with Python (maybe Real Time(ish) Python) A comprehensive "Learn Python" course that puts all this together I realize that this is outside of the "help with this code" request, but I would value your advice. Ed O _______________________________________________ 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 lzantal at gmail.com Sat Nov 10 17:53:56 2012 From: lzantal at gmail.com (lzantal) Date: Sat, 10 Nov 2012 08:53:56 -0800 Subject: [Tutor] Python books In-Reply-To: References: <1351367401.24299.YahooMailNeo@web160406.mail.bf1.yahoo.com> <509DAB6E.7040103@gmx.com> Message-ID: <029710D6-3EFC-4F31-B852-31C652BCD949@gmail.com> Hi, On Nov 9, 2012, at 11:13 PM, wesley chun wrote: > there is no one single book that has all you're seeking, however you can probably find one or two that may suit your fancy in these Python reading lists that i made earlier this year: http://goo.gl/i4u0R > > note that the 3rd set of books are some of the references that you're seeking. > > best of luck! > --wesley > > > On Fri, Nov 9, 2012 at 5:18 PM, Ed Owens wrote: >> I've been trying to learn Python, writing a Blackjack program. Seems that's a common problem for learning. I'm not in a class or school, just working on my own. I've been working in Python 2.7, and considering moving up to 3.x. My programming background is ancient, having done most of my programming in FORTRAN. I have been using free internet resources to learn, mostly Google searches on syntax, and their free courses. >> >> I have the basic game done: dealing from a shoe of multiple decks, splits, betting, etc. and started to work on the harder parts such as graphics of the table with cards, managing record keeping, and so on. There seem to be a plethora of packages and options, many of them outside of the "standard" Python installation. Plus, I'm still discovering how to do things with the standard library. I need more structure and organization! >> >> I have one book, "Python Programming for the Absolute Beginner" by Dawson, which is too plodding. Can you experts recommend a Python library? I would like to have: >> >> A command reference for the basic library. >> A comprehensive "How to" course for the basic library. >> Graphics in Python >> Data Management in Python >> Using the internet with Python >> (maybe Real Time(ish) Python) >> A comprehensive "Learn Python" course that puts all this together >> >> I realize that this is outside of the "help with this code" request, but I would value your advice. >> >> Ed O First book I highly recommend Learn Python the Hard Way http://learnpythonthehardway.org/ It's a great book which will get you going with python. It also has video companion which could come handy since you are learning on your own. Next book I would look at is Core Python Programming http://www.amazon.com/Core-Python-Programming-2nd-Edition/dp/0132269937/ref=sr_1_1?ie=UTF8&qid=1352566105&sr=8-1&keywords=Core+python+programming I used the first edition and I liked how it covers a lot of areas of python and most of what's on your list. Good luck with your study and have fun doing it Laszlo >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > > -- > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "A computer never does what you want... only what you tell it." > +wesley chun : wescpy at gmail : @wescpy > Python training & consulting : http://CyberwebConsulting.com > "Core Python" books : http://CorePython.com > Python blog: http://wescpy.blogspot.com > _______________________________________________ > 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 kendy at kendy.org Sat Nov 10 20:23:27 2012 From: kendy at kendy.org (kendy at kendy.org) Date: Sat, 10 Nov 2012 11:23:27 PST Subject: [Tutor] encrypt a file in Python3 Message-ID: <55758.1352575407@speakeasy.net> Thank you Mark and eryksun! You've put me back on the road to success! I'll start saving up for your bill. :-) Ken From breamoreboy at yahoo.co.uk Sun Nov 11 01:42:31 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 11 Nov 2012 00:42:31 +0000 Subject: [Tutor] encrypt a file in Python3 In-Reply-To: <55758.1352575407@speakeasy.net> References: <55758.1352575407@speakeasy.net> Message-ID: On 10/11/2012 19:23, kendy at kendy.org wrote: > Thank you Mark and eryksun! > > You've put me back on the road to success! I'll start saving up for your bill. :-) > > Ken > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Please ensure that all funds are sent directly to me. Let's face it apart from ... what does erkysun know about Python? -- Cheers. Mark Lawrence. From swinson_darren at yahoo.com Sun Nov 11 02:24:20 2012 From: swinson_darren at yahoo.com (darren swinson) Date: Sat, 10 Nov 2012 17:24:20 -0800 (PST) Subject: [Tutor] Python Project Message-ID: <1352597060.67268.YahooMailNeo@web142404.mail.bf1.yahoo.com> Hello Tutor, My name is darren and I'm new to this python subject but I'm a quick and persistent learner. I'm trying to do a presentation with rst2Reveal using html5 and to tell you the truth it's not that simple. So far I wrote the rst file and there is a rst2Reveal webpage with all the needed docs. [https://bitbucket.org/adimascio/rst2reveal/src] My problem is that I don't know what to do first. I'm using python 2.7. I have my repo on bitbucket. I have the images I want to use. I have my rst file. I need to know the steps I need to do to get this presentation up and running. I even started my python script??? I think??? #!c:/Python27/python.exe def main(): ??? print "Content-type: text/html" ??? print ??? print "" ??? print "Scrum Presentation" ??? print "" ??? print "Hello World" ??? print "" #?????? if _name_=="_main_":.00000 Any way, I think this is all that I have as now. I've search the web and got lots of info. But still there is the fact that I need to know the steps exactly for me to finish this . Or at leat get the web page up and running. Any andall help will be appreciated. Sincerely, Darren Swinson -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: project.rst Type: application/octet-stream Size: 4164 bytes Desc: not available URL: From alan.gauld at btinternet.com Sun Nov 11 03:05:42 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Nov 2012 02:05:42 +0000 Subject: [Tutor] Python Project In-Reply-To: <1352597060.67268.YahooMailNeo@web142404.mail.bf1.yahoo.com> References: <1352597060.67268.YahooMailNeo@web142404.mail.bf1.yahoo.com> Message-ID: On 11/11/12 01:24, darren swinson wrote: > My name is darren and I'm new to this python subject but I'm a quick and > persistent learner. Wekcome to the list, however... > I'm trying to do a presentation with rst2Reveal using html5 Ok, I have no idea what that means. Its not standard Python so you are probably going to have to give us a bit of a clue or ask questions on a forum aimed at rst2Reveal... > My problem is that I don't know what to do first. Nor me. To write a Python program you write python code in a file. But how that fits with your rst files I have no idea. > I need to know the steps I need to do to get this presentation up and > running. > I even started my python script??? I think??? > > #!c:/Python27/python.exe > > def main(): > print "Content-type: text/html" > print > print "" > print "Scrum Presentation" > print "" > print "Hello World" > print "" #?????? > > if _name_=="_main_":.00000 The only bit of help I can offer is that there should be two underscores on each side of name and main: if __name__=="__main__":.00000 What the .0000 does I have no idea. If you are using something outside of standard Python you can't expect us to know about it, you need to explain what you are doing first. > Or at leat get the web page up and running. Any andall help will be > appreciated. I suspect you need help somewhere else before getting to the point where this list can help. Unless you get lucky and somebody on the list does actually use the same framework - or is prepared to do the research for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc at marcd.org Sun Nov 11 06:01:50 2012 From: marc at marcd.org (Marc) Date: Sun, 11 Nov 2012 00:01:50 -0500 Subject: [Tutor] Parsing a multi-line/record text file Message-ID: <005801cdbfc9$a9689eb0$fc39dc10$@org> Hello, I am trying to parse a text file with a structure that looks like: [record: Some text about the record] Attribute 1 = Attribute 1 text Attribute 3 = Attribute 3 text Attribute 4 = Attribute 4 text Attribute 7 = Attribute 7 text [record: Some text about the record] Attribute 1 = Attribute 1 text Attribute 2 = Attribute 2 text Attribute 3 = Attribute 3 text Attribute 4 = Attribute 4 text Attribute 5 = Attribute 5 text Attribute 6 = Attribute 6 text [record: Some text about the record] Attribute 2 = Attribute 2 text Attribute 3 = Attribute 3 text Attribute 7 = Attribute 7 text Attribute 8 = Attribute 8 text Etc.for many hundreds of records I am looking to create output that looks like: Attribute 1 text | Attribute 3 text Attribute 1 text | Attribute 3 text Blank | Attribute 3 text Treating each record as a record with its associated lines is the holy grail for which I am searching, yet I seem to only be coming up with dead parrots. It should be simple, but the answer is eluding me and Google has not been helpful. Pathetic thing is that I do this with Python and XML all the time, but I can't seem to figure out a simple text file. I 'm missing something simple, I'm sure. Here's the most I have gotten to work (poorly) so far - it gets me the correct data, but not in the correct format because the file is being handled sequentially, not by record - it's not even close, but I thought I'd include it here: for line in infile: while line != '\n': Attribute1 = 'Blank' Attribute3 = 'Blank' line = line.lstrip('\t') line = line.rstrip('\n') LineElements = line.split('=') if LineElements[0] == 'Attribute1 ': Attribute1=LineElements[1] if LineElements[0] == 'Attribute3 ': Attribute3=LineElements[1] print("%s | %s\n" % (Attribute1, Attribute3)) Is there a library or example I could be looking at for this? I use lxml for xml, but I don't think it will work for this - at least the way I tried did not. Thank you, Marc -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Nov 11 07:37:36 2012 From: d at davea.name (Dave Angel) Date: Sun, 11 Nov 2012 01:37:36 -0500 Subject: [Tutor] Parsing a multi-line/record text file In-Reply-To: <005801cdbfc9$a9689eb0$fc39dc10$@org> References: <005801cdbfc9$a9689eb0$fc39dc10$@org> Message-ID: <509F47B0.6040604@davea.name> On 11/11/2012 12:01 AM, Marc wrote: > Hello, > > I am trying to parse a text file with a structure that looks like: > > [record: Some text about the record] So the record delimiter starts with a left bracket, in first column? And all lines within the record are indented? Use this fact. > Attribute 1 = Attribute 1 text > Attribute 3 = Attribute 3 text > Attribute 4 = Attribute 4 text > Attribute 7 = Attribute 7 text > > [record: Some text about the record] > Attribute 1 = Attribute 1 text > Attribute 2 = Attribute 2 text > Attribute 3 = Attribute 3 text > Attribute 4 = Attribute 4 text > Attribute 5 = Attribute 5 text > Attribute 6 = Attribute 6 text > > [record: Some text about the record] > Attribute 2 = Attribute 2 text > Attribute 3 = Attribute 3 text > Attribute 7 = Attribute 7 text > Attribute 8 = Attribute 8 text > > Etc.for many hundreds of records > > I am looking to create output that looks like: > > Attribute 1 text | Attribute 3 text > Attribute 1 text | Attribute 3 text > Blank | Attribute 3 text > > Treating each record as a record with its associated lines is the holy grail > for which I am searching, yet I seem to only be coming up with dead parrots. > It should be simple, but the answer is eluding me and Google has not been > helpful. > > Pathetic thing is that I do this with Python and XML all the time, but I > can't seem to figure out a simple text file. I 'm missing something simple, > I'm sure. Here's the most I have gotten to work (poorly) so far - it gets > me the correct data, but not in the correct format because the file is being > handled sequentially, not by record - it's not even close, but I thought I'd > include it here: > > for line in infile: > while line != '\n': > Attribute1 = 'Blank' > Attribute3 = 'Blank' > line = line.lstrip('\t') > line = line.rstrip('\n') > LineElements = line.split('=') > if LineElements[0] == 'Attribute1 ': > Attribute1=LineElements[1] > if LineElements[0] == 'Attribute3 ': > Attribute3=LineElements[1] > print("%s | %s\n" % (Attribute1, Attribute3)) > > Is there a library or example I could be looking at for this? I use lxml > for xml, but I don't think it will work for this - at least the way I tried > did not. I don't think any existing library will fit your format, unless you happen to be very lucky. What you probably want is to write a generator function that gives you a record at a time. It'll take a file object (infile) and it'll yield a list of lines. Then your main loop would be something like: for record in records(infile): attrib1 = attrib2 = "" for line in record: line = strip(line) line_elements = line.split("=") etc. here you print out the attrib1/2 as appropriate I'll leave you to write the records() generator. But the next() method will probably play a part. -- DaveA From norman at khine.net Sun Nov 11 11:48:22 2012 From: norman at khine.net (Norman Khine) Date: Sun, 11 Nov 2012 10:48:22 +0000 Subject: [Tutor] checking if regex in pattern Message-ID: hello, i have this code >>> import re >>> import BeautifulSoup >>> matcher = re.compile(r"""

Burkina Faso, Cercle des S?cheurs

Burkina Faso, Cercle des S?cheurs

Ajouter ? ma liste d'envies

""" I can print the text out but I am unsure how to check for the pattern as I would like to check if pattern exists and then extract the Country and Producer - in this case: Burkina Faso and Cercle des S?cheurs if i try: >>> for txt in soup.findAll(text=True): ... print type(txt) ... >>> for txt in soup.findAll(text=True): ... matches = matcher.match(txt) ... if matches: ... print txt ... Traceback (most recent call last): File "", line 2, in AttributeError: 'builtin_function_or_method' object has no attribute 'match' >>> what am i missing? From emailkgnow at gmail.com Sun Nov 11 12:39:42 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 11 Nov 2012 14:39:42 +0300 Subject: [Tutor] Connecting to a DB via a function call Message-ID: Hi, Why is it that the following even though I call the below function? And how do I write a function that makes connection that I can use to query my DB? Traceback (most recent call last): File "C:/Python33/My Stuff/schedule_machine/schedule_machine01.py", line 19, in cur.execute('INSERT INTO schedule \ NameError: name 'cur' is not defined 1. import csv 2. import sqlite3 3. 4. def connect(): 5. conn = sqlite3.connect(':memory:')#use sch3.db or sch4.db .... etc. 6. cur = conn.cursor() 7. cur.execute("create table schedule (teams integer, sn integer, badge integer ,name text, grp integer,\ 8. major text, track text, stage text, tc text)") 9. 10. connect() -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Sun Nov 11 12:45:19 2012 From: norman at khine.net (Norman Khine) Date: Sun, 11 Nov 2012 11:45:19 +0000 Subject: [Tutor] Connecting to a DB via a function call In-Reply-To: References: Message-ID: hi On Sun, Nov 11, 2012 at 11:39 AM, Khalid Al-Ghamdi wrote: > Hi, > > Why is it that the following even though I call the below function? And how > do I write a function that makes connection that I can use to query my DB? > > Traceback (most recent call last): > File "C:/Python33/My Stuff/schedule_machine/schedule_machine01.py", line > 19, in > cur.execute('INSERT INTO schedule \ > NameError: name 'cur' is not defined > > import csv > import sqlite3 > > def connect(): > conn = sqlite3.connect(':memory:')#use sch3.db or sch4.db .... etc. > cur = conn.cursor() > cur.execute("create table schedule (teams integer, sn integer, badge > integer ,name text, grp integer,\ > major text, track text, stage text, tc text)") > > connect() > try this http://docs.python.org/2/library/sqlite3.html > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From norman at khine.net Sun Nov 11 13:05:51 2012 From: norman at khine.net (Norman Khine) Date: Sun, 11 Nov 2012 12:05:51 +0000 Subject: [Tutor] checking if regex in pattern In-Reply-To: References: Message-ID: ok, i think i have it On Sun, Nov 11, 2012 at 10:48 AM, Norman Khine wrote: > hello, > > i have this code > >>>> import re >>>> import BeautifulSoup >>>> matcher = re.compile(r"""

Burkina Faso, Cercle des S?cheurs

Burkina Faso, Cercle des S?cheurs

Ajouter ? ma liste d'envies

""" > > I can print the text out but I am unsure how to check for the pattern > as I would like to check if pattern exists and then extract the > Country and Producer - in this case: Burkina Faso and Cercle des > S?cheurs > > if i try: > >>>> for txt in soup.findAll(text=True): > ... print type(txt) > ... > >>>> for txt in soup.findAll(text=True): > ... matches = matcher.match(txt) > ... if matches: > ... print txt > ... > Traceback (most recent call last): > File "", line 2, in > AttributeError: 'builtin_function_or_method' object has no attribute 'match' >>>> >>> for txt in soup.findAll(text=True): ... if re.search('Origine',txt,re.I): ... print txt.next ... Burkina Faso, Cercle des S??cheurs Burkina Faso, Cercle des S??cheurs > > > what am i missing? From d at davea.name Sun Nov 11 14:10:10 2012 From: d at davea.name (Dave Angel) Date: Sun, 11 Nov 2012 08:10:10 -0500 Subject: [Tutor] Connecting to a DB via a function call In-Reply-To: References: Message-ID: <509FA3B2.4050305@davea.name> On 11/11/2012 06:39 AM, Khalid Al-Ghamdi wrote: > Hi, > > Why is it that the following even though I call the below function? And how > do I write a function that makes connection that I can use to query my DB? > > Traceback (most recent call last): > File "C:/Python33/My Stuff/schedule_machine/schedule_machine01.py", line > 19, in > cur.execute('INSERT INTO schedule \ > NameError: name 'cur' is not defined > > > 1. import csv > 2. import sqlite3 > 3. > 4. def connect(): > 5. conn = sqlite3.connect(':memory:')#use sch3.db or sch4.db .... > etc. > 6. cur = conn.cursor() > 7. cur.execute("create table schedule (teams integer, sn integer, > badge integer ,name text, grp integer,\ > 8. major text, track text, stage text, tc text)") > 9. > 10. connect() > > Thank you for posting the full traceback. The code you posted doesn't match the error you show. For one thing, there's no line 19. For another, the literal string of the line shown in the error doesn't agree with the one in the displayed code. Next, the variable is clearly defined in line 6, with no conditional to skip around it. Next, the error happens in top-level code, not inside any function. Finally, the def would never execute, since it has an indentation error in line 8. My guess is that you do not have the call to connect() in line 10, and that you have another attempt to call the execute method at line 19. I'm not the one to advise you on the database stuff, but if anyone is to help you, you need to post code that matches the error you post. Incidentally, although it doesn't matter much for 10 lines, you should ditch the line numbers when posting. Paste the source file contents as it really exists. Otherwise, you're making it harder for everyone who tries to run your code. -- DaveA From alan.gauld at btinternet.com Sun Nov 11 16:37:00 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Nov 2012 15:37:00 +0000 Subject: [Tutor] Connecting to a DB via a function call In-Reply-To: References: Message-ID: On 11/11/12 11:39, Khalid Al-Ghamdi wrote: > Hi, > > Why is it that the following even though I call the below function? And > how do I write a function that makes connection that I can use to query > my DB? The code and error don't align so it would help if we could see the actual code that generated the error. However there are some comments we can make about your function... > def connect(): > conn = sqlite3.connect(':memory:')#use sch3.db or sch4.db .... > cur = conn.cursor() > cur.execute("create table schedule (teams integer, sn integer, > badge integer ,name text, grp integer,\ > major text, track text, stage text, tc text)") You are doing everything inside the function so when the function ends all the local variables will be destroyed. Nothing is being passed back to the outside world. You probably want a 'return cur' Also by executing a create table inside the connect you seriously limit the reuse of your connect() function. Are you sure you always want to create a new schedule table every time you connect? You can find some sample SQLite code in my tutorial (v2 only) under the databases topic. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emailkgnow at gmail.com Mon Nov 12 09:29:23 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Mon, 12 Nov 2012 11:29:23 +0300 Subject: [Tutor] Adding items from a cursor to a dict? Message-ID: Hi all, How would you go about adding items from a cursor to a dictionary? i tried this but to no avail: >>> cur.execute('select * from schedule limit 10') >>> for i in range(len(cur.fetchall())): d[i]=cur.fetchall()[i] Traceback (most recent call last): File "", line 2, in d[i]=cur.fetchall()[i] IndexError: list index out of range Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Nov 12 10:15:13 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Nov 2012 09:15:13 +0000 Subject: [Tutor] Adding items from a cursor to a dict? In-Reply-To: References: Message-ID: On 12/11/12 08:29, Khalid Al-Ghamdi wrote: > Hi all, > How would you go about adding items from a cursor to a dictionary? > > i tried this but to no avail: > > >>> cur.execute('select * from schedule limit 10') > > >>> for i in range(len(cur.fetchall())): > d[i]=cur.fetchall()[i] > The second fetchall() won't return anything because you already fetched all there was to fetch in the first call. But why would you want a dictionary indexed by sequence number? You'd be better off with a list, which is what fetchall() gives you.. The normal pattern would be for row in cur.fetchall(): d[ row[0] ] = row # assuming row[0] is the desired key or similar. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From timomlists at gmail.com Mon Nov 12 12:17:52 2012 From: timomlists at gmail.com (Timo) Date: Mon, 12 Nov 2012 12:17:52 +0100 Subject: [Tutor] Adding items from a cursor to a dict? In-Reply-To: References: Message-ID: <50A0DAE0.4060009@gmail.com> Op 12-11-12 09:29, Khalid Al-Ghamdi schreef: > Hi all, > How would you go about adding items from a cursor to a dictionary? There is a nice buitin way, with example here: http://docs.python.org/2/library/sqlite3.html#sqlite3.Row It's not a real dictionary though, but it can act like it. Also, the docs say the following: """ If returning a tuple doesn?t suffice and you want name-based access to columns, you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution. """ Timo > > i tried this but to no avail: > > >>> cur.execute('select * from schedule limit 10') > > >>> for i in range(len(cur.fetchall())): > d[i]=cur.fetchall()[i] > > Traceback (most recent call last): > File "", line 2, in > d[i]=cur.fetchall()[i] > IndexError: list index out of range > > Thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From norman at khine.net Mon Nov 12 16:48:36 2012 From: norman at khine.net (Norman Khine) Date: Mon, 12 Nov 2012 15:48:36 +0000 Subject: [Tutor] correctly encoding of BeautifulSoup content Message-ID: hello, i have this piece of code (http://pastie.org/5366200) which uses BeatifulSoup to scrape content from a site, the html for the example can be seen here http://pastie.org/5366172 short_description = soup.find('div', attrs={"class": "short-description"}) if short_description: short_desc = short_description.find('div', attrs={"class": "std"}) if short_desc: adm_product.append(short_desc.renderContents()) long_description = soup.find('div', attrs={"class": "box-collateral box-description"}) if long_description: long_desc = long_description.find('div', attrs={"class": "std"}) if long_desc: adm_product.append(long_desc.renderContents()) L = [] for tag in long_desc.recursiveChildGenerator(): if isinstance(tag,BeautifulSoup.Tag): L.append(tag.renderContents()) desc = " ".join(v for v in L if v > 0) print desc adm_product.append(desc) else: adm_product.append('pas du description') # we get the country and producer for txt in product_shop.findAll(text=True): if re.search('Origine',txt,re.I): origin = txt.next.strip() try: country, producer = origin.split(', ') except Exception, e: pass else: adm_product.append(country) adm_product.append(producer) when i print the adm_product list i get: ['002267', 'Barre chocolat au lait fourr\xc3\xa9e \xc3\xa0 la cr\xc3\xa8me de lait
25g, bio et \xc3\xa9quitable
Produit bio contr\xc3\xb4l\xc3\xa9 par Bio Inspecta', 'CHOKICHOC : la barre de chocolat au lait, fourrée à la crème de lait CHOKICHOC : la barre de chocolat au lait, fourrée à la crème de lait Exquis mélange des plus fins cacaos et de l’aromatique sucre bio du Paraguay, CHOKICHOC est composée exclusivement de matières premières cultivées sans additif ni arôme artificiel. Tous les ingrédients proviennent de cultures biologiques. Légère, fondante, idéale pour le goûter, un vrai délice! Légère, fondante, idéale pour le goûter, un vrai délice! La commercialisation des barres CHOKICHOC garantit un prix minimum pour le producteur, des contrats d’achats à long terme ainsi que le préfinancement partiel de la récolte.', '0,90\xc2\xa0', u'/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/0/0/002267_2.jpg', u'Burkina Faso', u'Cercle des S\xe9cheurs'] my list item[1] is correctly encoded, but item[2] is not; nor are the last 2 items what am i missing? thanks From bbbgggwww at gmail.com Tue Nov 13 03:49:12 2012 From: bbbgggwww at gmail.com (brandon w) Date: Mon, 12 Nov 2012 21:49:12 -0500 Subject: [Tutor] Questions about classes Message-ID: I have been trying to understand classes. I have been studying from a book I picked up recently. I have two questions about them. 1. I saw in the book an assignment written like this: class HumanBeing: def makeName(self, name): *self.name = name* * * Why is it not written like this?: class HumanBeing: def makeName(self, name): * name = self.name* * * 2. Why use a class in the first place? What is the purpose of constructing a class instead of just writing a program with a bunch of functions? Thanks, Brandon -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Tue Nov 13 04:14:45 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 13 Nov 2012 03:14:45 +0000 Subject: [Tutor] Questions about classes In-Reply-To: References: Message-ID: On 13/11/2012 02:49, brandon w wrote: > I have been trying to understand classes. I have been studying from a book > I picked up recently. > I have two questions about them. > > 1. I saw in the book an assignment written like this: > > class HumanBeing: > def makeName(self, name): > *self.name = name* > * > * > Why is it not written like this?: > > class HumanBeing: > def makeName(self, name): > * name = self.name* > * > * > 2. Why use a class in the first place? What is the purpose of constructing > a class instead of just writing a program with a bunch of functions? > > > Thanks, > > Brandon > This is not a Python question, so please do some research into something like object orientated vs functional vs procedural programming styles. When you've read and misunderstood, come back and ask again, and we'll explain The Zen of Python, specifically "practicality beats purity" :) -- Cheers. Mark Lawrence. From amonroe at columbus.rr.com Tue Nov 13 04:13:42 2012 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon, 12 Nov 2012 22:13:42 -0500 Subject: [Tutor] Questions about classes In-Reply-To: References: Message-ID: <425215401.20121112221342@columbus.rr.com> > 2. Why use a class in the first place? What is the purpose of > constructing a class instead of just writing a program with a bunch > of functions? Sometimes, you DO just write programs with functions. A class can be useful if you have a bunch of a thing. Like a monster. Each monster can know its own location, hitpoints, etc. Alan From rbeniga04 at gmail.com Tue Nov 13 04:56:16 2012 From: rbeniga04 at gmail.com (Rufino Beniga) Date: Mon, 12 Nov 2012 19:56:16 -0800 Subject: [Tutor] functions and iterations Message-ID: def IterateLogistic(x,r,n): for i in xrange(n): x = r*(1-x) if i = n: print x I want this function to take in x and r which can be any two real numbers and after a certain number of iterations (n), the function should print the current state which is x. I tried this function and it doesn't do anything. May you please tell me what i did wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From thudfoo at gmail.com Tue Nov 13 06:01:48 2012 From: thudfoo at gmail.com (xDog Walker) Date: Mon, 12 Nov 2012 21:01:48 -0800 Subject: [Tutor] functions and iterations In-Reply-To: References: Message-ID: <201211122101.48159.thudfoo@gmail.com> On Monday 2012 November 12 19:56, Rufino Beniga wrote: > def IterateLogistic(x,r,n): > ? ? for i in xrange(n): > ? ? ? ? x = r*(1-x) > ? ? ? ? if i = n: > ? ? ? ? ? ? print x > > I want this function to take in x and r which can be any two real numbers > and after a certain number of iterations (n), the function should print the > current state which is x. I tried this function and it doesn't do anything. > May you please tell me what i did wrong? Python 2.7.2 (default, Oct 10 2011, 10:47:36) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def IterateLogistic(x,r,n): ... for i in xrange(n): ... x = r*(1-x) ... if i = n: File "", line 4 if i = n: ^ SyntaxError: invalid syntax >>> print x -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. From thudfoo at gmail.com Tue Nov 13 06:21:45 2012 From: thudfoo at gmail.com (xDog Walker) Date: Mon, 12 Nov 2012 21:21:45 -0800 Subject: [Tutor] functions and iterations In-Reply-To: References: <201211122101.48159.thudfoo@gmail.com> Message-ID: <201211122121.45683.thudfoo@gmail.com> On Monday 2012 November 12 21:07, you wrote: > I tried it with i == n as well and it still doesnt work :/ Check the documentation on range and xrange and you will find out why i never equals n. >>> n = 5 >>> range(n) [0, 1, 2, 3, 4] >>> for i in xrange(n): print i ... 0 1 2 3 4 >>> -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. From rbeniga04 at gmail.com Tue Nov 13 07:43:20 2012 From: rbeniga04 at gmail.com (Rufino Beniga) Date: Mon, 12 Nov 2012 22:43:20 -0800 Subject: [Tutor] writing files using modules and functions Message-ID: def MatInv(arr,file): f = open('file.txt','w') f.write(arr) f.close() So I'm trying to write a module that will take a matrix (arr) and write it to a text file. The above module is called MatrixIO.py #first I import it import MatrixIO #Then i call the function MatInv with matrix(a) and file name (doc) as the arguments MatInv(a,doc) It creates a file called txt and it shows only boxes. What am I doing wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Nov 13 09:35:03 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Nov 2012 08:35:03 +0000 Subject: [Tutor] writing files using modules and functions In-Reply-To: References: Message-ID: On 13/11/12 06:43, Rufino Beniga wrote: > def MatInv(arr,file): > f = open('file.txt','w') > f.write(arr) > f.close() > > So I'm trying to write a module that will take a matrix (arr) and write > it to a text file. > The above module is called MatrixIO.py > > #first I import it > > import MatrixIO > > #Then i call the function MatInv with matrix(a) and file name (doc) as > the arguments > MatInv(a,doc) > > It creates a file called txt and it shows only boxes. What am I doing wrong? We can't tell until we see your code. Assuming its not more than 100 lines or so why not post it? If it is more then try creating a smaller example... The most likely thing is that the data is binary and when you display it the values do not map to printable values. You probably need to convert the array to strings before writing. But that's just a guess because I can't see what you are doing. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From d at davea.name Tue Nov 13 09:50:38 2012 From: d at davea.name (Dave Angel) Date: Tue, 13 Nov 2012 03:50:38 -0500 Subject: [Tutor] Questions about classes In-Reply-To: References: Message-ID: <50A209DE.3000805@davea.name> On 11/12/2012 09:49 PM, brandon w wrote: > I have been trying to understand classes. I have been studying from a book > I picked up recently. > I have two questions about them. > > 1. I saw in the book an assignment written like this: > > class HumanBeing: > def makeName(self, name): > *self.name = name* > * > * > Why is it not written like this?: > > class HumanBeing: > def makeName(self, name): > * name = self.name* > * > * Presumably there are also other methods, including an __init__ one. That's where initial attributes are (or should be) assigned. You don't say what else you *do* understand. So I'll assume you know what functions are, and how arguments are passed into parameters. A class method is very similar, except that it has an extra argument, normally called 'self', which is usually passed in a funny way. You know what a list is? It's an instance of the list class, and it has certain methods. Some of those are done with special syntax, like [5], while others are done with standard method syntax, like the third line below: mylist = list( (3,4) ) #this is usually shortcutted as [3,4] item = 42 mylist.append(item) mylist is an instance of list, and if you were to look at the class definition of list, it'd have a method called append. In this case, the self parameter of that method refers to mylist (the object), and the other parameter of that method refers to item. A class that you write is usually like a collection, with a bunch of data items (data attributes), and a bunch of methods (method attributes) to manipulate them. But unlike a list, they don't have to be uniform -- you define their behavior entirely. And each time you create an instance of that class, it gets its own set of attributes. This persistence of data between method calls is most of what makes the class approach more powerful than functions. Anyway, back to your example. class HumanBeing: def makeName(self, name): *self.name = name* name is the second parameter, while self.name is an attribute on the current instance. So if it's the latter you want changed, you'd better have it on the left side of the equals sign. > 2. Why use a class in the first place? What is the purpose of constructing > a class instead of just writing a program with a bunch of functions? > > > See above. A class lets you collect multiple characteristics of a "thing" (object) under one roof, along with the methods to manipulate them. For the HumanBeing class, I'd have data attributes for things like name, address, birthdate, bank_account_num. And the individual attributes might change over the life of the object, but they're all kept together. If you only had one HumanBeing to deal with in a given program, it wouldn't matter much. But if you have a lot of them, trying to use global variables is very sloppy. BTW, I wouldn't have a makeName() method, unless I had to start keeping track of a person (infant) before they got their name. But I very well might have a changeName method, to be used at marriage and divorce, or whenever a person went to court to have it changed. -- DaveA From d at davea.name Tue Nov 13 10:08:28 2012 From: d at davea.name (Dave Angel) Date: Tue, 13 Nov 2012 04:08:28 -0500 Subject: [Tutor] writing files using modules and functions In-Reply-To: References: Message-ID: <50A20E0C.9050605@davea.name> On 11/13/2012 01:43 AM, Rufino Beniga wrote: > def MatInv(arr,file): > f = open('file.txt','w') > f.write(arr) > f.close() > > So I'm trying to write a module that will take a matrix (arr) and write it > to a text file. > The above module is called MatrixIO.py > > #first I import it > > import MatrixIO > > #Then i call the function MatInv with matrix(a) and file name (doc) as the > arguments > MatInv(a,doc) > > It creates a file called txt and it shows only boxes. What am I doing wrong? > > Before you try to figure out how it'll work in two modules, make it work in one script. Since you don't post enough code to actually run it, we'd only be guessing why. And even the code you show is wrong. The call to MatInv won't work with that import statement; you'd need to qualify it. def matrix(values): return something?? import Matrix10 a = matrix(42) doc = something else, perhaps a string literal Matrix10.MatInv(a.doc) So clearly you have some different source, if it ever gets as far as writing to the file. Strip the code to a minimal test (pref. under 50 lines) Specify Python version, OS type and version Specify website and version for any non-standard library you import (eg. perhaps matrix) Show the filenames and contents for all the source you supply Show the full traceback of any error you get, OR Explain what you expected it to do, and how it was different If I had to make a wild guess, I'd say that matrix was some form of collection of floating point numbers. But I have no idea what it supplies to the write method, nor why one would expect that it should be printable. Might help to look at the docs for matrix. -- DaveA From norman at khine.net Tue Nov 13 10:50:35 2012 From: norman at khine.net (Norman Khine) Date: Tue, 13 Nov 2012 09:50:35 +0000 Subject: [Tutor] mapping list appends to correct position for csv output Message-ID: hello, i am trying to create a csv file in python and map the fields to a pre-existing fields, here is the title fileds of my csv c = csv.writer(open("adm_products.csv", "wb"), delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL) import_fields = ["ID", "Active (0/1)", "Name *", "Categories (x,y,z...)", "Price tax excl. or Price tax incl.", "Tax rules ID", "Wholesale price", "On sale (0/1)", "Discount amount", "Discount percent", "Discount from (yyyy-mm-dd)", "Discount to (yyyy-mm-dd)", "Reference #", "Supplier reference #", "Supplier", "Manufacturer", "EAN13", "UPC", "Ecotax", "Weight", "Quantity", "Short description", "Description", "Tags (x,y,z...)", "Meta-title", "Meta-keywords", "Meta-description", "URL rewritten", "Text when in stock", "Text when backorder allowed", "Available for order (0 = No, 1 = Yes)", "Product creation date", "Show price (0 = No, 1 = Yes)", "Image URLs (x,y,z...)", "Delete existing images (0 = No, 1 = Yes)", "Feature(Name:Value:Position)", "Available online only (0 = No, 1 = Yes)", "Condition", "ID / Name of shop"] so for example: adm_product = [] for category in breadcrumbs.findAll('li', { "class" : re.compile(r'\bcategory\d')}): adm_product.append(category.find('a').renderContents()) # MAP TO CATEGORY product_shop = soup.find('div', attrs={"class": "product-shop"}) product_sku = soup.find('p', attrs={"class": "product-sku"}) if product_sku: sku = product_sku.renderContents() product_ref = ref(sku)[0] adm_product.append(product_ref) # MAP TO REFERENCE # short_description = soup.find('div', attrs={"class": "short-description"}) if short_description: short_desc = short_description.find('div', attrs={"class": "std"}) if short_desc: adm_product.append(short_desc.renderContents()) # MAP TO SHORT DESCRIPTION What is the correct way to map the product_ref to the Reference # in the import_fields list with any missing values being left blank or create a csv so that when i append a value it is added to the correct column? also which is more efficient: c.writerow(adm_product) # writing the product to the csv when all the fileds are found or products = [] # adding them to a list first and then writing them to the csv products.append(adm_product) c.writerow(x) for x in products From alan.gauld at btinternet.com Tue Nov 13 12:08:25 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Nov 2012 11:08:25 +0000 Subject: [Tutor] Questions about classes In-Reply-To: References: Message-ID: On 13/11/12 02:49, brandon w wrote: > class HumanBeing: > def makeName(self, name): > * self.name = name > * > * > Why is it not written like this?: > > class HumanBeing: > def makeName(self, name): > * name = self.name Because they two completely different things :-) The first example takes an argument and assigns it to an attribute of the object 'self'. The second takes an argument and assigns the value of the object attribute to the argument (which will then get thrown away when the function exits) When we use self.xxx we are accessing or storing that value in an object such that its value persists beyond the life of the function. attributes of objects are a bit like module (or global) level variables except they are unique to a specific object. So whereas using global variables is considered bad practice using object attributes is good. You get the advantages of shared data without the problems of global names. > 2. Why use a class in the first place? What is the purpose of > constructing a class instead of just writing a program with a bunch of > functions? We write classes as a convenient way of encapsulating functions and data that we want to reuse, either within a single project or across projects. We reuse them by creating objects. It is the objects that are useful, classes are the mechanism for creating objects. The problem with writing code purely with functions (and data) is the management of the data. Its fine if you only have a few data elements but when you start processing hundred, thousands or millions of data entities keeping them all stored separately and writing functions to access the data, making sure you don't corrupt one item while working on another becomes a real headache. If you now start parallel processing it gets even worse. Just like modules are a way to control complexity and avoid data management issues classes do the same at a finer granularity. Many people also find thinking about problems in terms of the objects involved more intuitive than separating the problem into functions and data. The real world is made up of objects that interact so it makes sense to build our software the same way. This is more effective in programs that model real world entities than in more abstract areas. But it can be a real benefit in things like GUIs where we have objects like windows, buttons, sliders, menus etc. Having code that reflects those visible objects makes GUI development much easier. Even in the standard Python library we have string objects, file objects, and so on. Classes allow us to extend those concepts by creating our own objects. They are optional though. You don't have to use them. You can achieve an awful lot without them. But often they make life easier, especially as your programs get bigger and more complex. You'll find more detailed info and examples in the OOP topic of my tutorial. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 13 12:15:43 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Nov 2012 11:15:43 +0000 Subject: [Tutor] functions and iterations In-Reply-To: References: Message-ID: On 13/11/12 03:56, Rufino Beniga wrote: > def IterateLogistic(x,r,n): > for i in xrange(n): > x = r*(1-x) > if i = n: > print x > DogWalker has answered your basic question. But you don't really need the test at all. Just print x after the loop finishes: def IterateLogistic(x,r,n): for i in xrange(n): x = r*(1-x) print x But printing inside a function is usually not the best thing to do. It's generally better practice to return the value and then print the result externally: def IterateLogistic(x,r,n): for i in xrange(n): x = r*(1-x) return x print IterateLogistic(5,2,4) It makes your function much more reusable. You can print the result or store it in a variable for later, or even use it directly in a bigger more complex expression. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Nov 13 12:42:36 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Nov 2012 11:42:36 +0000 Subject: [Tutor] mapping list appends to correct position for csv output In-Reply-To: References: Message-ID: On 13/11/12 09:50, Norman Khine wrote: > also which is more efficient: > > c.writerow(adm_product) # writing the product to the csv when all the > fileds are found > > or > > products = [] # adding them to a list first and then writing them to the csv > products.append(adm_product) > c.writerow(x) for x in products Don't guess, measure. Write a small test and compare. timeit is your friend. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Nov 13 13:57:47 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 13 Nov 2012 23:57:47 +1100 Subject: [Tutor] Questions about classes In-Reply-To: References: Message-ID: <50A243CB.1080208@pearwood.info> On 13/11/12 13:49, brandon w wrote: > 1. I saw in the book an assignment written like this: > > class HumanBeing: > def makeName(self, name): > *self.name = name* > * > * > Why is it not written like this?: > > class HumanBeing: > def makeName(self, name): > * name = self.name* This creates a class called "HumanBeing". It includes a method called "makeName". Methods are very similar to functions, the differences will become clear further on. Methods are defined in the same way as functions: the "def" keyword, followed by the name of method, then the parameters. Each parameter creates a local variable, so the "makeName" method has two local variables: - self - name "self" is special. When you call the method, Python will automatically provide the "self" argument. So if you do this: fred = HumanBeing() # create an instance of HumanBeing class fred.makeName("flintstone") the makeName method gets passed two arguments: - self = fred, provided automatically by Python - name = "flintstone", provided by you Now, inside the body of the method, we have this: self.name = name That says: - take the argument *name* (which has value "flintstone") - attach it to the instance *self* using the attribute called "name" After the line finishes executing, the instance *fred* will now have an attribute *name* with value "flintstone". So if you later call: print(fred.name) Python will print "flintstone". What if it were written the other way, as you suggested? name = self.name That goes in the opposite direction: first Python tries to look up an attribute called name. It probably doesn't find one, and so it will raise an exception and print an error message. But let's suppose it did find one. It then takes that value and stores it in the local variable "name", over-writing the local variable you provided as an argument to the method. Then, when the method returns (either at a "return" statement, or by reaching the end of the method), the local variable is forgotten and no permanent change is made. > 2. Why use a class in the first place? What is the purpose of constructing > a class instead of just writing a program with a bunch of functions? Classes are useful for a couple of reasons: 1) Encapsulation A class keeps together related code and data. A good example comes from the Python built-in class "list". The list class combines: - a storage area for the list data; - methods which operate on that list data. For example, lists have a method "index". But strings also have a method called "index". The list.index method knows how to search a list. It knows nothing about strings, and doesn't need to care about strings. It only needs to care about lists. The str.list method knows how to search a string. It knows nothing about lists, and only cares about strings. That makes it much easier to program. Instead of one giant function: def index(obj, value): if obj is a string: code for searching strings elif obj is a list: code for searching lists elif obj is a tuple: code for searching tuples else: raise TypeError("don't know how to index obj") instead each branch of the function gets encapsulated into a str class, a list class, a tuple class, and anything else that you might want to index. If you write a Book class, you can give it an index method without needing to care about lists, strings, tuples, etc. The other advantage of classes is: 2) Inheritance With classes, you can *inherit* behaviour by creating a subclass. Say, for example, you want a type of list that is exactly the same as ordinary lists except that every time you append a value, it prints what you appended. This might be useful for debugging. Without inheritance, you would have to duplicate the entire code base for list, many hundreds or thousands of lines of code. But with inheritance, it just takes FOUR lines: class MyList(list): def append(self, value): print("appending %s" % value) super(MyList, self).append(value) This creates a new class called "MyList", which inherits from the built-in list class; everything else is the same as list, except for the append method, which prints the value first, then calls the built-in list.append method. (If the super() call looks a bit mysterious, don't worry too much about it right now.) So between encapsulation and inheritance, classes are a powerful tool for programming. -- Steven From wolfrage8765 at gmail.com Tue Nov 13 15:15:35 2012 From: wolfrage8765 at gmail.com (wolfrage8765 at gmail.com) Date: Tue, 13 Nov 2012 15:15:35 +0100 Subject: [Tutor] Parsing a multi-line/record text file In-Reply-To: <005801cdbfc9$a9689eb0$fc39dc10$@org> References: <005801cdbfc9$a9689eb0$fc39dc10$@org> Message-ID: On Sun, Nov 11, 2012 at 6:01 AM, Marc wrote: > ** > > Hello, > > I am trying to parse a text file with a structure that looks like: > > [record: Some text about the record] > > Attribute 1 = Attribute 1 text > > Attribute 3 = Attribute 3 text > > Attribute 4 = Attribute 4 text > > Attribute 7 = Attribute 7 text > > [record: Some text about the record] > > Attribute 1 = Attribute 1 text > > > > Etc?for many hundreds of records > It looks like a Config or INI file to me. It is worth a try to see if configparser is able to process the file, if it can you have a solution, if not you only wasted a few minutes trying. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pdickeybeta at gmail.com Tue Nov 13 16:42:55 2012 From: pdickeybeta at gmail.com (Patrick Dickey) Date: Tue, 13 Nov 2012 09:42:55 -0600 Subject: [Tutor] Reusing Timers (threading.timer) Message-ID: <1352821375.3276.21.camel@dcky-ubuntu64> Hi everyone, I've got an application that will use a timer to run a function automatically (it's an update function for my IPv6 endpoint). The questions that I have are these: 1. Can I stop and start the timer from different functions or methods in my program, and if so, how? 2. Can I stop the timer, change the value, and restart it (or would it create a new timer), or do I have to create a new timer with an entirely new name? 3. If I get a value from a textbox, how do I parse it from the string value to an integer (or float)? 4. Is there a better way of accomplishing this task? Here's the pseudocode for what I'm doing. if autoUpdates is enabled get updateFrequency start timer with time value from updateFrequency when time is reached, run update method else cancel timer if autoUpdates is enabled AND user changes updateFrequency stop timer get updateFrequency start timer with new time value from updateFrequency The autoUpdates and updateFrequency are a checkbox and text box in wxPython. Thanks for any advice on this, and have a great day.:) Patrick. From alan.gauld at btinternet.com Tue Nov 13 18:32:31 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Nov 2012 17:32:31 +0000 Subject: [Tutor] Reusing Timers (threading.timer) In-Reply-To: <1352821375.3276.21.camel@dcky-ubuntu64> References: <1352821375.3276.21.camel@dcky-ubuntu64> Message-ID: On 13/11/12 15:42, Patrick Dickey wrote: > 1. Can I stop and start the timer from different functions or methods > in my program, and if so, how? > 2. Can I stop the timer, change the value, and restart it (or would it > create a new timer), or do I have to create a new timer with an entirely > new name? I can't help with threading.timer since I've never used it but... > 3. If I get a value from a textbox, how do I parse it from the string > value to an integer (or float)? Use int() or float() ? > 4. Is there a better way of accomplishing this task? Possibly. If you are using wxPython there is a timer (wx.Timer) in there that will fire an event (EVT_TIMER) after a suitable delay. This moves the timed event into your main processing code rather than having it in a thread. That might be easier. You can certainly start/stop the timer. You can recreate the timer with a new value after stopping. You can reuse the same variable name to store the timer. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dancingbush at gmail.com Tue Nov 13 23:50:16 2012 From: dancingbush at gmail.com (Ciaran Mooney) Date: Tue, 13 Nov 2012 22:50:16 +0000 Subject: [Tutor] Questions about classes In-Reply-To: <50A243CB.1080208@pearwood.info> References: <50A243CB.1080208@pearwood.info> Message-ID: <949E8C4E-B81D-4F05-8601-F2FEF8C60727@gmail.com> Hi, Was hoping someone could help me. I have downloaded the latest pygame 1.9.1 i think) to a Mac powerbook OS 10.4.11. Python 3 does not recognise pygame although python 2.7 version does (unfortunately have never programmed python 2.7 and don't no how). Any help would be much appreciated. Thanks Ciaran On 13 Nov 2012, at 12:57, Steven D'Aprano wrote: > On 13/11/12 13:49, brandon w wrote: > > >> 1. I saw in the book an assignment written like this: >> >> class HumanBeing: >> def makeName(self, name): >> *self.name = name* >> * >> * >> Why is it not written like this?: >> >> class HumanBeing: >> def makeName(self, name): >> * name = self.name* > > This creates a class called "HumanBeing". It includes a method called > "makeName". Methods are very similar to functions, the differences will > become clear further on. > > Methods are defined in the same way as functions: the "def" keyword, > followed by the name of method, then the parameters. Each parameter > creates a local variable, so the "makeName" method has two local > variables: > > - self > - name > > "self" is special. When you call the method, Python will automatically > provide the "self" argument. So if you do this: > > fred = HumanBeing() # create an instance of HumanBeing class > fred.makeName("flintstone") > > the makeName method gets passed two arguments: > > - self = fred, provided automatically by Python > - name = "flintstone", provided by you > > > Now, inside the body of the method, we have this: > > self.name = name > > That says: > > - take the argument *name* (which has value "flintstone") > - attach it to the instance *self* using the attribute called "name" > > After the line finishes executing, the instance *fred* will now have > an attribute *name* with value "flintstone". > > So if you later call: > > print(fred.name) > > Python will print "flintstone". > > What if it were written the other way, as you suggested? > > name = self.name > > That goes in the opposite direction: first Python tries to look up > an attribute called name. It probably doesn't find one, and so it > will raise an exception and print an error message. But let's > suppose it did find one. It then takes that value and stores it > in the local variable "name", over-writing the local variable you > provided as an argument to the method. > > Then, when the method returns (either at a "return" statement, or > by reaching the end of the method), the local variable is > forgotten and no permanent change is made. > > > >> 2. Why use a class in the first place? What is the purpose of constructing >> a class instead of just writing a program with a bunch of functions? > > Classes are useful for a couple of reasons: > > 1) Encapsulation > > A class keeps together related code and data. A good example comes from the > Python built-in class "list". The list class combines: > > - a storage area for the list data; > - methods which operate on that list data. > > For example, lists have a method "index". But strings also have a method > called "index". The list.index method knows how to search a list. It knows > nothing about strings, and doesn't need to care about strings. It only > needs to care about lists. The str.list method knows how to search a string. > It knows nothing about lists, and only cares about strings. That makes it > much easier to program. Instead of one giant function: > > > def index(obj, value): > if obj is a string: > code for searching strings > elif obj is a list: > code for searching lists > elif obj is a tuple: > code for searching tuples > else: > raise TypeError("don't know how to index obj") > > instead each branch of the function gets encapsulated into a str class, a > list class, a tuple class, and anything else that you might want to index. > If you write a Book class, you can give it an index method without needing > to care about lists, strings, tuples, etc. > > > The other advantage of classes is: > > 2) Inheritance > > With classes, you can *inherit* behaviour by creating a subclass. Say, for > example, you want a type of list that is exactly the same as ordinary lists > except that every time you append a value, it prints what you appended. This > might be useful for debugging. Without inheritance, you would have to > duplicate the entire code base for list, many hundreds or thousands of lines > of code. But with inheritance, it just takes FOUR lines: > > class MyList(list): > def append(self, value): > print("appending %s" % value) > super(MyList, self).append(value) > > > This creates a new class called "MyList", which inherits from the built-in > list class; everything else is the same as list, except for the append > method, which prints the value first, then calls the built-in list.append > method. > > (If the super() call looks a bit mysterious, don't worry too much about it > right now.) > > > > So between encapsulation and inheritance, classes are a powerful tool for > programming. > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Wed Nov 14 00:13:08 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Nov 2012 10:13:08 +1100 Subject: [Tutor] Questions about classes In-Reply-To: <949E8C4E-B81D-4F05-8601-F2FEF8C60727@gmail.com> References: <50A243CB.1080208@pearwood.info> <949E8C4E-B81D-4F05-8601-F2FEF8C60727@gmail.com> Message-ID: <50A2D404.6020703@pearwood.info> On 14/11/12 09:50, Ciaran Mooney wrote: > Hi, > Was hoping someone could help me. > I have downloaded the latest pygame 1.9.1 i think) to a Mac powerbook OS 10.4.11. What does this question have to do with classes? When starting a brand new discussion, start with a brand new email thread: * do NOT hit reply to an existing thread * instead use your email program to create a new, fresh email * set the TO address to tutor at python.org * set the subject line to something appropriate, e.g. "Does Python 3 recognise pygame?" * type your question * hit SEND PyGame and Python 3 is a frequently asked question. If you google for "pygame python 3", you will find plenty of answers to your question. E.g.: http://www.pygame.org/wiki/FrequentlyAskedQuestions?#Does%20Pygame%20work%20with%20Python%203? http://florian-berger.de/en/articles/installing-pygame-for-python-3-on-os-x Please have a look at some of those, and if you are still not sure how to get pygame working with Python 3, please come back with some specific questions. Good luck, -- Steven From steve at pearwood.info Wed Nov 14 00:50:51 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 14 Nov 2012 10:50:51 +1100 Subject: [Tutor] Reusing Timers (threading.timer) In-Reply-To: <1352821375.3276.21.camel@dcky-ubuntu64> References: <1352821375.3276.21.camel@dcky-ubuntu64> Message-ID: <50A2DCDB.8050006@pearwood.info> On 14/11/12 02:42, Patrick Dickey wrote: > Hi everyone, > > I've got an application that will use a timer to run a function > automatically (it's an update function for my IPv6 endpoint). The > questions that I have are these: Have you read the documentation? http://docs.python.org/2/library/threading.html#timer-objects > 1. Can I stop and start the timer from different functions or methods > in my program, and if so, how? As the docs say: [quote] Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method. [end quote] Any function or method that has access to the timer object can call the start or cancel method. You just need to make sure that the function can see the timer object, using one of the standard ways in Python of giving a function access to any other object: * (best) pass the object into the function as an argument result = myfunction(a, b, c, some_timer) * (easiest) make the timer a global variable * put the timer inside a dict, list or other container and pass it to the function * put the timer in an attribute of the object etc. > 2. Can I stop the timer, change the value, and restart it (or would it > create a new timer), or do I have to create a new timer with an entirely > new name? Changing the timer is not supported. I expect that calling my_timer.start() after cancelling it would restart it, but haven't tested it. Just because you create a new timer doesn't mean you have to give it an entirely new name. > 3. If I get a value from a textbox, how do I parse it from the string > value to an integer (or float)? This has nothing to do with timers, and should go into a separate email thread so that those people who know nothing about threading can contribute. Regardless of where the string comes from, you turn a string into an int or float by calling the int() or float() function. > 4. Is there a better way of accomplishing this task? > > Here's the pseudocode for what I'm doing. > > if autoUpdates is enabled > get updateFrequency > start timer with time value from updateFrequency > when time is reached, run update method > else > cancel timer Well that won't work, because once the update has run, it will stop checking for new updates. > if autoUpdates is enabled AND user changes updateFrequency > stop timer > get updateFrequency > start timer with new time value from updateFrequency Seems fine to me. -- Steven From awesome.me.dm at outlook.com Wed Nov 14 04:17:39 2012 From: awesome.me.dm at outlook.com (David Martins) Date: Wed, 14 Nov 2012 14:17:39 +1100 Subject: [Tutor] data analysis with python Message-ID: Hi All I'm trying to use python for analysing data from building energy simulations and was wondering whether there is way to do this without using anything sql like. The simulations are typically run for a full year, every hour, i.e. there are 8760 rows and about 100+ variables such as external air temperature, internal air temperature, humidity, heating load, ... making roughly a million data points. I've got the data in a csv file and also managed to write it in a sqlite db. I would like to make requests like the following: Show the number of hours the aircon is running at 10%, 20%, ..., 100% Show me the average, min, max air temperature, humidity, solar gains,.... when the aircon is running at 10%, 20%,...,100% Eventually I'd also like to generate an automated html or pdf report with graphs. Creating graphs is actually somewhat essential. I tried sql and find it horrible, error prone, too much to write, the logic somehow seems to work different than my brain and I couldn't find particulary good documentation (particulary the documentation of the api is terrible, in my humble opinion). I heard about zope db which might be an alternative. Would you mind pointing me towards an appropriate way to solve my problem? Is there a way for me to avoid having to learn sql or am I doomed? Thank you dm -------------- next part -------------- An HTML attachment was scrubbed... URL: From walksloud at gmail.com Wed Nov 14 04:26:45 2012 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Tue, 13 Nov 2012 19:26:45 -0800 Subject: [Tutor] data analysis with python In-Reply-To: References: Message-ID: Hi David, > I'm trying to use python for analysing data from building energy simulations and was wondering whether there is way to do this without using anything sql like. > > The simulations are typically run for a full year, every hour, i.e. there are 8760 rows and about 100+ variables such as external air temperature, internal air temperature, humidity, heating load, ... making roughly a million data points. I've got the data in a csv file and also managed to write it in a sqlite db. > > I would like to make requests like the following: > > Show the number of hours the aircon is running at 10%, 20%, ..., 100% > Show me the average, min, max air temperature, humidity, solar gains,.... when the aircon is running at 10%, 20%,...,100% > > Eventually I'd also like to generate an automated html or pdf report with graphs. Creating graphs is actually somewhat essential. > > I tried sql and find it horrible, error prone, too much to write, the logic somehow seems to work different than my brain and I couldn't find particulary good documentation (particulary the documentation of the api is terrible, in my humble opinion). I heard about zope db which might be an alternative. Would you mind pointing me towards an appropriate way to solve my problem? Is there a way for me to avoid having to learn sql or am I doomed? I would recommend learning hdf5 http://www.hdfgroup.org/HDF5/ and the python utility to interface with it pytables http://www.pytables.org/moin and numpy and scipy are great for data analysis (python libraries) - numpy handles things like linear algebra, scipy has many built in scientific functions. And then matplotlib for plotting (very similar functions to matlab if you are familiar with it). Lastly, a very nice interface is "iPython", which is basically an enhanced python interpreter designed for/by science types. All of these tools are installed for you with the Enthought Python Distribution (full dist is free if you have a .edu address, otherwise they provide a light version with basic libraries, and you can install others you like) http://www.enthought.com/ If you have any specific questions on these (I know that is a lot to look into right away) let me know. Cheers, Andre From ryan.waples at gmail.com Wed Nov 14 06:13:46 2012 From: ryan.waples at gmail.com (Ryan Waples) Date: Tue, 13 Nov 2012 21:13:46 -0800 Subject: [Tutor] data analysis with python In-Reply-To: References: Message-ID: Not sure how stuck you are to python (I have no doubt it can tackle this) but this is very much the sort of thing that 'R' is *really* good at. Just FYI. Good luck Ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: From awesome.me.dm at outlook.com Wed Nov 14 09:13:02 2012 From: awesome.me.dm at outlook.com (David Martins) Date: Wed, 14 Nov 2012 19:13:02 +1100 Subject: [Tutor] data analysis with python In-Reply-To: References: , , Message-ID: Thanks Andre and Ryan At first glance Pytables looks certainly a lot better than sql... I also found vitables which seems to be a nice GUI interface and will play around with both tomorrow. I remember having looked at R a while ago but did never pick it up. I found a nice tutorial and will give it a go. Cheers Chris Date: Tue, 13 Nov 2012 21:13:46 -0800 Subject: Re: [Tutor] data analysis with python From: ryan.waples at gmail.com To: walksloud at gmail.com CC: awesome.me.dm at outlook.com; tutor at python.org Not sure how stuck you are to python (I have no doubt it can tackle this) but this is very much the sort of thing that 'R' is *really* good at. Just FYI. Good luck Ryan -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Nov 14 09:26:23 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Nov 2012 08:26:23 +0000 Subject: [Tutor] data analysis with python In-Reply-To: References: , , Message-ID: On 14/11/12 08:13, David Martins wrote: > I remember having looked at R a while ago but did never pick it up. I > found a nice tutorial and will give it a go. There is an interface to R from Python too. So you can combine the two.. However, given your stated aims SQL does look like the most natural choice and is worth learning, it's really not that hard, especially if performance is not critical. But if you want to really crunch the data rather than just mine it then R or numpy might be better suited. BTW There are graphical GUI front tends to SQLite that hide the SQL from you so if you managed to get the data into SQLite you could use those to get it out again... Try a Google search. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bjorn.h.madsen at googlemail.com Wed Nov 14 09:28:57 2012 From: bjorn.h.madsen at googlemail.com (Bjorn Madsen) Date: Wed, 14 Nov 2012 08:28:57 +0000 Subject: [Tutor] data analysis with python In-Reply-To: References: Message-ID: Hi David, I have found happiness with http://ipython.org/ which can do stuff like this: [image: _images/ipy_0.13.png] SQLite is embedded in python's database API, and gives an easy data import and handling. The syntax is extremely well described here: http://www.sqlite.org/lang.html and I've been handling just short of 300million records on a EEE-netbook. And in context with iPython's visual display and HTML comment you should be able to save the print-out from iPython directly onto your web-server. Feel free to write if you get stuck. Kind Regards, Bjorn On 14 November 2012 05:13, Ryan Waples wrote: > Not sure how stuck you are to python (I have no doubt it can tackle this) > but this is very much the sort of thing that 'R' is *really* good at. > Just FYI. > Good luck > Ryan > > > _______________________________________________ > 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 oscar.j.benjamin at gmail.com Wed Nov 14 14:59:25 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 14 Nov 2012 13:59:25 +0000 Subject: [Tutor] data analysis with python In-Reply-To: References: Message-ID: On 14 November 2012 03:17, David Martins wrote: > Hi All > > I'm trying to use python for analysing data from building energy simulations > and was wondering whether there is way to do this without using anything sql > like. There are many ways to do this. > > The simulations are typically run for a full year, every hour, i.e. there > are 8760 rows and about 100+ variables such as external air temperature, > internal air temperature, humidity, heating load, ... making roughly a > million data points. I've got the data in a csv file and also managed to > write it in a sqlite db. This dataset is not so big that you can't just load it all into memory. > > I would like to make requests like the following: > > Show the number of hours the aircon is running at 10%, 20%, ..., 100% > Show me the average, min, max air temperature, humidity, solar gains,.... > when the aircon is running at 10%, 20%,...,100% > > Eventually I'd also like to generate an automated html or pdf report with > graphs. Creating graphs is actually somewhat essential. Do you mean graphs or plots? I would use matplotlib for plotting. It can automatically generate image files of plots. There are also ways to generate output for visualising graphs but I guess that's not what you mean. Probably I would create a pdf report using latex and matplotlib but that's not the only way. http://en.wikipedia.org/wiki/Graph_(mathematics) http://en.wikipedia.org/wiki/Plot_(graphics) > I tried sql and find it horrible, error prone, too much to write, the logic > somehow seems to work different than my brain and I couldn't find > particulary good documentation (particulary the documentation of the api is > terrible, in my humble opinion). I heard about zope db which might be an > alternative. Would you mind pointing me towards an appropriate way to solve > my problem? Is there a way for me to avoid having to learn sql or am I > doomed? There are many ways to avoid learning SQL. I'll suggest the simplest one: Can you not just read all the data into memory and then perform the computations you want? For example: $ cat tmp.csv Temp,Humidity 23,85 25,87 26,89 23,90 24,81 24,80 $ cat tmp.py #!/usr/bin/env python import csv with open('tmp.csv', 'rb') as f: reader = csv.DictReader(f) data = [] for row in reader: row = dict((k, float(v)) for k, v in row.items()) data.append(row) maxtemp = max(row['Temp'] for row in data) mintemp = min(row['Temp'] for row in data) meanhumidity = sum(row['Humidity'] for row in data) / len(data) print('max temp is: %d' % maxtemp) print('min temp is: %d' % mintemp) print('mean humidity is: %f' % meanhumidity) $ ./tmp.py max temp is: 26 min temp is: 23 mean humidity is: 85.333333 This approach can also be extended to the case where you don't read all the data into memory. Oscar From selbyrowleycannon at ymail.com Wed Nov 14 18:52:03 2012 From: selbyrowleycannon at ymail.com (Selby Rowley Cannon) Date: Wed, 14 Nov 2012 17:52:03 +0000 Subject: [Tutor] LCM Message-ID: <50A3DA43.3000600@ymail.com> Hey, I've been trying to write a function to find the Lowest Common Multiple of two numbers, but it isn't working and I've kinda hit a dead end on the thought-process end of things. Anyone mind looking at it, and tell me what's wrong? (I hop you don't think it's too long to put in an email) Code: def lowestCommonMultiple(a, b, amount): #k float(amount) if a == b: print 'You cannot find the LCM of the same number twice.' else: numbersList = list(range(amount)) aMultiples = [] bMultiples = [] for aNumber in numbersList: aMultiples.append(a*aNumber) for bNumber in numbersList: bMultiples.append(b*bNumber) if aMultiples[1] == bMultiples[1]: print 'The LCM of ', a, ' and ', b, ' is ', aMultiple[1] From d at davea.name Wed Nov 14 19:27:28 2012 From: d at davea.name (Dave Angel) Date: Wed, 14 Nov 2012 13:27:28 -0500 Subject: [Tutor] LCM In-Reply-To: <50A3DA43.3000600@ymail.com> References: <50A3DA43.3000600@ymail.com> Message-ID: <50A3E290.4020606@davea.name> On 11/14/2012 12:52 PM, Selby Rowley Cannon wrote: > Hey, > > I've been trying to write a function to find the Lowest Common > Multiple of two numbers, but it isn't working and I've kinda hit a > dead end on the thought-process end of things. Anyone mind looking at > it, and tell me what's wrong? (I hop you don't think it's too long to > put in an email) > > Code: > > def lowestCommonMultiple(a, b, amount): #k > float(amount) > if a == b: > print 'You cannot find the LCM of the same number twice.' > else: > numbersList = list(range(amount)) > aMultiples = [] > bMultiples = [] > for aNumber in numbersList: > aMultiples.append(a*aNumber) > for bNumber in numbersList: > bMultiples.append(b*bNumber) > if aMultiples[1] == bMultiples[1]: > print 'The LCM of ', a, ' and ', b, ' is ', aMultiple[1] Which are you interested in, finding what's wrong with the code, or a simpler way to actually find an LCM ? Is this an assignment, or just part of a bigger program you're writing? -- DaveA From selbyrowleycannon at ymail.com Wed Nov 14 19:34:17 2012 From: selbyrowleycannon at ymail.com (Selby Rowley Cannon) Date: Wed, 14 Nov 2012 18:34:17 +0000 Subject: [Tutor] LCM In-Reply-To: <50A3E290.4020606@davea.name> References: <50A3DA43.3000600@ymail.com> <50A3E290.4020606@davea.name> Message-ID: <50A3E429.9080803@ymail.com> On 14/11/12 18:27, Dave Angel wrote: > On 11/14/2012 12:52 PM, Selby Rowley Cannon wrote: >> Hey, >> >> I've been trying to write a function to find the Lowest Common >> Multiple of two numbers, but it isn't working and I've kinda hit a >> dead end on the thought-process end of things. Anyone mind looking at >> it, and tell me what's wrong? (I hop you don't think it's too long to >> put in an email) >> >> Code: >> >> def lowestCommonMultiple(a, b, amount): #k >> float(amount) >> if a == b: >> print 'You cannot find the LCM of the same number twice.' >> else: >> numbersList = list(range(amount)) >> aMultiples = [] >> bMultiples = [] >> for aNumber in numbersList: >> aMultiples.append(a*aNumber) >> for bNumber in numbersList: >> bMultiples.append(b*bNumber) >> if aMultiples[1] == bMultiples[1]: >> print 'The LCM of ', a, ' and ', b, ' is ', aMultiple[1] > Which are you interested in, finding what's wrong with the code, or a > simpler way to actually find an LCM ? > > Is this an assignment, or just part of a bigger program you're writing? > a.) Finding what's wrong with the code; b.) Part of a bigger program. From d at davea.name Wed Nov 14 19:58:40 2012 From: d at davea.name (Dave Angel) Date: Wed, 14 Nov 2012 13:58:40 -0500 Subject: [Tutor] LCM In-Reply-To: <50A3E429.9080803@ymail.com> References: <50A3DA43.3000600@ymail.com> <50A3E290.4020606@davea.name> <50A3E429.9080803@ymail.com> Message-ID: <50A3E9E0.9090204@davea.name> On 11/14/2012 01:34 PM, Selby Rowley Cannon wrote: > On 14/11/12 18:27, Dave Angel wrote: >> On 11/14/2012 12:52 PM, Selby Rowley Cannon wrote: >>> Hey, >>> Tell us what version of Python you're targeting. I'm going to assume 2.x, since you have print without parens. >>> I've been trying to write a function to find the Lowest Common >>> Multiple of two numbers, but it isn't working and I've kinda hit a >>> dead end on the thought-process end of things. Anyone mind looking at >>> it, and tell me what's wrong? (I hop you don't think it's too long to >>> put in an email) >>> >>> Code: >>> >>> def lowestCommonMultiple(a, b, amount): #k Why would you require the caller to specify the "amount" ? It's easier for you to calculate the two ranges below, as needed. >>> float(amount) This statement does nothing, which is good, since range doesn't work on floats. >>> if a == b: >>> print 'You cannot find the LCM of the same number twice.' here you should just return a >>> else: >>> numbersList = list(range(amount)) In Python 2.x, range already returns a list. Besides, you'd be better off with a sequence, so I'd use xrange. >>> aMultiples = [] >>> bMultiples = [] >>> for aNumber in numbersList: >>> aMultiples.append(a*aNumber) >>> for bNumber in numbersList: >>> bMultiples.append(b*bNumber) >>> if aMultiples[1] == bMultiples[1]: This will never be true, since lhs is 2*a, and rhs is 2*b, and a != b What you really need is some form of loop, which compares every item in the first list to every item in the second, returning the lowest number that's in both. Try something like: for item in aMultiples: if item in bMultiples: return item >>> print 'The LCM of ', a, ' and ', b, ' is ', aMultiple[1] It's generally better to return a calculated result, and print it separately, than always to print it. >> Which are you interested in, finding what's wrong with the code, or a >> simpler way to actually find an LCM ? >> >> Is this an assignment, or just part of a bigger program you're writing? >> > a.) Finding what's wrong with the code; > b.) Part of a bigger program. > > This algorithm is fine for small numbers, but the loop you'll have to write at the end is going to be very slow for large ones. It'll also use up lots of memory for those lists. You could speed it up a tiny bit by using different ranges for the two lists. After all the first list needn't have more than b items in it, and the second needn't have more than a items in it. You could cut the memory usage a lot by making the first list simply an xrange. The second, though, has to be traversed multiple times, so you presumably need a list. But a set would be MUCH faster. Anyway, if all you care about is the result, then use Euclid's method, and the % operator to calculate the gcd. A few loops around, and even pretty large numbers will crumble. Then the lcm is simply the product of a and b, divided by the gcd of a and b. The heart of such a gcd loop is something like: while b > 0: a, b = b, a%b -- DaveA From eryksun at gmail.com Wed Nov 14 20:13:43 2012 From: eryksun at gmail.com (eryksun) Date: Wed, 14 Nov 2012 14:13:43 -0500 Subject: [Tutor] LCM In-Reply-To: <50A3DA43.3000600@ymail.com> References: <50A3DA43.3000600@ymail.com> Message-ID: On Wed, Nov 14, 2012 at 12:52 PM, Selby Rowley Cannon wrote: > > I've been trying to write a function to find the Lowest Common Multiple > of two numbers, but it isn't working and I've kinda hit a dead end on the > thought-process end of things. Since the LCM is the smallest multiple of both numbers, you want to factor out what they have in common from one of them: x = x_unique * gcd y = y_unique * gcd lcm = x_unique * y_unique * gcd = (x / gcd) * y For example, say you have x = 21 = 3*7 and y = 35 = 5*7. The factor in common, i.e. the greatest common divisor (GCD), is 7. So the LCM is 105 = 3*5*7. I'm sure you can search for a good GCD algorithm with no problem since it's over 2,000 years old. But there's an "implementation" (it's not much work) in the fractions module: >>> 21 / fractions.gcd(21, 35) * 35 105 >>> print inspect.getsource(fractions.gcd) def gcd(a, b): """Calculate the Greatest Common Divisor of a and b. Unless b==0, the result will have the same sign as b (so that when b is divided by it, the result comes out positive). """ while b: a, b = b, a%b return a From marilyn at pythontrainer.com Wed Nov 14 21:10:38 2012 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Wed, 14 Nov 2012 12:10:38 -0800 (PST) Subject: [Tutor] unicode help In-Reply-To: <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> References: <51373.67.169.189.143.1306616764.squirrel@mail.tigertech.net> <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> Message-ID: <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> Hi, Last year, I was helped so that this ran nicely on my 2.6: #! /usr/bin/env python # -*- coding: utf-8 -*- # necessary for python not to complain about "?" symbol = unichr(165) print unicode(symbol) --- end of code --- But, now on my 2.7, and on 2.6 when I tried reinstalling it, I get: bash-3.2$ ./uni_test.py ./uni_test.py Traceback (most recent call last): File "./uni_test.py", line 6, in print unicode(symbol) UnicodeEncodeError: 'ascii' codec can't encode character u'\xa5' in position 0: ordinal not in range(128) bash-3.2$ Can anyone please help? It says 'ascii' codec? Shouldn't it be seeing 'utf-8'? I can't imagine it matters but I'm on an imac now and before I was on Ubuntu. Thank you, Marilyn Davis On Sat, May 28, 2011 2:17 pm, Marilyn Davis wrote: > Thank you Martin, > > > This: > > > #!/usr/bin/env python > # -*- coding: utf8 -*- > '''Unicode handling for 2.6. > ''' > [rest of module deleted] > > > produces an emacs warning: > > Warning (mule): Invalid coding system `utf8' is specified > for the current buffer/file by the :coding tag. It is highly recommended to > fix it before writing to a file. > > But, if I save anyway, and run, I get this: > > > ./uni.py > File "./uni.py", line 13 > SyntaxError: 'utf8' codec can't decode byte 0xa5 in position 0: unexpected > code byte > > but, on a hunch, I tried > > # -*- coding: utf-8 -*- > > > and emacs and python were very happy. Thank you thank you thank you. > > Now I can enjoy my Saturday. > > > Marilyn > > > > > > On Sat, May 28, 2011 3:00 pm, Martin A. Brown wrote: > > >> Hello there, >> >> >> >> : I'm still on Python 2.6 and I'm trying to work some unicode >> : handling. >> : >> : I've spent some hours on this snippet of code, trying to follow >> : PEP 0263, since the error tells me to see it. I've tried other >> : docs too and I am still clueless. >> >> >> >> OK, so this is PEP 0263. http://www.python.org/dev/peps/pep-0263/ >> >> >> >> Did you miss these lines? >> >> >> >> To define a source code encoding, a magic comment must >> be placed into the source files either as first or second line in the >> file, such as: >> >> Or was it the lack of an explicit example for UTF-8 in the PEP? >> >> >> >> Try adding a single line to your script, as the second line. That >> should make your script look like: >> >> #! /usr/bin/env python >> # -*- coding: utf8 -*- >> >> >> >> You might wonder why on earth you have to do this. The interpreter >> cannot safely assume that your editor (any arbitrary text editor) knows >> how to create/save anything other than ASCII without this (slightly >> hackish) hint. >> >> Good luck, >> >> >> >> -Martin >> >> >> >> -- >> Martin A. Brown >> http://linux-ip.net/ From d at davea.name Wed Nov 14 21:34:35 2012 From: d at davea.name (Dave Angel) Date: Wed, 14 Nov 2012 15:34:35 -0500 Subject: [Tutor] unicode help In-Reply-To: <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> References: <51373.67.169.189.143.1306616764.squirrel@mail.tigertech.net> <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> Message-ID: <50A4005B.8030509@davea.name> On 11/14/2012 03:10 PM, Marilyn Davis wrote: > Hi, > > Last year, I was helped so that this ran nicely on my 2.6: > > #! /usr/bin/env python > # -*- coding: utf-8 -*- > # necessary for python not to complain about "?" > > symbol = unichr(165) > print unicode(symbol) > > --- end of code --- > > But, now on my 2.7, and on 2.6 when I tried reinstalling it, I get: > > bash-3.2$ ./uni_test.py > ./uni_test.py > Traceback (most recent call last): > File "./uni_test.py", line 6, in > print unicode(symbol) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xa5' in > position 0: ordinal not in range(128) > bash-3.2$ > > Can anyone please help? It says 'ascii' codec? Shouldn't it be seeing > 'utf-8'? > > I can't imagine it matters but I'm on an imac now and before I was on Ubuntu. > > Thank you, > > Marilyn Davis > > > > You top-posted your message. If you need to quote something, please put your new text after what you're quoting. Try the following in your 2.7 interpreter: >>> import sys >>> print sys.stdout.encoding UTF-8 If you don't see UTF-8, then there's a discrepancy between what you think the terminal is doing, and what Python thinks. Somebody familiar with the Mac might be able to tell you how to fix it right, but you could try sys.stdout.encoding = "UTF-8" and see if it changes your symptoms. -- DaveA From marilyn at pythontrainer.com Wed Nov 14 22:07:36 2012 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Wed, 14 Nov 2012 13:07:36 -0800 (PST) Subject: [Tutor] unicode help In-Reply-To: <50A4005B.8030509@davea.name> References: <51373.67.169.189.143.1306616764.squirrel@mail.tigertech.net> <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> <50A4005B.8030509@davea.name> Message-ID: <50959.50.131.112.243.1352927256.squirrel@mail.tigertech.net> Thank you, Dave, for looking at my problem, and for correcting me on my top posting. See below: On Wed, November 14, 2012 12:34 pm, Dave Angel wrote: > On 11/14/2012 03:10 PM, Marilyn Davis wrote: > >> Hi, >> >> >> Last year, I was helped so that this ran nicely on my 2.6: >> >> >> #! /usr/bin/env python >> # -*- coding: utf-8 -*- >> # necessary for python not to complain about "?" >> >> >> symbol = unichr(165) print unicode(symbol) >> >> --- end of code --- >> >> >> But, now on my 2.7, and on 2.6 when I tried reinstalling it, I get: >> >> >> bash-3.2$ ./uni_test.py ./uni_test.py >> Traceback (most recent call last): >> File "./uni_test.py", line 6, in >> print unicode(symbol) UnicodeEncodeError: 'ascii' codec can't encode >> character u'\xa5' in position 0: ordinal not in range(128) bash-3.2$ >> >> Can anyone please help? It says 'ascii' codec? Shouldn't it be seeing >> 'utf-8'? >> >> >> I can't imagine it matters but I'm on an imac now and before I was on >> Ubuntu. >> >> >> Thank you, >> >> >> Marilyn Davis >> >> >> >> >> > > You top-posted your message. If you need to quote something, please put > your new text after what you're quoting. > > Try the following in your 2.7 interpreter: > > >>>> import sys print sys.stdout.encoding > UTF-8 > > > If you don't see UTF-8, then there's a discrepancy between what you > think the terminal is doing, and what Python thinks. You're right, I get this: bash-3.2$ python Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys import sys >>> print sys.stdout.encoding print sys.stdout.encoding US-ASCII >>> > > Somebody familiar with the Mac might be able to tell you how to fix it > right, but you could try sys.stdout.encoding = "UTF-8" > > and see if it changes your symptoms. and, your good idea didn't work: >>> sys.stdout.encoding="UTF-8" sys.stdout.encoding="UTF-8" Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute >>> Goodness! I didn't expect it to be a Mac thing. So, on a Windows machine, running Python 2.6.6, sys.stdout.encoding is 'cp1252', yet the code runs fine. On Ubuntu with 2.7, it's 'UTF-8' and it runs just fine. I find this most mysterious. Thank you for any help to get it running on my Mac. Marilyn > > -- > > > DaveA From marilyn at pythontrainer.com Wed Nov 14 22:23:59 2012 From: marilyn at pythontrainer.com (Marilyn Davis) Date: Wed, 14 Nov 2012 13:23:59 -0800 (PST) Subject: [Tutor] unicode help In-Reply-To: <50959.50.131.112.243.1352927256.squirrel@mail.tigertech.net> References: <51373.67.169.189.143.1306616764.squirrel@mail.tigertech.net> <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> <50A4005B.8030509@davea.name> <50959.50.131.112.243.1352927256.squirrel@mail.tigertech.net> Message-ID: <51051.50.131.112.243.1352928239.squirrel@mail.tigertech.net> On Wed, November 14, 2012 1:07 pm, Marilyn Davis wrote: > Thank you, Dave, for looking at my problem, and for correcting me on my > top posting. > > See below: > > > On Wed, November 14, 2012 12:34 pm, Dave Angel wrote: > > >> On 11/14/2012 03:10 PM, Marilyn Davis wrote: >> >> >>> Hi, >>> >>> >>> >>> Last year, I was helped so that this ran nicely on my 2.6: >>> >>> >>> >>> #! /usr/bin/env python >>> # -*- coding: utf-8 -*- >>> # necessary for python not to complain about "?" >>> >>> >>> >>> symbol = unichr(165) print unicode(symbol) >>> >>> --- end of code --- >>> >>> >>> >>> But, now on my 2.7, and on 2.6 when I tried reinstalling it, I get: >>> >>> >>> >>> bash-3.2$ ./uni_test.py ./uni_test.py Traceback (most recent call >>> last): >>> File "./uni_test.py", line 6, in >>> print unicode(symbol) UnicodeEncodeError: 'ascii' codec can't encode >>> character u'\xa5' in position 0: ordinal not in range(128) bash-3.2$ >>> >>> Can anyone please help? It says 'ascii' codec? Shouldn't it be >>> seeing 'utf-8'? >>> >>> >>> >>> I can't imagine it matters but I'm on an imac now and before I was on >>> Ubuntu. >>> >>> >>> >>> Thank you, >>> >>> >>> >>> Marilyn Davis >>> >>> >>> >>> >>> >>> >> >> You top-posted your message. If you need to quote something, please >> put your new text after what you're quoting. >> >> Try the following in your 2.7 interpreter: >> >> >> >>>>> import sys print sys.stdout.encoding >> UTF-8 >> >> >> >> If you don't see UTF-8, then there's a discrepancy between what you >> think the terminal is doing, and what Python thinks. > > You're right, I get this: > > > bash-3.2$ python Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43) > [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys > import sys >>>> print sys.stdout.encoding > print sys.stdout.encoding US-ASCII > >>>> > > >> >> Somebody familiar with the Mac might be able to tell you how to fix it >> right, but you could try sys.stdout.encoding = "UTF-8" >> >> and see if it changes your symptoms. > > and, your good idea didn't work: > >>>> sys.stdout.encoding="UTF-8" > sys.stdout.encoding="UTF-8" Traceback (most recent call last): > File "", line 1, in > TypeError: readonly attribute > >>>> > > Goodness! I didn't expect it to be a Mac thing. > > > So, on a Windows machine, running Python 2.6.6, sys.stdout.encoding is > 'cp1252', yet the code runs fine. > > > On Ubuntu with 2.7, it's 'UTF-8' and it runs just fine. > > > I find this most mysterious. > > > Thank you for any help to get it running on my Mac. > > > Marilyn > I found this site: http://hints.macworld.com/article.php?story=20100713130450549 and that fixes it. I would never guessed that! Marilyn From d at davea.name Wed Nov 14 23:08:31 2012 From: d at davea.name (Dave Angel) Date: Wed, 14 Nov 2012 17:08:31 -0500 Subject: [Tutor] unicode help In-Reply-To: <50959.50.131.112.243.1352927256.squirrel@mail.tigertech.net> References: <51373.67.169.189.143.1306616764.squirrel@mail.tigertech.net> <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> <50A4005B.8030509@davea.name> <50959.50.131.112.243.1352927256.squirrel@mail.tigertech.net> Message-ID: <50A4165F.2060807@davea.name> On 11/14/2012 04:07 PM, Marilyn Davis wrote: > > > Goodness! I didn't expect it to be a Mac thing. > > So, on a Windows machine, running Python 2.6.6, sys.stdout.encoding is > 'cp1252', yet the code runs fine. > > On Ubuntu with 2.7, it's 'UTF-8' and it runs just fine. > > I find this most mysterious. > > Thank you for any help to get it running on my Mac. > > To resolve something like this, I'd start searching the internet (and especially the python.org site) for a string like: python sys.stdout.encoding https://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/ According to this page, the encoding is chosen by the environment variable: LC_CTYPE set LC_CTYPE=en_GB.utf-8 I have no idea if that's correct, or always correct, but it could be worth experimenting. (Later note: I think this affects more than just the terminal, so I'd skip it) In the meantime, you posted a link to http://hints.macworld.com/article.php?story=20100713130450549 which suggests two different environment variables: PYTHONIOENCODING and LC-CTYPE Looking at the python.org site is presumably more authoritative. See http://docs.python.org/2/whatsnew/2.6.html?highlight=pythonioencoding which says """ The encoding used for standard input, output, and standard error can be specified by setting the PYTHONIOENCODING environment variable before running the interpreter. The value should be a string in the form or :. The /encoding/ part specifies the encoding?s name, e.g. utf-8 or latin-1; the optional /errorhandler/ part specifies what to do with characters that can?t be handled by the encoding, and should be one of ?error?, ?ignore?, or ?replace?. (Contributed by Martin von Loewis.)""" Also: http://docs.python.org/2/using/cmdline.html?highlight=pythonioencoding#PYTHONIOENCODING Anyway, just realize that this does NOT change the terminal. If it's not really utf-8, you'll sometimes get garbage characters. But at least you shouldn't get the encoding errors. The *right* answer I figure would be to experiment to find out what the terminal on your Mac actually uses, and use that in your environment variable. -- DaveA From sander.sweers at gmail.com Wed Nov 14 23:09:40 2012 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 14 Nov 2012 23:09:40 +0100 Subject: [Tutor] unicode help In-Reply-To: <51051.50.131.112.243.1352928239.squirrel@mail.tigertech.net> References: <51373.67.169.189.143.1306616764.squirrel@mail.tigertech.net> <58968.67.169.189.143.1306621024.squirrel@mail.tigertech.net> <50083.50.131.112.243.1352923838.squirrel@mail.tigertech.net> <50A4005B.8030509@davea.name> <50959.50.131.112.243.1352927256.squirrel@mail.tigertech.net> <51051.50.131.112.243.1352928239.squirrel@mail.tigertech.net> Message-ID: <1352930980.2215.2.camel@infirit.lan> Marilyn Davis schreef op wo 14-11-2012 om 13:23 [-0800]: > I found this site: > http://hints.macworld.com/article.php?story=20100713130450549 > > and that fixes it. Short answer: It is not a fix but a workaround. Try: print symbol.encode('utf-8') Longer answer: It is not really a fix, it is a workaround for the implicit encode/decode python does. Setting this environment variable will make the errors go away for *you* but what about the other people running the code. What you are seeing is the *implicit* encode from a unicode string to a byte string using sys.getdefaultencoding. What you need to do is encode your *unicode* string to a *byte* string by using encode() method. You should watch/read http://nedbatchelder.com/text/unipain.html and see how to fix this properly. This quick interactive session shows how this error is properly solved. $ python Python 2.7.3 (default, Sep 22 2012, 18:13:33) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding 'ascii' >>> unicode_symbol = unichr(165) >>> print unicode_symbol Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xa5' in position 0: ordinal not in range(128) >>> byte_symbol = unicode_symbol.encode('utf-8') >>> print byte_symbol ? I do not use macosx but I suspect it will support UTF-8, however if not you need to find an encoding that is supported and has your character. This can be quite confusing so I really suggest strongly to watch Ned's talk ;-). Greets Sander From awesome.me.dm at outlook.com Thu Nov 15 03:04:48 2012 From: awesome.me.dm at outlook.com (David Martins) Date: Thu, 15 Nov 2012 13:04:48 +1100 Subject: [Tutor] data analysis with python In-Reply-To: References: , Message-ID: Thanks again for all the useful tips. I settled with R for now. As Oscar said, the dataset is not massive so I could have done it using a dictionary. However some of the more frequent requests will include to find data during certain times during certain days, for specific months or weekdays vs. weekends, etc. I believe this would mean that I would have needed some indexing (which made me think of using databases in the first place). All of this seems to be quite easy in R as well # The weather[3] column stores the string for the weekday wkdays = which(weather[3] !="Sat"& weather[3] !="Sun") I guess that would be easy enough with a list comprehension in python too. Binning looks like this: heatcut = cut(as.matrix(lib[15]),breaks=c(0,max(lib[15])*0.1,max(lib[15])*0.2,max(lib[15])*0.3,max(lib[15])*0.4,max(lib[15])*0.5,max(lib[15])*0.6,max(lib[15])*0.7,max(lib[15])*0.8,max(lib[15])*0.9,max(lib[15])*1.0),labels=c('0%','10%','20%','30%','40%','50%','60%','80%','90%','100%')) This can be added to a function. So the call will look something like bin_me(lib[15], breaks=default, labels=default). To get one bin in sqlite I wrote this for a sqlite db (not sure if there is an easier way): select count(Heating_plant_sensible_load) from LibraryMainwhere Heating_plant_sensible_load > (select max(Heating_plant_sensible_load)*0.3 from LibraryMain ANDHeating_plant_sensible_load < (select max(Heating_plant_sensible_load)*0.4 from LibraryMain; Indexing for certain times, using my approach, would add even more lines; on top of this, I believe you would have to add this either to a view or a new table... So are seems to be clearer and more concise compared to sql/sqlite (at least for me). On top of that it provides the possibility to do additional analysis later on for specific cases. That it can connect with python is another plus. Thanks again for everyones ideasdm > Date: Wed, 14 Nov 2012 13:59:25 +0000 > Subject: Re: [Tutor] data analysis with python > From: oscar.j.benjamin at gmail.com > To: awesome.me.dm at outlook.com > CC: tutor at python.org > > On 14 November 2012 03:17, David Martins wrote: > > Hi All > > > > I'm trying to use python for analysing data from building energy simulations > > and was wondering whether there is way to do this without using anything sql > > like. > > There are many ways to do this. > > > > > The simulations are typically run for a full year, every hour, i.e. there > > are 8760 rows and about 100+ variables such as external air temperature, > > internal air temperature, humidity, heating load, ... making roughly a > > million data points. I've got the data in a csv file and also managed to > > write it in a sqlite db. > > This dataset is not so big that you can't just load it all into memory. > > > > > I would like to make requests like the following: > > > > Show the number of hours the aircon is running at 10%, 20%, ..., 100% > > Show me the average, min, max air temperature, humidity, solar gains,.... > > when the aircon is running at 10%, 20%,...,100% > > > > Eventually I'd also like to generate an automated html or pdf report with > > graphs. Creating graphs is actually somewhat essential. > > Do you mean graphs or plots? I would use matplotlib for plotting. It > can automatically generate image files of plots. There are also ways > to generate output for visualising graphs but I guess that's not what > you mean. Probably I would create a pdf report using latex and > matplotlib but that's not the only way. > http://en.wikipedia.org/wiki/Graph_(mathematics) > http://en.wikipedia.org/wiki/Plot_(graphics) > > > I tried sql and find it horrible, error prone, too much to write, the logic > > somehow seems to work different than my brain and I couldn't find > > particulary good documentation (particulary the documentation of the api is > > terrible, in my humble opinion). I heard about zope db which might be an > > alternative. Would you mind pointing me towards an appropriate way to solve > > my problem? Is there a way for me to avoid having to learn sql or am I > > doomed? > > There are many ways to avoid learning SQL. I'll suggest the simplest > one: Can you not just read all the data into memory and then perform > the computations you want? > > For example: > > $ cat tmp.csv > Temp,Humidity > 23,85 > 25,87 > 26,89 > 23,90 > 24,81 > 24,80 > > $ cat tmp.py > #!/usr/bin/env python > > import csv > > with open('tmp.csv', 'rb') as f: > reader = csv.DictReader(f) > data = [] > for row in reader: > row = dict((k, float(v)) for k, v in row.items()) > data.append(row) > > maxtemp = max(row['Temp'] for row in data) > mintemp = min(row['Temp'] for row in data) > meanhumidity = sum(row['Humidity'] for row in data) / len(data) > > print('max temp is: %d' % maxtemp) > print('min temp is: %d' % mintemp) > print('mean humidity is: %f' % meanhumidity) > > $ ./tmp.py > max temp is: 26 > min temp is: 23 > mean humidity is: 85.333333 > > This approach can also be extended to the case where you don't read > all the data into memory. > > > Oscar -------------- next part -------------- An HTML attachment was scrubbed... URL: From matheusoares at poli.ufrj.br Thu Nov 15 03:32:45 2012 From: matheusoares at poli.ufrj.br (Matheus Soares da Silva) Date: Thu, 15 Nov 2012 00:32:45 -0200 Subject: [Tutor] Tkinter, how to retrieve information about an object on canvas Message-ID: Hello, I would like to be able to get information from a Tkinter canvas object. (color, width, tags, root points, etc), I wrote the following function that, with a canvas bind, returns me the widget that has been clicked on, the widget is returned as a tuple by the find_overlapping method. # detecting click def Hasclicked(e): global obj global lastClick lastClick = [e.x, e.y] obj = e.widget.find_overlapping(e.x, e.y, e.x, e.y) So, there's any method I can use on 'obj' to get the attributes? (Tkinter Documentation: http://www.tkdocs.com/tutorial/index.html) -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Nov 15 09:48:56 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Nov 2012 08:48:56 +0000 Subject: [Tutor] Tkinter, how to retrieve information about an object on canvas In-Reply-To: References: Message-ID: On 15/11/12 02:32, Matheus Soares da Silva wrote: > > Hello, I would like to be able to get information from a Tkinter canvas > object. (color, width, tags, root points, etc), > > I wrote the following function that, with a canvas bind, returns me > the widget that has been clicked on, the widget is returned as a tuple > by the find_overlapping method. > > # detecting click > def Hasclicked(e): > global obj > global lastClick > lastClick = [e.x, e.y] > obj = e.widget.find_overlapping(e.x, e.y, e.x, e.y) > > So, there's any method I can use on 'obj' to get the attributes? Do you want to get the attributes of the object within the canvas or of the canvas itself? I'm not quite clear from your description? In either case you can access an attribute of an object using standard Tkinter attribute access mechanism: obj['attributeName'] >>> import Tkinter as tk >>> top = Tk() >>> top = tk.Tk() >>> l = tk.Label(top,text='hello') >>> l.pack() >>> l['text'] 'hello' >>> HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From glez_b at comunidad.unam.mx Thu Nov 15 10:20:50 2012 From: glez_b at comunidad.unam.mx (Boris Vladimir Comi) Date: Thu, 15 Nov 2012 09:20:50 +0000 Subject: [Tutor] Plot multiple lines using python / basemap Message-ID: <9D6FC4172EA6B64B9044B9B8196DBB250DF7AB63@BL2PRD0710MB373.namprd07.prod.outlook.com> Hi all: I have begun to learn about python / matplolib / basemap and really need some help. My data is in an Excel workbook with the following structure: Evento Fecha Latitud Longitud Hora (UTC) 1 02/mayo 19,7 -95,2 0045 19,3 -95.3 0115 19,8 -95,6 0145 19,9 -96,6 0215 2 03/mayo 20,2 -99,6 0815 21,5 -99,8 0845 22,5 -99,9 0915 23,5 -100,0 0945 3 15/mayo 21,3 -118,9 2215 21,5 -118,7 2245 22,8 -120,3 2315 . . . . . . . . . . . . . . . How to open excel file in python? I would like to plot multiple line joining the positions of each of the events, it is possible to do this? Have any idea how to do it? The idea is to plot the trajectories on a particular region, for my case is Mexico. From __peter__ at web.de Thu Nov 15 10:37:12 2012 From: __peter__ at web.de (Peter Otten) Date: Thu, 15 Nov 2012 10:37:12 +0100 Subject: [Tutor] Tkinter, how to retrieve information about an object on canvas References: Message-ID: Matheus Soares da Silva wrote: > Hello, I would like to be able to get information from a Tkinter canvas > object. (color, width, tags, root points, etc), > > I wrote the following function that, with a canvas bind, returns me the > widget that has been clicked on, the widget is returned as a tuple by the > find_overlapping method. > > # detecting click > def Hasclicked(e): > global obj > global lastClick > lastClick = [e.x, e.y] > obj = e.widget.find_overlapping(e.x, e.y, e.x, e.y) > > So, there's any method I can use on 'obj' to get the attributes? obj is a tuple of ids. You can use canvas.itemcget(id, attribute) to explore the properties of the underlying objects To get (for example) their fill-color: for id in e.widget.find_overlapping(e.x, e.y, e.x, e.y): print canvas.itemcget(id, "fill") A complete example: from __future__ import division import Tkinter as tk from math import cos, sin, pi WIDTH = 640 HEIGHT = 480 root = tk.Tk() canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT) canvas.pack() var = tk.StringVar() label = tk.Label(root, textvariable=var) label.pack() def canvas_click(event): x, y = event.x, event.y ids = canvas.find_overlapping(x, y, x, y) clicked_colors = ", ".join(canvas.itemcget(id, "fill") for id in ids) var.set(clicked_colors) RADIUS = 100 R = 80 CX = WIDTH // 2 CY = HEIGHT // 2 phi = pi/2 # 90 degree for color in "red", "green", "blue": x = int(CX + R*cos(phi)) y = int(CY - R*sin(phi)) phi += pi*2/3 # 120 degree canvas.create_oval(x-RADIUS, y-RADIUS, x+RADIUS, y+RADIUS, fill=color) canvas.bind("", canvas_click) root.mainloop() From d at davea.name Thu Nov 15 11:29:19 2012 From: d at davea.name (Dave Angel) Date: Thu, 15 Nov 2012 05:29:19 -0500 Subject: [Tutor] Plot multiple lines using python / basemap In-Reply-To: <9D6FC4172EA6B64B9044B9B8196DBB250DF7AB63@BL2PRD0710MB373.namprd07.prod.outlook.com> References: <9D6FC4172EA6B64B9044B9B8196DBB250DF7AB63@BL2PRD0710MB373.namprd07.prod.outlook.com> Message-ID: <50A4C3FF.1020701@davea.name> On 11/15/2012 04:20 AM, Boris Vladimir Comi wrote: > > Hi all: > > I have begun to learn about python / matplolib / basemap and really need some help. > > My data is in an Excel workbook with the following structure: > > Evento Fecha Latitud Longitud Hora (UTC) > 1 02/mayo 19,7 -95,2 0045 > 19,3 -95.3 0115 > 19,8 -95,6 0145 > 19,9 -96,6 0215 > > > 2 03/mayo 20,2 -99,6 0815 > 21,5 -99,8 0845 > 22,5 -99,9 0915 > 23,5 -100,0 0945 > > 3 15/mayo 21,3 -118,9 2215 > 21,5 -118,7 2245 > 22,8 -120,3 2315 > > . . . . . > . . . . . > . . . . . > > > > > > > How to open excel file in python? >From Excel, save the file as a csv file, rather than a proprietary format. Then, within Python program, use the csv module, http://docs.python.org/2/library/csv.html The essential parts: import csv def getdata(filename): with open(filename, "rb") as infile: csvreader = csv.reader(infile, delimiter ="\t", quotechar='"') for row in csvreader: ---- process row ---- where row comes back as a list of items. You may have to play with the delimiter and quotechar, as I don't use Excel itself, to know what it defaults to. But a csv file is a text file, so it should be pretty obvious if you just look at the file with a text editor or viewer, what the separator and quote characters are. The quote character generally only matters if some field has an embedded separator or newline in it. > > I would like to plot multiple line joining the positions of each of the events, it is possible to do this? Have any idea how to do it? Try matplotlib: http://pypi.python.org/pypi/matplotlib/1.1.0 It depends on numpy: http://numpy.scipy.org/ > > The idea is to plot the trajectories on a particular region, for my case is Mexico. > -- DaveA From breamoreboy at yahoo.co.uk Thu Nov 15 11:58:42 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 15 Nov 2012 10:58:42 +0000 Subject: [Tutor] Plot multiple lines using python / basemap In-Reply-To: <9D6FC4172EA6B64B9044B9B8196DBB250DF7AB63@BL2PRD0710MB373.namprd07.prod.outlook.com> References: <9D6FC4172EA6B64B9044B9B8196DBB250DF7AB63@BL2PRD0710MB373.namprd07.prod.outlook.com> Message-ID: On 15/11/2012 09:20, Boris Vladimir Comi wrote: > > > Hi all: > > I have begun to learn about python / matplolib / basemap and really need some help. > > How to open excel file in python? As Dave Angel has suggested save your data in csv format or use this http://www.python-excel.org/ > > I would like to plot multiple line joining the positions of each of the events, it is possible to do this? Have any idea how to do it? The matplotlib documentation is here http://matplotlib.org/contents.html and it's superb. As an added bonus matplotlib 1.2.0 has just been released and it supports Python 3, yee haa :) You might consider using matplotlib with IPython see http://ipython.org/, together they make a very powerful working environment. > > The idea is to plot the trajectories on a particular region, for my case is Mexico. > -- Cheers. Mark Lawrence. From sulinet at postafiok.hu Thu Nov 15 12:00:09 2012 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Thu, 15 Nov 2012 12:00:09 +0100 Subject: [Tutor] PostreSQL Message-ID: Hi folks, Here are to listings of Python interfaces to PostgreSQL: Postgres wiki: http://wiki.postgresql.org/wiki/Python Python wiki: http://wiki.python.org/moin/PostgreSQL I have Python 3.2.3. Does anybody have experiences with these modules? Which is worth to use? Any point of view to compare them? Thanks, P?ter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sulinet at postafiok.hu Thu Nov 15 12:12:45 2012 From: sulinet at postafiok.hu (=?ISO-8859-1?Q?V=E1las_P=E9ter?=) Date: Thu, 15 Nov 2012 12:12:45 +0100 Subject: [Tutor] PostreSQL In-Reply-To: References: Message-ID: Two listings, of course. :-) I failed to tell that my PG version is "PostgreSQL 8.1.2" (and my client uses Windows 7, if this has relevance). 2012/11/15 V?las P?ter > Hi folks, > > Here are to listings of Python interfaces to PostgreSQL: > Postgres wiki: http://wiki.postgresql.org/wiki/Python > Python wiki: http://wiki.python.org/moin/PostgreSQL > > I have Python 3.2.3. > Does anybody have experiences with these modules? Which is worth to use? > Any point of view to compare them? > > Thanks, P?ter > -------------- next part -------------- An HTML attachment was scrubbed... URL: From matheusoares at poli.ufrj.br Thu Nov 15 16:13:15 2012 From: matheusoares at poli.ufrj.br (Matheus Soares da Silva) Date: Thu, 15 Nov 2012 13:13:15 -0200 Subject: [Tutor] Tkinter, how to retrieve information about an object on canvas In-Reply-To: References: Message-ID: 2012/11/15 Peter Otten <__peter__ at web.de> > Matheus Soares da Silva wrote: > > > Hello, I would like to be able to get information from a Tkinter canvas > > object. (color, width, tags, root points, etc), > > > > I wrote the following function that, with a canvas bind, returns me the > > widget that has been clicked on, the widget is returned as a tuple by the > > find_overlapping method. > > > > # detecting click > > def Hasclicked(e): > > global obj > > global lastClick > > lastClick = [e.x, e.y] > > obj = e.widget.find_overlapping(e.x, e.y, e.x, e.y) > > > > So, there's any method I can use on 'obj' to get the attributes? > > obj is a tuple of ids. You can use canvas.itemcget(id, attribute) to > explore > the properties of the underlying objects > > To get (for example) their fill-color: > > for id in e.widget.find_overlapping(e.x, e.y, e.x, e.y): > print canvas.itemcget(id, "fill") > > A complete example: > > from __future__ import division > import Tkinter as tk > from math import cos, sin, pi > > WIDTH = 640 > HEIGHT = 480 > > root = tk.Tk() > canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT) > canvas.pack() > > var = tk.StringVar() > label = tk.Label(root, textvariable=var) > label.pack() > > def canvas_click(event): > x, y = event.x, event.y > ids = canvas.find_overlapping(x, y, x, y) > clicked_colors = ", ".join(canvas.itemcget(id, "fill") for id in ids) > var.set(clicked_colors) > > RADIUS = 100 > R = 80 > CX = WIDTH // 2 > CY = HEIGHT // 2 > > phi = pi/2 # 90 degree > for color in "red", "green", "blue": > x = int(CX + R*cos(phi)) > y = int(CY - R*sin(phi)) > phi += pi*2/3 # 120 degree > > canvas.create_oval(x-RADIUS, y-RADIUS, x+RADIUS, y+RADIUS, fill=color) > > canvas.bind("", canvas_click) > root.mainloop() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thank you, just what I needed. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Thu Nov 15 22:21:39 2012 From: eire1130 at gmail.com (James Reynolds) Date: Thu, 15 Nov 2012 16:21:39 -0500 Subject: [Tutor] PostreSQL In-Reply-To: References: Message-ID: Psycopg2 is the driver for postgres. Not sure if it is py3k compliant On Nov 15, 2012 6:13 AM, "V?las P?ter" wrote: > Two listings, of course. :-) > I failed to tell that my PG version is "PostgreSQL 8.1.2" (and my client > uses Windows 7, if this has relevance). > > 2012/11/15 V?las P?ter > >> Hi folks, >> >> Here are to listings of Python interfaces to PostgreSQL: >> Postgres wiki: http://wiki.postgresql.org/wiki/Python >> Python wiki: http://wiki.python.org/moin/PostgreSQL >> >> I have Python 3.2.3. >> Does anybody have experiences with these modules? Which is worth to use? >> Any point of view to compare them? >> >> Thanks, P?ter >> > > > _______________________________________________ > 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 memilanuk at gmail.com Sat Nov 17 00:54:11 2012 From: memilanuk at gmail.com (Monte Milanuk) Date: Fri, 16 Nov 2012 15:54:11 -0800 Subject: [Tutor] data analysis with python In-Reply-To: References: Message-ID: Hello David, I know you said you settled on R... but just in case you are still interested in possible Python options, I think this book might well cover about everything you were looking for using numpy, scipy and pandas. Python for Data Analysis http://shop.oreilly.com/product/0636920023784.do Monte -------------- next part -------------- An HTML attachment was scrubbed... URL: From axel.wegen at gmail.com Thu Nov 15 05:44:13 2012 From: axel.wegen at gmail.com (Axel Wegen) Date: Thu, 15 Nov 2012 05:44:13 +0100 Subject: [Tutor] Tkinter, how to retrieve information about an object on canvas In-Reply-To: (Matheus Soares da Silva's message of "Thu, 15 Nov 2012 00:32:45 -0200") References: Message-ID: <87pq3f5vc2.fsf@gmail.com> Matheus Soares da Silva writes: > Hello, I would like to be able to get information from a Tkinter > canvas object. (color, width, tags, root points, etc), You can get the information of an object on the canvas by passing its id to certain canvas methods like itemconfigure: >>> c = Canvas() >>> c.pack() >>> c.create_rectangle(30,30,90,90,fill="black") 1 >>> c.itemconfigure(1) Should yield a dictionary containing the options of the rectangle. > the widget is returned as a tuple by the find_overlapping method. Utilising find_overlapping you will get a tuple of multiple object-ids. To get a single object you index into the tuple: >>> c.find_overlapping(31,31,33,33) (1,) >>> c.itemconfigure(c.find_overlapping(31,31,33,33)[0]) btw. there is also a tkinter specific mailing-list: tkinter-discuss at python.org -- Axel Wegen From dancingbush at gmail.com Tue Nov 13 09:49:34 2012 From: dancingbush at gmail.com (Ciaran Mooney) Date: Tue, 13 Nov 2012 08:49:34 +0000 Subject: [Tutor] Pygame problem with mac Message-ID: <9DC790DD-03F7-4352-BF04-0553C824BF51@gmail.com> Hi, Was hoping u could help me. I can't seem to download a version of pygame that is compatible with python 3.2 on my Mac powerbook with OS tiger. I only seem to he able to get pygame for python 2.7 which i have never used. Thanks Ciaran From ebalderston1 at gmail.com Sat Nov 10 20:48:32 2012 From: ebalderston1 at gmail.com (Elizabeth Balderston) Date: Sat, 10 Nov 2012 14:48:32 -0500 Subject: [Tutor] Adding a gifting option too basic shipping page Message-ID: Hi- I'm attempting to use Python in order to set up a basic shipping order page. After having figured out thee page along with email confirmation, I realized that I had forgotten a gift option that would automatically affect the price if checked. I have no idea how to add this feature to my program or if it will change the whole thing so I have to start from scratch. If you could help me with creating this, that would be amazing. Thank you so much, Liz -------------- next part -------------- An HTML attachment was scrubbed... URL: From turner15429 at gmail.com Fri Nov 16 18:28:51 2012 From: turner15429 at gmail.com (sillywilly98) Date: Fri, 16 Nov 2012 09:28:51 -0800 (PST) Subject: [Tutor] Quick question about definitions. Message-ID: <1353086931418-4996080.post@n6.nabble.com> I know this code is not fully debugged. I just cant see why 1 definition is wrong. Here is the code: # This program draws a robot. from turtle import * def draw_eyes(): # This function penup() color("purple") goto(-50, 200) pendown() begin_fill() circle(20) end_fill() penup() goto(50, 200) begin_fill() circle(20) end_fill(() def draw_nose(): # This function penup() color("orange") goto(0, 150) pendown() begin_fill() circle(20, steps=3) end_fill(() def draw_mouth(): # This function penup() color("pink" goto(-50, 100) pendown() begin_fill() forward(100) right(90) forward(20) right(90) forward(100) right(90) forward((20) right(90) end_fill() def draw_head(): # This function draw_eyes() draw_nose() draw_mouth() penup() color("blackk") goto(-100, 50 pendown() goto(100, 50) goto(100, 275) goto(-100, 275) gto(-100, 50) def draw_panel(): # This function penup() color("grey") width(4) goto(-75, 0) pendown() goto(75, 0) goto(75, -100) goto(-75, -100) goto(-75, 0) penup() clor("red") goto(-25, -50) pendown() circle25, steps=3) penup() color("green") goto(25, -50) pendown() rght(180) circle(25, steps=3) right(180) def draw_arm(): # This function pendown() color("black") width(2) right(90") forward(150) right(90) forward(25) color("red") begin_fill() circle(50) end_fill() color("black") forward(25) right(90) forward(150) right(90) forward(50) def draw_body(): # This function draw_panel() penup() color("black") width(1)) goto(-150, 50) pendown() goto(150, 50) goto(150, -250) goto(-150, -250) goto(-150, 50) draw_arm() penupp() goto(200, 50) draw_arm() draw_head() draw_body() exitonclick) -- View this message in context: http://python.6.n6.nabble.com/Quick-question-about-definitions-tp4996080.html Sent from the Python - tutor mailing list archive at Nabble.com. From unaiza.ahsan at gmail.com Fri Nov 16 18:40:22 2012 From: unaiza.ahsan at gmail.com (Unaiza Ahsan) Date: Fri, 16 Nov 2012 12:40:22 -0500 Subject: [Tutor] New to Python - simple question Message-ID: Hi all, I am following Jan Erik Solem's book "Programming Computer Vision with Python" and I'm just on the first chapter. The book asked us to create a file imtools.py and put down helpful functions there, which we can just call later. There is a function created for histogram equalization of images (called * histeq*), and saved in imtools.py. When I use this function and type this in IDLE: >>> from PIL import Image >>> from numpy import * >>> im = array(Image.open('Tulips.jpg').convert('L')) >>> im2,cdf = imtools.histeq(im) I get this: Traceback (most recent call last): File "", line 1, in im2,cdf = imtools.histeq(im) File "C:\Python27\imtools.py", line 18, in histeq imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) NameError: global name 'histogram' is not defined And the relevant portion in imtools.py is: def histeq(im,nbr_bins=256): """ Histogram equalization of a grayscale image. """ #get image histogram imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() #Cumulative distribution function cdf = 255* cdf/cdf[-1] #Normalize #Use linear interpolation of cdf to find new pixel values im2 = interp(im.flatten(), bins[:-1],cdf) return im2.reshape(im.shape), cdf ------------------------------------ Can anybody point out where I'm going wrong? I have Python 2.7, NumPY, SciPY etc. Thanks very much Python Newbie! -------------- next part -------------- An HTML attachment was scrubbed... URL: From me at staticsafe.ca Sat Nov 17 18:47:52 2012 From: me at staticsafe.ca (staticsafe) Date: Sat, 17 Nov 2012 12:47:52 -0500 Subject: [Tutor] New to Python - simple question In-Reply-To: References: Message-ID: <50A7CDC8.7070906@staticsafe.ca> On 11/16/2012 12:40, Unaiza Ahsan wrote: > Hi all, > > I am following Jan Erik Solem's book "Programming Computer Vision with > Python" and I'm just on the first chapter. The book asked us to create a > file imtools.py and put down helpful functions there, which we can just > call later. > > There is a function created for histogram equalization of images (called * > histeq*), and saved in imtools.py. When I use this function and type this > in IDLE: >>>> from PIL import Image >>>> from numpy import * >>>> im = array(Image.open('Tulips.jpg').convert('L')) >>>> im2,cdf = imtools.histeq(im) > > I get this: > > Traceback (most recent call last): > File "", line 1, in > im2,cdf = imtools.histeq(im) > File "C:\Python27\imtools.py", line 18, in histeq > imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) > NameError: global name 'histogram' is not defined > > And the relevant portion in imtools.py is: > def histeq(im,nbr_bins=256): > """ Histogram equalization of a grayscale image. """ > > #get image histogram > imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) > cdf = imhist.cumsum() #Cumulative distribution function > cdf = 255* cdf/cdf[-1] #Normalize > > #Use linear interpolation of cdf to find new pixel values > im2 = interp(im.flatten(), bins[:-1],cdf) > > return im2.reshape(im.shape), cdf > > ------------------------------------ > Can anybody point out where I'm going wrong? I have Python 2.7, NumPY, > SciPY etc. > > Thanks very much > > Python Newbie! Where is the histogram() function from? Is it in imtools.py as well? -- staticsafe O< ascii ribbon campaign - stop html mail - www.asciiribbon.org Please don't top post - http://goo.gl/YrmAb From eryksun at gmail.com Sat Nov 17 19:21:59 2012 From: eryksun at gmail.com (eryksun) Date: Sat, 17 Nov 2012 13:21:59 -0500 Subject: [Tutor] Quick question about definitions. In-Reply-To: <1353086931418-4996080.post@n6.nabble.com> References: <1353086931418-4996080.post@n6.nabble.com> Message-ID: On Fri, Nov 16, 2012 at 12:28 PM, sillywilly98 wrote: > > I know this code is not fully debugged. I just cant see why 1 definition is > wrong. You have several typos (there may be more): draw_eyes: end_fill(() draw_nose: end_fill(() draw_mouth: color("pink" forward((20) draw_head: color("blackk") goto(-100, 50 gto(-100, 50) draw_panel: clor("red") circle25, steps=3) rght(180) draw_arm: right(90") draw_body: width(1)) penupp() From d at davea.name Sat Nov 17 19:31:03 2012 From: d at davea.name (Dave Angel) Date: Sat, 17 Nov 2012 13:31:03 -0500 Subject: [Tutor] Quick question about definitions. In-Reply-To: <1353086931418-4996080.post@n6.nabble.com> References: <1353086931418-4996080.post@n6.nabble.com> Message-ID: <50A7D7E7.4010909@davea.name> On 11/16/2012 12:28 PM, sillywilly98 wrote: > I know this code is not fully debugged. I just cant see why 1 definition is > wrong. > Here is the code: > # This program draws a robot. > > from turtle import * > > def draw_eyes(): > # This function > penup() > color("purple") > goto(-50, 200) > pendown() > begin_fill() > circle(20) > end_fill() > penup() > goto(50, 200) > begin_fill() > circle(20) > end_fill(() The call to end_fil has unmatched parentheses. That means the expression continues on the next line. But def is a keyword and not valid inside an expression. def draw_nose(): # This function penup() color("orange") goto(0, 150) pendown() begin_fill() circle(20, steps=3) end_fill(() Same here. But in general, once you fix one error, you can spot the next one more easily. -- DaveA From alan.gauld at btinternet.com Sun Nov 18 00:36:56 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Nov 2012 23:36:56 +0000 Subject: [Tutor] Adding a gifting option too basic shipping page In-Reply-To: References: Message-ID: On 10/11/12 19:48, Elizabeth Balderston wrote: > I'm attempting to use Python in order to set up a basic shipping order > page. OK, I'll assume that you mean you are building a web app rather than a desktop? If so which web framework are you using, if any? > I realized that I had forgotten a gift option that would automatically > affect the price if checked. > > I have no idea how to add this feature to my program or if it will > change the whole thing so I have to start from scratch. And with no idea of what your design is like or which framework you are using neither does anyone else. This is a mailing list for folks learning to program with Python. Its focus is on Python itself and the standard library. You question is probably more related ton the web framework you are using and as such is better answered by their forum. However, even there, much will depend on how you have structured your application. Are you using a templating system to separate the web page design from the code? Are you using a database, and if so are you accessing it via an object-relational wrapper? Is it an MVC framework? Without knowing any of that we can only make the wildest guesses about your solution. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Nov 18 00:40:55 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Nov 2012 23:40:55 +0000 Subject: [Tutor] New to Python - simple question In-Reply-To: References: Message-ID: On 16/11/12 17:40, Unaiza Ahsan wrote: > There is a function created for histogram equalization of images (called > *histeq*), and saved in imtools.py. >>>> from PIL import Image >>>> from numpy import * >>>> im = array(Image.open('Tulips.jpg').convert('L')) >>>> im2,cdf = imtools.histeq(im) > > I get this: > > Traceback (most recent call last): > im2,cdf = imtools.histeq(im) > File "C:\Python27\imtools.py", line 18, in histeq > imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) > NameError: global name 'histogram' is not defined This tells us that the name histogram is not defined in the imtools.py file. Is it one of the modules ytou show imported above? If so it will not be visible inside imtools.py. You need to import the required module in that file too. But that's just a guess... > And the relevant portion in imtools.py is: > def histeq(im,nbr_bins=256): > """ Histogram equalization of a grayscale image. """ > > #get image histogram > imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) This is the call, but where is histogram? If it is in imtools are you sure the spelling is correct? If its not there you need to import it from wherever it is defined. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Nov 18 03:12:07 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 18 Nov 2012 13:12:07 +1100 Subject: [Tutor] Quick question about definitions. In-Reply-To: <1353086931418-4996080.post@n6.nabble.com> References: <1353086931418-4996080.post@n6.nabble.com> Message-ID: <50A843F7.4050800@pearwood.info> On 17/11/12 04:28, sillywilly98 wrote: > I know this code is not fully debugged. I just cant see why 1 definition is > wrong. Please don't send screen shots if you don't need to. In this case, the screen shot adds nothing, and turns this into a "long question" instead of a "quick question". When you try to run the code, Python will print an error message as text, which you can easily copy and paste into your email. You should get something like this: Traceback (most recent call last): File "", line 1, in File "test.py", line 20 def draw_nose(): ^ SyntaxError: invalid syntax That is MUCH quicker and simpler than: * take a screen shot * crop it * save it to a file * upload it to nabble.com * copy the URL * send the URL in an email * hope that people will click on the url * and that nabble isn't blocked for them (many people can receive email but have all or parts of the web blocked) * hope that they can guess what editor you are using * hope that they can guess why the editor has coloured "def" red * or yellow-grey-brown, if they are colour-blind[1] In this case, the solution is simple: the previous line to the def is missing the closing parenthesis: end_fill(() Unfortunately, when there is a missing bracket of any type, whether round ), square ] or brace }, the Python interpreter cannot tell it is missing until it reaches the *next* line. So often when you have a SyntaxError, it is on the line after the line with the actual problem. [1] Software developers: if your software uses colour *alone* to represent information, you are doing it wrong. About 8% of men and 0.5% of women have red-green colour-blindness, with other forms being less common. All up, about 1 in 10 men and 1 in 100 women cannot easily or at all distinguish colours. http://en.wikipedia.org/wiki/Colour_blindness -- Steven From swordangel at gmail.com Sun Nov 18 06:15:16 2012 From: swordangel at gmail.com (Kal Sze) Date: Sun, 18 Nov 2012 13:15:16 +0800 Subject: [Tutor] New to Python - simple question In-Reply-To: References: Message-ID: On 18 November 2012 07:40, Alan Gauld wrote: > On 16/11/12 17:40, Unaiza Ahsan wrote: > >> There is a function created for histogram equalization of images (called >> *histeq*), and saved in imtools.py. > > > >>>>> from PIL import Image >>>>> from numpy import * >>>>> im = array(Image.open('Tulips.jpg').convert('L')) >>>>> im2,cdf = imtools.histeq(im) >> >> >> I get this: >> >> Traceback (most recent call last): >> im2,cdf = imtools.histeq(im) >> File "C:\Python27\imtools.py", line 18, in histeq >> imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) >> NameError: global name 'histogram' is not defined > > > This tells us that the name histogram is not defined > in the imtools.py file. Is it one of the modules ytou show imported above? > If so it will not be visible inside imtools.py. You need to import the > required module in that file too. > > But that's just a guess... > > >> And the relevant portion in imtools.py is: >> def histeq(im,nbr_bins=256): >> """ Histogram equalization of a grayscale image. """ >> >> #get image histogram >> imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) > > > This is the call, but where is histogram? If it is in imtools are you sure > the spelling is correct? If its not there you need to import it from > wherever it is defined. > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hi all, The function histogram is supposed to come from the numpy module; at least that's the case on my computer (I have numpy 1.6.2 for Python 2.7): >>> from numpy import * >>> histogram Maybe something is wrong with Unaiza's version of numpy. Kal From sbjaved at gmail.com Sun Nov 18 06:23:28 2012 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 18 Nov 2012 10:23:28 +0500 Subject: [Tutor] sending email via smtplib Message-ID: import smtplib from_addr = "some_addr at hotmail.com" to_addr = "some_addr at gmail.com" smtp_srv = "smtp.live.com" subject = "Test" message = "Test" msg = "To:%s\nFrom:%s\nSubject: %s\n\n%s" % (to_addr, from_addr, subject, message) smtp = smtplib.SMTP(smtp_srv, 587) smtp.set_debuglevel(1) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(user, passwd) smtp.sendmail(from_addr, to_addr, msg) smtp.quit() When I run this code, I get this output: send: 'ehlo [127.0.1.1]\r\n' reply: '250-BLU0-SMTP190.blu0.hotmail.com Hello [my-ip-address]\r\n' reply: '250-TURN\r\n' reply: '250-SIZE 41943040\r\n' reply: '250-ETRN\r\n' reply: '250-PIPELINING\r\n' reply: '250-DSN\r\n' reply: '250-ENHANCEDSTATUSCODES\r\n' reply: '250-8bitmime\r\n' reply: '250-BINARYMIME\r\n' reply: '250-CHUNKING\r\n' reply: '250-VRFY\r\n' reply: '250-TLS\r\n' reply: '250-STARTTLS\r\n' reply: '250 OK\r\n' reply: retcode (250); Msg: BLU0-SMTP190.blu0.hotmail.com Hello [my-ip-address] TURN SIZE 41943040 ETRN PIPELINING DSN ENHANCEDSTATUSCODES 8bitmime BINARYMIME CHUNKING VRFY TLS STARTTLS OK send: 'STARTTLS\r\n' Traceback (most recent call last): File "sendemail.py", line 24, in smtp.starttls() File "/usr/lib/python2.7/smtplib.py", line 636, in starttls (resp, reply) = self.docmd("STARTTLS") File "/usr/lib/python2.7/smtplib.py", line 385, in docmd return self.getreply() File "/usr/lib/python2.7/smtplib.py", line 358, in getreply + str(e)) smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 104] Connection reset by peer I can send email via browser. Why is my authentication being blocked by hotmail? P.S: I tried sending from gmail. Same error. Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 18 09:44:22 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 18 Nov 2012 08:44:22 +0000 (GMT) Subject: [Tutor] New to Python - simple question In-Reply-To: References: Message-ID: <1353228262.61378.YahooMailNeo@web87902.mail.ir2.yahoo.com> >>> And the relevant portion in imtools.py is: >>> def histeq(im,nbr_bins=256): >>>? ? ? """ Histogram equalization of a grayscale image. """ >>> >>>? ? ? #get image histogram >>>? ? ? imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) >> >> >> This is the call, but where is histogram? If it is in imtools are you sure > >The function histogram is supposed to come from the numpy module; at >least that's the case on my computer (I have numpy 1.6.2 for Python >2.7): > >>>> from numpy import * >>>> histogram > > >Maybe something is wrong with Unaiza's version of numpy. >More likely is that there is no import statement for numpy in imtools.py Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Sun Nov 18 12:21:50 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 18 Nov 2012 14:21:50 +0300 Subject: [Tutor] Help with a SQL Statement Message-ID: Hi All, The SQL statement below doesn't return anything.. and I don't know why... I've used the parans but still no luck. Any Suggestions? cur.execute("""select badge, name, stage, tc, major, package, subject, course, sb_as from records where sb_as = 0 and (subject like 'Workshop&' or subject like 'Basic%' or subject like 'Introduction%') and (major not like 'Customer%' or major not like 'Warehouse%') order by tc""") Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From emailkgnow at gmail.com Sun Nov 18 12:29:27 2012 From: emailkgnow at gmail.com (Khalid Al-Ghamdi) Date: Sun, 18 Nov 2012 14:29:27 +0300 Subject: [Tutor] Help with a SQL Statement In-Reply-To: References: Message-ID: Hi, I found one typo in 'Workshop&' which should be 'Workshop%' but it still gives results containing majors with 'Customer%' and 'Warehouse%' in them... On Sun, Nov 18, 2012 at 2:21 PM, Khalid Al-Ghamdi wrote: > Hi All, > > The SQL statement below doesn't return anything.. and I don't know why... > I've used the parans but still no luck. Any Suggestions? > > cur.execute("""select badge, name, stage, tc, major, package, subject, > course, sb_as from records where > sb_as = 0 and (subject like 'Workshop&' or subject like > 'Basic%' or subject like 'Introduction%') and > (major not like 'Customer%' or major not like > 'Warehouse%') order by tc""") > > Thanks > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Sun Nov 18 13:13:16 2012 From: bodsda at googlemail.com (Bod Soutar) Date: Sun, 18 Nov 2012 12:13:16 +0000 Subject: [Tutor] Help with a SQL Statement In-Reply-To: References: Message-ID: On Nov 18, 2012 11:30 AM, "Khalid Al-Ghamdi" wrote: > > Hi, I found one typo in 'Workshop&' which should be 'Workshop%' but it still gives results containing majors with 'Customer%' and 'Warehouse%' in them... > > > On Sun, Nov 18, 2012 at 2:21 PM, Khalid Al-Ghamdi wrote: >> >> Hi All, >> >> The SQL statement below doesn't return anything.. and I don't know why... I've used the parans but still no luck. Any Suggestions? >> >> cur.execute("""select badge, name, stage, tc, major, package, subject, course, sb_as from records where >> sb_as = 0 and (subject like 'Workshop&' or subject like 'Basic%' or subject like 'Introduction%') and >> (major not like 'Customer%' or major not like 'Warehouse%') order by tc""") >> >> Thanks >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > This is not a python issue, but shouldn't the last part of your where clause be "major not like 'Customer%' and major not like 'Warehouse%'" ? Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 18 16:53:32 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Nov 2012 15:53:32 +0000 Subject: [Tutor] Help with a SQL Statement In-Reply-To: References: Message-ID: On 18/11/12 11:29, Khalid Al-Ghamdi wrote: > The SQL statement below doesn't return anything.. and I don't know > why... I've used the parans but still no luck. Any Suggestions? I'll restructure it to how I think you want it... cur.execute(""" select badge, name, stage, tc, major, package, subject, course, sb_as from records where sb_as = 0 and (subject like 'Workshop&') or (subject like 'Basic%') or (subject like 'Introduction%') and (major not like 'Customer%') or (major not like 'Warehouse%') order by tc""") See if that helps... I think your parens were grouping the wrong things. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From drew00andy at yahoo.co.uk Sun Nov 18 18:50:14 2012 From: drew00andy at yahoo.co.uk (Andrew) Date: Sun, 18 Nov 2012 19:50:14 +0200 Subject: [Tutor] LCM In-Reply-To: <50A3DA43.3000600@ymail.com> References: <50A3DA43.3000600@ymail.com> Message-ID: On Wed, 14 Nov 2012 19:52:03 +0200, Selby Rowley Cannon wrote: > Hey, > > I've been trying to write a function to find the Lowest Common > Multiple of two numbers, but it isn't working and I've kinda hit a dead > end on the thought-process end of things. Anyone mind looking at it, and > tell me what's wrong? (I hop you don't think it's too long to put in an > email) > > Code: > > def lowestCommonMultiple(a, b, amount): #k > float(amount) > if a == b: > print 'You cannot find the LCM of the same number twice.' > else: > numbersList = list(range(amount)) > aMultiples = [] > bMultiples = [] > for aNumber in numbersList: > aMultiples.append(a*aNumber) > for bNumber in numbersList: > bMultiples.append(b*bNumber) > if aMultiples[1] == bMultiples[1]: > print 'The LCM of ', a, ' and ', b, ' is ', aMultiple[1] > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hello World, I have script I wonder if it would be suitable: def LCM(x,y): for n in range(1, 10000): for n2 in range(1, 10000): x_lcm = x*n y_lcm = y*n2 if x_lcm == y_lcm: print"The LCM of",x,"and",y,"is",x_lcm return x_lcm else: pass dx -- ???(shuhari) first learn, then detach, and finally transcend From jguadamuz at gmail.com Sun Nov 18 19:41:20 2012 From: jguadamuz at gmail.com (=?ISO-8859-1?Q?Jonat=E1n_Guadamuz_Espinoza?=) Date: Sun, 18 Nov 2012 12:41:20 -0600 Subject: [Tutor] Pygame problem with mac In-Reply-To: <9DC790DD-03F7-4352-BF04-0553C824BF51@gmail.com> References: <9DC790DD-03F7-4352-BF04-0553C824BF51@gmail.com> Message-ID: El nov 17, 2012 11:39 a.m., "Ciaran Mooney" escribi?: > > Hi, > > Was hoping u could help me. > > I can't seem to download a version of pygame that is compatible with python 3.2 on my Mac powerbook with OS tiger. You could look at this page http://packages.debian.org/experimental/python3-pygame Here you can get source could suited for python 3. > > I only seem to he able to get pygame for python 2.7 which i have never used. > > Thanks > Ciaran > > > _______________________________________________ > 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 d at davea.name Sun Nov 18 21:27:49 2012 From: d at davea.name (Dave Angel) Date: Sun, 18 Nov 2012 15:27:49 -0500 Subject: [Tutor] LCM In-Reply-To: References: <50A3DA43.3000600@ymail.com> Message-ID: <50A944C5.7030005@davea.name> On 11/18/2012 12:50 PM, Andrew wrote: > On Wed, 14 Nov 2012 19:52:03 +0200, Selby Rowley Cannon > wrote: > >> Hey, >> >> I've been trying to write a function to find the Lowest Common >> Multiple of two numbers, but it isn't working and I've kinda hit a >> dead end on the thought- >> I have script I wonder if it would be suitable: > > > def LCM(x,y): > for n in range(1, 10000): > for n2 in range(1, 10000): > x_lcm = x*n > y_lcm = y*n2 > if x_lcm == y_lcm: > print"The LCM of",x,"and",y,"is",x_lcm > return x_lcm > else: > pass > That won't usually provide the LCM, it'll just provide some common multiple. Occasionally, it'll happen to be right. Rather than returning the first value that's equal, you'd have to return the lowest value that's equal. -- DaveA From etter at member.fsf.org Mon Nov 19 00:42:00 2012 From: etter at member.fsf.org (Alexander) Date: Sun, 18 Nov 2012 18:42:00 -0500 Subject: [Tutor] sending email via smtplib In-Reply-To: References: Message-ID: On Sun, Nov 18, 2012 at 12:23 AM, Saad Javed wrote: > import smtplib > > from_addr = "some_addr at hotmail.com" > to_addr = "some_addr at gmail.com" > smtp_srv = "smtp.live.com" > > subject = "Test" > message = "Test" > > msg = "To:%s\nFrom:%s\nSubject: %s\n\n%s" % (to_addr, from_addr, subject, > message) > > smtp = smtplib.SMTP(smtp_srv, 587) > smtp.set_debuglevel(1) > smtp.ehlo() > smtp.starttls() > smtp.ehlo() > smtp.login(user, passwd) > smtp.sendmail(from_addr, to_addr, msg) > smtp.quit() > > When I run this code, I get this output: > send: 'ehlo [127.0.1.1]\r\n' > reply: '250-BLU0-SMTP190.blu0.hotmail.com Hello [my-ip-address]\r\n' > reply: '250-TURN\r\n' > reply: '250-SIZE 41943040\r\n' > reply: '250-ETRN\r\n' > reply: '250-PIPELINING\r\n' > reply: '250-DSN\r\n' > reply: '250-ENHANCEDSTATUSCODES\r\n' > reply: '250-8bitmime\r\n' > reply: '250-BINARYMIME\r\n' > reply: '250-CHUNKING\r\n' > reply: '250-VRFY\r\n' > reply: '250-TLS\r\n' > reply: '250-STARTTLS\r\n' > reply: '250 OK\r\n' > reply: retcode (250); Msg: BLU0-SMTP190.blu0.hotmail.com Hello > [my-ip-address] > TURN > SIZE 41943040 > ETRN > PIPELINING > DSN > ENHANCEDSTATUSCODES > 8bitmime > BINARYMIME > CHUNKING > VRFY > TLS > STARTTLS > OK > send: 'STARTTLS\r\n' > Traceback (most recent call last): > File "sendemail.py", line 24, in > smtp.starttls() > File "/usr/lib/python2.7/smtplib.py", line 636, in starttls > (resp, reply) = self.docmd("STARTTLS") > File "/usr/lib/python2.7/smtplib.py", line 385, in docmd > return self.getreply() > File "/usr/lib/python2.7/smtplib.py", line 358, in getreply > + str(e)) > smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno > 104] Connection reset by peer > > I can send email via browser. Why is my authentication being blocked by > hotmail? > > P.S: I tried sending from gmail. Same error. > > Saad > > You start TLS but is the connection to the server secured using SSL? Usually email providers have particular ports and types of encryption that must be specified to authenticate before you can DL an entire inbox or send a message from the address. Alexander -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbjaved at gmail.com Mon Nov 19 06:32:25 2012 From: sbjaved at gmail.com (Saad Javed) Date: Mon, 19 Nov 2012 10:32:25 +0500 Subject: [Tutor] sending email via smtplib In-Reply-To: References: Message-ID: I don't think using SSL works with hotmail. I tried using: smtplib.*SMTP_SSL*("smtp.live.com", 587) smtplib.login(user, passwd) ... That gave this error: Traceback (most recent call last): File "sendemail.py", line 22, in smtp = smtplib.SMTP_SSL(smtp_srv, 587) File "/usr/lib/python2.7/smtplib.py", line 776, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout) File "/usr/lib/python2.7/smtplib.py", line 249, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 309, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 782, in _get_socket new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket ciphers=ciphers) File "/usr/lib/python2.7/ssl.py", line 143, in __init__ self.do_handshake() File "/usr/lib/python2.7/ssl.py", line 305, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Mon Nov 19 12:02:47 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 19 Nov 2012 03:02:47 -0800 (PST) Subject: [Tutor] memoize, lookup, or KIS? Message-ID: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> Hi, I have a function that converts a date value, expressed as the number of seconds sinds start of the gregorian calendar, into a human-readable format (typically an iso-date). So if a record contains x date values, and a data set contains y records, the number of function calls are x * y. Imagine a data set with 1M records with dob and enrollment_date in in it: the number of function calls is huge (well, 2M). I was reading about memoize decorators the other day and I realized that this function might benefit from memoizing, or a lookup table. On the other hand, it might complicate the code too much, so it might be better to Keep It Simple (KIS). Is the code below a sound approach? I believe that, in effect, it uses a memoization approach (as it is a slowly growing lookup table). import datetime class Test(object): ??? def __init__(self): ??????? self.isoDateLookup = {} ??????? self.lookupCount = 0 ??????? ??? def spss2strDate(self, gregorianDate, fmt="%Y-%m-%d", recodeSysmisTo=""): ??????? """ This function converts internal SPSS dates (number of seconds ??????? since midnight, Oct 14, 1582 (the beginning of the Gregorian calendar)) ??????? to a human-readable format """ ??????? MAXLOOKUP = 10**6 ??????? try: ??????????? if not hasattr(self, "gregorianEpoch"): ??????????????? self.gregorianEpoch = datetime.datetime(1582, 10, 14, 0, 0, 0) ??????????? if fmt == "%Y-%m-%d" and len(self.isoDateLookup) <= MAXLOOKUP: ??????????????? try: ??????????????????? result = self.isoDateLookup[gregorianDate] ??????????????????? self.lookupCount += 1 ??????????????? except KeyError: ??????????????????? theDate = self.gregorianEpoch + datetime.timedelta(seconds=gregorianDate) ??????????????????? result = datetime.datetime.strftime(theDate, fmt) ??????????????????? self.isoDateLookup[gregorianDate] = result ??????????????? return result ??????????? else: ??????????????? theDate = self.gregorianEpoch + datetime.timedelta(seconds=gregorianDate) ??????????????? return datetime.datetime.strftime(theDate, fmt) ??????? except OverflowError: ??????????? return recodeSysmisTo ??????? except TypeError: ??????????? return recodeSysmisTo ??????? except ValueError: ??????????? return recodeSysmisTo if __name__ == "__main__": ??? import random ??? t = Test() ??? someDate = 11654150400.0 ??? aDay = 24 * 60 * 60 ??? random.seed(43210) ??? for i in xrange(10**3): ??????? randDate = random.randint(0, 10**3) * random.choice([aDay, -aDay]) + someDate ??????? t.spss2strDate(randDate) ??? print t.lookupCount ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Nov 19 13:05:27 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 19 Nov 2012 23:05:27 +1100 Subject: [Tutor] memoize, lookup, or KIS? In-Reply-To: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> References: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> Message-ID: <50AA2087.80600@pearwood.info> On 19/11/12 22:02, Albert-Jan Roskam wrote: > Hi, > > I have a function that converts a date value, expressed as the number of >seconds sinds start of the gregorian calendar, into a human-readable format >(typically an iso-date). So if a record contains x date values, and a data >set contains y records, the number of function calls are x * y. Imagine a > data set with 1M records with dob and enrollment_date in in it: the number > of function calls is huge (well, 2M). > > > I was reading about memoize decorators the other day and I realized that >this function might benefit from memoizing, or a lookup table. Emphasis on "might". Unless you have timed the code with or without a lookup table, you're just guessing whether it is an optimization or a pessimization. On the other hand, my intuition is that it *will* benefit from memoization, so my guess is the same as your guess :) > On the other hand, it might complicate the code too much, so it might >be better to Keep It Simple (KIS). Is the code below a sound approach? No. You should separate the cache code from the non-cache code. Decorators are ideal for that, but even without decorators you should split the code. See below. Also, you should have some way to stop the lookup table from growing forever. If you are running Python 3.3, you can use functools.lru_cache, which implements a Least Recently Used cache. Once the cache reaches a certain size, the element which was least recently used is flushed. Usage is trivially simple, at least for functions, I've never used it with methods and there may be some complications. But the usage is: @functools.lru_cache(maxsize) def myfunction(a, b, c): result = some_calculation(a, b) + c # whatever return result and the decorator will automatically look after storing results in the lookup table, retrieving them afterwards, and ensuring it never gets too big. Writing completely general purpose memoize decorators can be a bit tricky, but you can find a whole lot of recipes here: http://code.activestate.com/search/recipes/#q=memoize Here's a trivial approach which doesn't use a decorator at all. The important feature is that the caching logic isn't mixed up with the uncached logic. class Test(object): def __init__(self): self._cache = {} def clear_cache(self): self._cache.clear() def spss2strDate(self, gregorianDate, fmt="%Y-%m-%d", recodeSysmisTo=""): # cached wrapper t = (gregorianDate, fmt, recodeSysmisTo) if t in self._cache: # cache hit return self._cache[t] # otherwise cache miss result = self._calculate_spss2strDate(*t) # this does the real work if len(self._cache) > 1000: self._cache.popitem() # discard an arbitrary (key,value) pair self._cache[t] = result return result def _calculate_spss2strDate(self, gregorianDate, fmt, recodeSysmisTo): # uncached version return some_calculation(...) You can fill in the details for the uncached version :) One good improvement would be to add instrumentation[1] to the cache so you can tell whether or not the cache is worthwhile. E.g. record how many times each set of arguments are used. If you find that hardly any triple of arguments is used multiple times (i.e. nearly every call is unique), then the cache is a waste of time. [1] A fancy term for any sort of extra data associated with the cache, such as a count of how many cache hits and misses there are. -- Steven From oscar.j.benjamin at gmail.com Mon Nov 19 13:18:19 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 19 Nov 2012 12:18:19 +0000 Subject: [Tutor] memoize, lookup, or KIS? In-Reply-To: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> References: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> Message-ID: On 19 November 2012 11:02, Albert-Jan Roskam wrote: > Hi, > > I have a function that converts a date value, expressed as the number of > seconds sinds start of the gregorian calendar, into a human-readable format > (typically an iso-date). So if a record contains x date values, and a data > set contains y records, the number of function calls are x * y. Imagine a > data set with 1M records with dob and enrollment_date in in it: the number > of function calls is huge (well, 2M). The number of function calls is one factor that affects whether memoisation is worthwhile. The more important questions are: How often do you call the function with the same input values? How expensive is the function compared with the table lookup? Memoisation can, for a cheap function, actually slow it down. Before you do anything like this you need to profile your code and ensure that the function in question is actually a bottleneck. Otherwise you're wasting memory and coding time without getting much of a speed up. > I was reading about memoize decorators the other day and I realized that > this function might benefit from memoizing, or a lookup table. On the other > hand, it might complicate the code too much, so it might be better to Keep > It Simple (KIS). Is the code below a sound approach? I believe that, in > effect, it uses a memoization approach (as it is a slowly growing lookup > table). This function is using memoisation but why aren't you just using the memoisation decorators that you read about? > import datetime > > class Test(object): > > def __init__(self): > self.isoDateLookup = {} > self.lookupCount = 0 > > def spss2strDate(self, gregorianDate, fmt="%Y-%m-%d", > recodeSysmisTo=""): > """ This function converts internal SPSS dates (number of seconds > since midnight, Oct 14, 1582 (the beginning of the Gregorian > calendar)) > to a human-readable format """ > MAXLOOKUP = 10**6 > try: > if not hasattr(self, "gregorianEpoch"): > self.gregorianEpoch = datetime.datetime(1582, 10, 14, 0, 0, > 0) > if fmt == "%Y-%m-%d" and len(self.isoDateLookup) <= MAXLOOKUP: > try: > result = self.isoDateLookup[gregorianDate] > self.lookupCount += 1 > except KeyError: > theDate = self.gregorianEpoch + > datetime.timedelta(seconds=gregorianDate) > result = datetime.datetime.strftime(theDate, fmt) > self.isoDateLookup[gregorianDate] = result > return result > else: > theDate = self.gregorianEpoch + > datetime.timedelta(seconds=gregorianDate) > return datetime.datetime.strftime(theDate, fmt) > except OverflowError: > return recodeSysmisTo > except TypeError: > return recodeSysmisTo > except ValueError: > return recodeSysmisTo The advantage of using a decorator for this are that you don't need to complicate the internal code of the function that is memoised and it is easy to enable and disable memoisation. I would just use a decorator. You don't need to write one yourself. Since Python 3.2 the standard library contains a memoisation decorator that you can use: http://docs.python.org/dev/library/functools.html#functools.lru_cache Presumably the place where you read about them would have listed some example decorators that you can use for memoisation. Here's a quick example that works for hashable inputs: def memo(func): table = {} def wrapper(inputarg): try: return table[inputarg] except KeyError: table[inputarg] = val = func(inputarg) return val return wrapper @memo def square(x): print('Calling square()') return x ** 2 print('2**2 is %i' % square(2)) # cache miss print('3**2 is %i' % square(3)) # cache miss print('2**2 is %i' % square(2)) # cache hit Output: $ python tmp.py Calling square() 2**2 is 4 Calling square() 3**2 is 9 2**2 is 4 Oscar From fomcl at yahoo.com Mon Nov 19 17:52:28 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 19 Nov 2012 08:52:28 -0800 (PST) Subject: [Tutor] memoize, lookup, or KIS? In-Reply-To: References: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> Message-ID: <1353343948.40230.YahooMailNeo@web110710.mail.gq1.yahoo.com> >Presumably the place where you read about them would have listed some >example decorators that you can use for memoisation. Here's a quick >example that works for hashable inputs: > Some of these I don't really understand so I am hesitant to use them. >def memo(func): >? ? table = {} >? ? def wrapper(inputarg): >? ? ? ? try: >? ? ? ? ? ? return table[inputarg] >? ? ? ? except KeyError: >? ? ? ? ? ? table[inputarg] = val = func(inputarg) >? ? ? ? ? ? return val >? ? return wrapper > >@memo >def square(x): >? ? print('Calling square()') >? ? return x ** 2 Nice and conscise! I did some profiling and it is fast, too. But as Steven said, I also need to maximize the cache, among other things. I also gotta figure out what I'll do with datetime values (probably it's not useful to cache these). # 1M function calls a--115.837 CPU seconds? # no memoization b--215.753 CPU seconds? # memodict # http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/ c--62.547 CPU seconds?? # simple decorator # http://code.activestate.com/recipes/577219-minimalistic-memoization/ d--60.771 CPU seconds?? # Oscar Benjamin, modified to: ??? def memo(func): ??????? table = {} ??????? def wrapper(*inputarg): ??????????? try: ??????????????? return table[inputarg[0:2]] # ??????????? except KeyError: ??????????????? table[inputarg[0:2]] = val = func(*inputarg) ??????????????? return val ??????? return wrapper From fomcl at yahoo.com Mon Nov 19 18:38:22 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 19 Nov 2012 09:38:22 -0800 (PST) Subject: [Tutor] memoize, lookup, or KIS? In-Reply-To: <50AA2087.80600@pearwood.info> References: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> <50AA2087.80600@pearwood.info> Message-ID: <1353346702.7298.YahooMailNeo@web110714.mail.gq1.yahoo.com> > Emphasis on "might". Unless you have timed the code with or without a > lookup > table, you're just guessing whether it is an optimization or a > pessimization. > See my earlier reply to Oscar's mail. I used cProfile and memoizing was almost twice as fast in the fastsest implementation. > On the other hand, my intuition is that it *will* benefit from memoization, > so my guess is the same as your guess :) > > >> On the other hand, it might complicate the code too much, so it might >> be better to Keep It Simple (KIS). Is the code below a sound approach? > > > No. You should separate the cache code from the non-cache code. Decorators > are ideal for that, but even without decorators you should split the code. > See below. Yes, it feels a lot less mentally straining to read the code where memoizing and the actual job are separated. > Also, you should have some way to stop the lookup table from growing forever. > If you are running Python 3.3, you can use functools.lru_cache, which > implements a Least Recently Used cache. Once the cache reaches a certain size, > the element which was least recently used is flushed. > I read about that. Time to upgrade! Wish I could use this in the office! ? > class Test(object): > > ? ? def __init__(self): > ? ? ? ? self._cache = {} > > ? ? def clear_cache(self): > ? ? ? ? self._cache.clear() > > ? ? def spss2strDate(self, gregorianDate, fmt="%Y-%m-%d", > recodeSysmisTo=""): > ? ? ? ? # cached wrapper > ? ? ? ? t = (gregorianDate, fmt, recodeSysmisTo) > ? ? ? ? if t in self._cache: > ? ? ? ? ? ? # cache hit > ? ? ? ? ? ? return self._cache[t] > ? ? ? ? # otherwise cache miss > ? ? ? ? result = self._calculate_spss2strDate(*t)? # this does the real work > ? ? ? ? if len(self._cache) > 1000: > ? ? ? ? ? ? self._cache.popitem()? # discard an arbitrary (key,value) pair > ? ? ? ? self._cache[t] = result > ? ? ? ? return result > > ? ? def _calculate_spss2strDate(self, gregorianDate, fmt, recodeSysmisTo): > ? ? ? ? # uncached version > ? ? ? ? return some_calculation(...) > > > You can fill in the details for the uncached version :) > > One good improvement would be to add instrumentation[1] to the cache so you can > tell whether or not the cache is worthwhile. E.g. record how many times each > set of arguments are used. If you find that hardly any triple of arguments is > used multiple times (i.e. nearly every call is unique), then the cache is a > waste of time. It would be cool if the memoizer "turned off" itself off if hardly items are retrieved from it (ie, the calls are almost always unique). stop_memoizing = (n_cached_version / float(n_newly_calculated_version)) < some_threshold and len(cache) > some_value From ramit.prasad at jpmorgan.com Mon Nov 19 19:14:07 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 19 Nov 2012 18:14:07 +0000 Subject: [Tutor] sending email via smtplib In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474167B8904@SCACMX008.exchad.jpmchase.net> Saad Javed wrote: > > I don't think using SSL works with hotmail. I tried using: > > smtplib.SMTP_SSL("smtp.live.com", 587) You need to use port 25 not 587. http://windows.microsoft.com/en-US/hotmail/send-receive-email-from-mail-client > smtplib.login(user, passwd) > ... > > That gave this error: > > Traceback (most recent call last): > ? File "sendemail.py", line 22, in > ? ? smtp = smtplib.SMTP_SSL(smtp_srv, 587) > ? File "/usr/lib/python2.7/smtplib.py", line 776, in __init__ > ? ? SMTP.__init__(self, host, port, local_hostname, timeout) > ? File "/usr/lib/python2.7/smtplib.py", line 249, in __init__ > ? ? (code, msg) = self.connect(host, port) > ? File "/usr/lib/python2.7/smtplib.py", line 309, in connect > ? ? self.sock = self._get_socket(host, port, self.timeout) > ? File "/usr/lib/python2.7/smtplib.py", line 782, in _get_socket > ? ? new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) > ? File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket > ? ? ciphers=ciphers) > ? File "/usr/lib/python2.7/ssl.py", line 143, in __init__ > ? ? self.do_handshake() > ? File "/usr/lib/python2.7/ssl.py", line 305, in do_handshake > ? ? self._sslobj.do_handshake() > ssl.SSLError: [Errno 1] _ssl.c:504: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol > ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ramit.prasad at jpmorgan.com Mon Nov 19 22:25:58 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Mon, 19 Nov 2012 21:25:58 +0000 Subject: [Tutor] memoize, lookup, or KIS? In-Reply-To: <1353346702.7298.YahooMailNeo@web110714.mail.gq1.yahoo.com> References: <1353322967.87760.YahooMailNeo@web110715.mail.gq1.yahoo.com> <50AA2087.80600@pearwood.info> <1353346702.7298.YahooMailNeo@web110714.mail.gq1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474167B8BC9@SCACMX008.exchad.jpmchase.net> Albert-Jan Roskam wrote: > [snip] > > Also, you should have some way to stop the lookup table from growing forever. > > If you are running Python 3.3, you can use functools.lru_cache, which > > implements a Least Recently Used cache. Once the cache reaches a certain size, > > the element which was least recently used is flushed. > > > > I read about that. Time to upgrade! Wish I could use this in the office! > Why can you not? Even if you are not using Python3.2+ you should be able to back port it from the Python source. You may need to backport other features (e.g. OrderedDict) depending on the Python version you use. http://svn.python.org/projects/python/tags/r32b1/Lib/functools.py Alternatively, you can use Raymond Hettinger's recipe. At a brief glance, it looks to be Python 2.x compatible. http://code.activestate.com/recipes/498245/ ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From isaac.parkes at googlemail.com Mon Nov 19 19:07:10 2012 From: isaac.parkes at googlemail.com (Isaac Parkes) Date: Mon, 19 Nov 2012 18:07:10 +0000 Subject: [Tutor] help Message-ID: hi, I'm quite new to python and have just made a program that makes a GUI but when i open it it says there are some errors. I can't find any :( if you find any problems could you tell me ASAP # Match finder from TKinter import * import random girls = ['Ellie', 'Maddy', 'Ursula', 'Annie', 'Stella', 'Kimberely', 'Flora', 'Hannah', 'Bella', 'Ella', 'Rosa', 'Olivia', 'Liya', 'Emma', 'Irene'] boys = ['Charlie', 'sion', 'Mikey', 'Jem', 'Matthew', 'Ethan', 'Kainan', 'Louis', 'Jack', 'Abel', 'Alex', 'Tom', 'Will', 'James', 'Isaac'] class Application(Frame): """ GUI application which can reveal your perfect match. """ def __init__(self, master): """ Initialize the frame. """ Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create button, text, and entry widgets. """ # create instruction label self.inst_lbl = Label(self, text = "Enter details below to find out your perfect match") self.inst_lbl.grid(row = 0, column = 0, columnspan = 2, sticky = W) # create label for name self.pw_lbl = Label(self, text = "Name: ") self.pw_lbl.grid(row = 1, column = 0, sticky = W) # create entry widget to accept name self.pw_ent = Entry(self) self.pw_ent.grid(row = 1, column = 1, sticky = W) # create variable for single, favorite type of movie self.favorite = StringVar() # create boy radio button Radiobutton(self, gender = "Boy", variable = self.favorite, gender1 = "Boy.", command = self.update_text ).grid(row = 2, column = 0, sticky = W) # create girl radio button Radiobutton(self, gender = "Girl", variable = self.favorite, gender1 = "Girl.", command = self.update_text ).grid(row = 3, column = 0, sticky = W) # create submit button self.submit_bttn = Button(self, text = "Submit", command = self.reveal) self.submit_bttn.grid(row = 2, column = 0, sticky = W) # create text widget to display message self.secret_txt = Text(self, width = 35, height = 5, wrap = WORD) self.secret_txt.grid(row = 3, column = 0, columnspan = 2, sticky = W) def update_text(self): """ Display message based on match. """ message = "Your perfect match is: ", if gender == 'boy': choice = random.choice(girls) else: choice = random.choice(boys) message += choice self.secret_txt.delete(0.0, END) self.secret_txt.insert(0.0, message) # main root = Tk() root.title("Match finder") root.geometry("250x150") app = Application(root) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: From unaiza.ahsan at gmail.com Sat Nov 17 20:15:06 2012 From: unaiza.ahsan at gmail.com (Unaiza Ahsan) Date: Sat, 17 Nov 2012 14:15:06 -0500 Subject: [Tutor] New to Python - simple question Message-ID: * Where is the histogram() function from? Is it in imtools.py as well? * It is a NumPY function. -------------- next part -------------- An HTML attachment was scrubbed... URL: From unaiza.ahsan at gmail.com Sun Nov 18 15:07:04 2012 From: unaiza.ahsan at gmail.com (Unaiza Ahsan) Date: Sun, 18 Nov 2012 09:07:04 -0500 Subject: [Tutor] New to Python - simple question Message-ID: *Hi all, The function histogram is supposed to come from the numpy module; at* * least that's the case on my computer (I have numpy 1.6.2 for Python 2.7): >>> from numpy import ** * >>> histogram Maybe something is wrong with Unaiza's version of numpy.* * Kal *Yes it's supposed to come from numpy. In imtools.py, the following line is there: from numpy import * But I'm still getting the error. Since I'm a beginner in Python, I'm not at all sure what's wrong here. Thanks for the pointers/help. Unaiza -------------- next part -------------- An HTML attachment was scrubbed... URL: From vaddesreenivasulu at gmail.com Mon Nov 19 17:33:55 2012 From: vaddesreenivasulu at gmail.com (Sreenivasulu) Date: Mon, 19 Nov 2012 22:03:55 +0530 Subject: [Tutor] pyXML i Python2.6 Message-ID: Hi, Am unable to install pyXML in Ubuntu usig python2.6 Could you please help me Regards, Sreenu -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Tue Nov 20 00:28:24 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Mon, 19 Nov 2012 23:28:24 +0000 Subject: [Tutor] help In-Reply-To: References: Message-ID: It's asking a lot if you want people to read your whole code to try and spot the errors. Try to run it from the console and paste what the errors are here. From breamoreboy at yahoo.co.uk Tue Nov 20 00:37:02 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 19 Nov 2012 23:37:02 +0000 Subject: [Tutor] pyXML i Python2.6 In-Reply-To: References: Message-ID: On 19/11/2012 16:33, Sreenivasulu wrote: > Hi, > > Am unable to install pyXML in Ubuntu usig python2.6 > > Could you please help me > > Regards, > Sreenu > What have you tried? What went wrong? If you don't give such basic data how can we help? -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Nov 20 00:53:11 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 19 Nov 2012 23:53:11 +0000 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 19/11/2012 18:07, Isaac Parkes wrote: First of all giving a meaningful subject helps everybody, how about "tkinter problems"? > hi, > > I'm quite new to python and have just made a program that makes a GUI but > when i open it it says there are some errors. I can't find any :( if you > find any problems could you tell me ASAP > Stating there are some errors is as useful as a chocolate teapot. How did you try to run the code? What Python version, your code will need changing to run on Python 3.x, what OS? What are you expecting to happen, what actually happened? -- Cheers. Mark Lawrence. From breamoreboy at yahoo.co.uk Tue Nov 20 01:33:25 2012 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 20 Nov 2012 00:33:25 +0000 Subject: [Tutor] help In-Reply-To: References: Message-ID: On 19/11/2012 23:28, Matthew Ngaha wrote: > It's asking a lot if you want people to read your whole code to try > and spot the errors. Try to run it from the console and paste what the > errors are here. I believe that to be complete nonsense, there was very little code to parse. What was missing I've already asked for in a separate reply. -- Cheers. Mark Lawrence. From steve at pearwood.info Tue Nov 20 02:46:00 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Nov 2012 12:46:00 +1100 Subject: [Tutor] help In-Reply-To: References: Message-ID: <50AAE0D8.6020305@pearwood.info> On 20/11/12 11:33, Mark Lawrence wrote: > On 19/11/2012 23:28, Matthew Ngaha wrote: >> It's asking a lot if you want people to read your whole code to try >> and spot the errors. Try to run it from the console and paste what the >> errors are here. > > I believe that to be complete nonsense, there was very little code to >parse. What was missing I've already asked for in a separate reply. My, you're argumentative today :) You *also* asked the Original Poster to explain what errors he got. Your exact words: "Stating there are some errors is as useful as a chocolate teapot. ... What are you expecting to happen, WHAT ACTUALLY HAPPENED?" [emphasis added] Whether there are 10000 lines or 10 lines, telling people "there are errors" and expecting them to work out for themselves what those errors are *is* asking a lot. We're volunteers here, people asking for help are asking us to donate our time for free. Asking us to help identify and fix errors is one thing. Asking us to *find* the errors first is too much. Honestly, sometimes I don't understand people on the Internet. No offense to the original poster Isaac, but do they think that the world resolves around them and that we're sitting here just dying for the opportunity to be their unpaid personal servant? If you ask a friend to help you move, you tell him where you are moving from, you don't say "I'm in the phone book, look me up, I'm too lazy to tell you my address." Well, when asking *total strangers* to debug your code, you tell them what errors you are getting, you don't expect them to work it out for themselves. -- Steven From oscar.j.benjamin at gmail.com Tue Nov 20 03:24:06 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 20 Nov 2012 02:24:06 +0000 Subject: [Tutor] New to Python - simple question In-Reply-To: References: Message-ID: On 18 November 2012 14:07, Unaiza Ahsan wrote: > Hi all, > > > The function histogram is supposed to come from the numpy module; at > > least that's the case on my computer (I have numpy 1.6.2 for Python > 2.7): > >>>> from numpy import * > >>>> histogram > > > Maybe something is wrong with Unaiza's version of numpy. > > > Kal > > Yes it's supposed to come from numpy. In imtools.py, the following line is > there: > from numpy import * > > But I'm still getting the error. Since I'm a beginner in Python, I'm not at > all sure what's wrong here. I've checked and I also have a histogram function in my numpy module so I don't understand what the problem is. What would make it possible for us to help you, Unaiza, is if you provide a short piece of code that demonstrates the problem you are having. Perhaps you could just post the whole of the code you are using but if you are able to shorten it while still demonstrating the problem then that is better. Reading the link below will help you to seek help from others. In particular I don't have enough information to check if your code would work on my computer or not, so it's difficult for me to help you right now: http://sscce.org/ The ideal thing would be if you could make a single Python script that shows the problem you are having. If that is not possible then please provide complete code and also as much as possible information about how you are running your script, what folder it's in and what other modules are in the folder and so on (more information is usually better). Oscar From pedrooconnell at gmail.com Tue Nov 20 04:43:12 2012 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Tue, 20 Nov 2012 16:43:12 +1300 Subject: [Tutor] How to load python code only after program startup? Message-ID: Hi I use a compositing program called Nuke which loads my custom modules on start up. So if I have an error in my python code somewhere, Nuke won't open and it throws a typical error which is easy enough to fix. The problem I am running into is that when others on my network are using an older version of Nuke, some of my code causes their older version to not open. For example, recently I started using gnuplot.py for graphical feed back which the older version of Nuke doesn't like. So my question is: What is the best way to wrap all my custom code so that it isn't read on startup, but rather only after I invoke a "loadMyCustomModules.py" module. Help please:)! Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbjaved at gmail.com Tue Nov 20 05:30:55 2012 From: sbjaved at gmail.com (Saad Javed) Date: Tue, 20 Nov 2012 09:30:55 +0500 Subject: [Tutor] sending email via smtplib In-Reply-To: References: Message-ID: Using port 25 with SMTP_SSL gives: Traceback (most recent call last): File "sendemail.py", line 22, in smtp = smtplib.SMTP_SSL(smtp_srv, 25) File "/usr/lib/python2.7/smtplib.py", line 776, in __init__ SMTP.__init__(self, host, port, local_hostname, timeout) File "/usr/lib/python2.7/smtplib.py", line 249, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python2.7/smtplib.py", line 309, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python2.7/smtplib.py", line 782, in _get_socket new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile) File "/usr/lib/python2.7/ssl.py", line 381, in wrap_socket ciphers=ciphers) File "/usr/lib/python2.7/ssl.py", line 143, in __init__ self.do_handshake() File "/usr/lib/python2.7/ssl.py", line 305, in do_handshake self._sslobj.do_handshake() socket.error: [Errno 104] Connection reset by peer -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Nov 20 10:30:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 20 Nov 2012 20:30:34 +1100 Subject: [Tutor] How to load python code only after program startup? In-Reply-To: References: Message-ID: <50AB4DBA.8050801@pearwood.info> On 20/11/12 14:43, Pete O'Connell wrote: > Hi I use a compositing program called Nuke which loads my custom modules on > start up. So if I have an error in my python code somewhere, Nuke won't > open and it throws a typical error which is easy enough to fix. > The problem I am running into is that when others on my network are using > an older version of Nuke, some of my code causes their older version to not > open. For example, recently I started using gnuplot.py for graphical feed > back which the older version of Nuke doesn't like. > So my question is: > What is the best way to wrap all my custom code so that it isn't read on > startup, but rather only after I invoke a "loadMyCustomModules.py" module. Put it in a module "loadMyCustomModules.py" instead of whatever place Nuke expects to find it. What is Nuke? What exactly does it do? Where does it expect to find your modules? What you are asking is really a question about Nuke, not Python. Can you update the other versions of Nuke? Or tell it to be more forgiving of errors? Or less aggressive about loading things automatically? -- Steven From eryksun at gmail.com Tue Nov 20 11:14:47 2012 From: eryksun at gmail.com (eryksun) Date: Tue, 20 Nov 2012 05:14:47 -0500 Subject: [Tutor] How to load python code only after program startup? In-Reply-To: References: Message-ID: On Mon, Nov 19, 2012 at 10:43 PM, Pete O'Connell wrote: > Hi I use a compositing program called Nuke which loads my custom modules on > start up. So if I have an error in my python code somewhere, Nuke won't open > and it throws a typical error which is easy enough to fix. > The problem I am running into is that when others on my network are using an > older version of Nuke, some of my code causes their older version to not > open. For example, recently I started using gnuplot.py for graphical feed > back which the older version of Nuke doesn't like. > So my question is: > What is the best way to wrap all my custom code so that it isn't read on > startup, but rather only after I invoke a "loadMyCustomModules.py" module. I found the following in the docs: http://docs.thefoundry.co.uk/nuke/63/pythondevguide/startup.html Can you add your plugins via ~/.nuke/init.py? From ramit.prasad at jpmorgan.com Tue Nov 20 19:29:22 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 20 Nov 2012 18:29:22 +0000 Subject: [Tutor] pyXML i Python2.6 In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474167BB1D3@SCACMX008.exchad.jpmchase.net> Sreenivasulu wrote: > > Hi, > > Am unable to install pyXML in Ubuntu usig python2.6 > > Could you please help me > > Regards, > Sreenu Since you do not provide a link I am guessing you are referring to the very outdated package. You use the ElementTree class or the reputed third party module lxml. The ElementTree class is in the Python 2.6 standard library at xml.etree.ElementTree.ElementTree. You can try modifying the pyXML source (seems like a small change), but I do not recommend this approach. http://stackoverflow.com/questions/4953600/pyxml-on-ubuntu ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From chigga101 at gmail.com Tue Nov 20 23:05:31 2012 From: chigga101 at gmail.com (Matthew Ngaha) Date: Tue, 20 Nov 2012 22:05:31 +0000 Subject: [Tutor] help In-Reply-To: References: Message-ID: > Traceback (most recent call last): > File "Match finder GUI.py", line 87, in ? > app = Application(root) > File "\Match finder GUI.py", line 23, in __init__ > self.create_widgets() > File "Match finder GUI.py", line 61, in create_widgets > self.submit_bttn = Button(self, text = "Submit", command = self.reveal) > AttributeError: Application instance has no attribute 'reveal' > > i only know really basic tkinter, but i think the error is looking for a method called reveal(). other than your __init__() and create_widgets() methods, i only see an update() method. I think your update method should be named reveal? From ashish.makani at gmail.com Wed Nov 21 08:54:51 2012 From: ashish.makani at gmail.com (ashish makani) Date: Wed, 21 Nov 2012 13:24:51 +0530 Subject: [Tutor] Creating a torrent file & associated tracker through a django web app Message-ID: Hi Tutor folks I am trying to achieve the following : The user should log into a web app, select a file & the web app should generate a .torrent file & a private tracker(http://IP_ADDRESS:PORT_NUMBER/announce) for that .torrent file. Basically, i want to programmatically create a .torrent file, on the server side. I found two libraries mktorrent[1] & py3createtorrent [2], but i need help with how to create a torrent from a django web app. Any suggestions for django modules or libraries which can do this ? Any suggestions/pointers/ideas/links will be greatly appreciated Thanks a ton, cheers, ashish 1. http://mktorrent.sourceforge.net/ 2. http://www.robertnitsch.de/projects/py3createtorrent -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Wed Nov 21 11:23:24 2012 From: timomlists at gmail.com (Timo) Date: Wed, 21 Nov 2012 11:23:24 +0100 Subject: [Tutor] Creating a torrent file & associated tracker through a django web app In-Reply-To: References: Message-ID: <50ACAB9C.1020809@gmail.com> Op 21-11-12 08:54, ashish makani schreef: > > Hi Tutor folks > > I am trying to achieve the following : > > The user should log into a web app, select a file & the web app should > generate a .torrent file & a private > tracker(http://IP_ADDRESS:PORT_NUMBER/announce) for that .torrent file. > > Basically, i want to programmatically create a .torrent file, on the > server side. > > I found two libraries mktorrent[1] & py3createtorrent [2], but i need > help with how to create a torrent from a django web app. > > Any suggestions for django modules or libraries which can do this ? > You don't need Django specific modules, just use the ones you linked and install them on your server. It doesn't matter if you call it from a script on your desktop or a Django webapp. Looking at the example on Wikipedia [1], it's not hard to create it manually. It even looks like a JSON file, you'll just need a way to bencode the data. Timo [1] http://en.wikipedia.org/wiki/Torrent_file#Single_file > Any suggestions/pointers/ideas/links will be greatly appreciated > > Thanks a ton, > > cheers, > > ashish > > 1. http://mktorrent.sourceforge.net/ > 2. http://www.robertnitsch.de/projects/py3createtorrent > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From ashish.makani at gmail.com Wed Nov 21 11:57:26 2012 From: ashish.makani at gmail.com (ashish makani) Date: Wed, 21 Nov 2012 16:27:26 +0530 Subject: [Tutor] Creating a torrent file & associated tracker through a django web app In-Reply-To: <50ACAB9C.1020809@gmail.com> References: <50ACAB9C.1020809@gmail.com> Message-ID: Clarifying query inline . On Wed, Nov 21, 2012 at 3:53 PM, Timo wrote: > Op 21-11-12 08:54, ashish makani schreef: > > >> Hi Tutor folks >> >> I am trying to achieve the following : >> >> The user should log into a web app, select a file & the web app should >> generate a .torrent file & a private tracker(http://IP_ADDRESS >> :**PORT_NUMBER/announce) for that .torrent file. >> >> Basically, i want to programmatically create a .torrent file, on the >> server side. >> >> I found two libraries mktorrent[1] & py3createtorrent [2], but i need >> help with how to create a torrent from a django web app. >> >> Any suggestions for django modules or libraries which can do this ? >> >> You don't need Django specific modules, just use the ones you linked and > install them on your server. It doesn't matter if you call it from a script > on your desktop or a Django webapp. > Looking at the example on Wikipedia [1], it's not hard to create it > manually. It even looks like a JSON file, you'll just need a way to bencode > the data. > > Timo > Thanks a ton Timo for your prompt reply. I am a django newbie, so can you please clarify the following for me : I can create a torrent using py3createtorrent locally, but am unable to figure how it will work via a django web app. To make it work locally, i specified the local location of the folder, i wanted to create a torrent for. In the web app scenario, the user selects the content present on the user's local machine, after that, how do i use py3createtorrent to create a torrent on the server end, since the content is not present on the server . > > [1] http://en.wikipedia.org/wiki/**Torrent_file#Single_file > > Any suggestions/pointers/ideas/**links will be greatly appreciated >> >> Thanks a ton, >> >> cheers, >> >> ashish >> >> 1. http://mktorrent.sourceforge.**net/ >> 2. http://www.robertnitsch.de/**projects/py3createtorrent >> >> >> >> ______________________________**_________________ >> 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 dfjennings at gmail.com Wed Nov 21 14:50:37 2012 From: dfjennings at gmail.com (Don Jennings) Date: Wed, 21 Nov 2012 08:50:37 -0500 Subject: [Tutor] Tutor Digest, Vol 105, Issue 55 In-Reply-To: References: Message-ID: On Nov 21, 2012, at 5:57 AM, tutor-request at python.org wrote: > On Wed, Nov 21, 2012 at 3:53 PM, Timo wrote: > > > I can create a torrent using py3createtorrent locally, but am unable to > figure how it will work via a django web app. > > To make it work locally, i specified the local location of the folder, i > wanted to create a torrent for. > > In the web app scenario, the user selects the content present on the user's > local machine, > after that, how do i use py3createtorrent to create a torrent on the server > end, since the content is not present on the server . I am pretty sure you've answered your own question: the content has to be on the server. Basically, after the user selects the content on their local machine, upload it to the server, then process it from there. Take care, Don -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at peterodoherty.net Thu Nov 22 13:55:01 2012 From: mail at peterodoherty.net (Peter O'Doherty) Date: Thu, 22 Nov 2012 13:55:01 +0100 Subject: [Tutor] Beginner's question Message-ID: <50AE20A5.7070800@peterodoherty.net> Hi list, Firstly, apologies for the low-level nature of this question - it's really quite basic but I don't seem to be able to solve it. I need to write a program that examines 3 variables x, y, z, and prints the largest odd number. I've tried all sorts of variations and this is the current version: x, y, z = 26, 15, 20 if x > y and x > z and x%2 != 0: print 'x is largest and odd' elif y > x and y > z and y%2 != 0: print 'y is largest and odd' elif z > x and z > y and z%2 != 0: print 'z is largest and odd' else: print 'no odd' A solution should be possible using only the simple operators and keywords above, no functions, lists or any other form of iteration. (It's from p. 16 of Introduction to Computation and Programming Using Python, and no, it's not "homework"!) Many thanks, Peter From mail at peterodoherty.net Thu Nov 22 14:14:08 2012 From: mail at peterodoherty.net (Peter O'Doherty) Date: Thu, 22 Nov 2012 14:14:08 +0100 Subject: [Tutor] Beginner's question In-Reply-To: References: <50AE20A5.7070800@peterodoherty.net> Message-ID: <50AE2520.5070001@peterodoherty.net> Hi Varun, Thanks for your reply. I agree the problem is logic - but how can one inspect one number using if x%2 == 0 and then compare it to two other numbers which should at the same time be checked for "oddness", just using the basic constructs? Thanks, Peter On 11/22/2012 02:06 PM, Varun Nagpal wrote: > Hi Peter, > > The reason why your program is not behaving as it should is not > Pythonic but rather logic. > > Instead of giving away the code, I would suggest you revisit the 'and' > conditions. > > The program should print the largest odd number i.e. the number which > is largest among all odd numbers. > Instead you are printing the number which is largest AND odd. > > -- > Varun > > > On Thu, Nov 22, 2012 at 6:25 PM, Peter O'Doherty > > wrote: > > Hi list, > Firstly, apologies for the low-level nature of this question - > it's really quite basic but I don't seem to be able to solve it. > > I need to write a program that examines 3 variables x, y, z, and > prints the largest odd number. I've tried all sorts of variations > and this is the current version: > > x, y, z = 26, 15, 20 > > if x > y and x > z and x%2 != 0: > print 'x is largest and odd' > elif y > x and y > z and y%2 != 0: > print 'y is largest and odd' > elif z > x and z > y and z%2 != 0: > print 'z is largest and odd' > else: > print 'no odd' > > > A solution should be possible using only the simple operators and > keywords above, no functions, lists or any other form of > iteration. (It's from p. 16 of Introduction to Computation and > Programming Using Python, and no, it's not "homework"!) > > Many thanks, > Peter > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- //============================= -> Peter O'Doherty -> http://www.peterodoherty.net -> mail at peterodoherty.net -> https://joindiaspora.com/people/70716 //============================= -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Thu Nov 22 15:17:08 2012 From: wprins at gmail.com (Walter Prins) Date: Thu, 22 Nov 2012 14:17:08 +0000 Subject: [Tutor] Beginner's question In-Reply-To: <50AE20A5.7070800@peterodoherty.net> References: <50AE20A5.7070800@peterodoherty.net> Message-ID: Hi Peter, On 22 November 2012 12:55, Peter O'Doherty wrote: > Hi list, > Firstly, apologies for the low-level nature of this question - it's really > quite basic but I don't seem to be able to solve it. > > I need to write a program that examines 3 variables x, y, z, and prints > the largest odd number. I've tried all sorts of variations and this is the > current version: > > x, y, z = 26, 15, 20 > > if x > y and x > z and x%2 != 0: > print 'x is largest and odd' > elif y > x and y > z and y%2 != 0: > print 'y is largest and odd' > elif z > x and z > y and z%2 != 0: > print 'z is largest and odd' > else: > print 'no odd' > The key logical mistake you make is that by your current logic the *smallest* number can never be the largest odd number, which is obviously false as in your example. Break the problem down (divide and conquer). Suppose I gave you only 2 numbers, and you had to say which of the 2 numbers were the largest odd, what would be the possible outcomes and what would the the solution be? (Hint, both can be odd, only x can be odd, only y can be odd, or neither can be odd.) Once you have that answer, then repeat the exact same solution for the first 2 numbers and apply to the answer from x&y and and the remaining z. The result from that is tells you the largest odd number from all 3. (Aside, your question states to print the largest odd number, which I interpret to mean the value, not the name of the variable holding the value. ) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at peterodoherty.net Thu Nov 22 15:56:09 2012 From: mail at peterodoherty.net (Peter O'Doherty) Date: Thu, 22 Nov 2012 15:56:09 +0100 Subject: [Tutor] Beginner's question In-Reply-To: References: <50AE20A5.7070800@peterodoherty.net> Message-ID: <50AE3D09.3040103@peterodoherty.net> On 11/22/2012 03:17 PM, Walter Prins wrote: > Hi Peter, > > > On 22 November 2012 12:55, Peter O'Doherty > wrote: > > Hi list, > Firstly, apologies for the low-level nature of this question - > it's really quite basic but I don't seem to be able to solve it. > > I need to write a program that examines 3 variables x, y, z, and > prints the largest odd number. I've tried all sorts of variations > and this is the current version: > > x, y, z = 26, 15, 20 > > if x > y and x > z and x%2 != 0: > print 'x is largest and odd' > elif y > x and y > z and y%2 != 0: > print 'y is largest and odd' > elif z > x and z > y and z%2 != 0: > print 'z is largest and odd' > else: > print 'no odd' > > > The key logical mistake you make is that by your current logic the > *smallest* number can never be the largest odd number, which is > obviously false as in your example. > > Break the problem down (divide and conquer). Suppose I gave you only > 2 numbers, and you had to say which of the 2 numbers were the largest > odd, what would be the possible outcomes and what would the the > solution be? (Hint, both can be odd, only x can be odd, only y can be > odd, or neither can be odd.) Once you have that answer, then repeat > the exact same solution for the first 2 numbers and apply to the > answer from x&y and and the remaining z. The result from that is > tells you the largest odd number from all 3. (Aside, your question > states to print the largest odd number, which I interpret to mean the > value, not the name of the variable holding the value. ) > > Walter Thanks Walter. This code appears to work although it's very cumbersome. Is there a better way to do it? x, y, z = 6, 23, 16 if x%2 != 0 and y%2 !=0: if x > y: ans = x else: ans = y elif x%2 !=0 and y%2 == 0: ans = x else: ans = y if ans%2 != 0 and z%2 !=0: if ans > z: ans = ans else: ans = z elif ans%2 !=0 and z%2 == 0: ans = ans else: ans = z print str(ans) + ' is largest odd' Regards, Peter -- //============================= -> Peter O'Doherty -> http://www.peterodoherty.net -> mail at peterodoherty.net -> https://joindiaspora.com/people/70716 //============================= -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Thu Nov 22 16:02:20 2012 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 22 Nov 2012 15:02:20 +0000 Subject: [Tutor] Beginner's question In-Reply-To: <50AE20A5.7070800@peterodoherty.net> References: <50AE20A5.7070800@peterodoherty.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> Peter O'Doherty wrote: > > Hi list, > Firstly, apologies for the low-level nature of this question - it's > really quite basic but I don't seem to be able to solve it. > > I need to write a program that examines 3 variables x, y, z, and prints > the largest odd number. I've tried all sorts of variations and this is > the current version: > > x, y, z = 26, 15, 20 > > if x > y and x > z and x%2 != 0: > print 'x is largest and odd' > elif y > x and y > z and y%2 != 0: > print 'y is largest and odd' > elif z > x and z > y and z%2 != 0: > print 'z is largest and odd' > else: > print 'no odd' > > > A solution should be possible using only the simple operators and > keywords above, no functions, lists or any other form of iteration. > (It's from p. 16 of Introduction to Computation and Programming Using > Python, and no, it's not "homework"!) > The "smart" solution is eluding me so my inelegant solution would figure out what is odd for each x,y, and z. Then compare only looking at values that are odd. Your current if statement only works if all values are odd, but not if the largest value is even and the middle (or low) value is odd. The following code snippets should give you an idea how to create the if statement so that it works correctly useX = x % 2 # 1 is equivalent to True if useX and ( ( useY and x > y ) or not useY ) # and for z: print 'X-izard, use largest odd value attack!', x ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From joel.goldstick at gmail.com Thu Nov 22 16:14:16 2012 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 22 Nov 2012 10:14:16 -0500 Subject: [Tutor] Beginner's question In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> Message-ID: On Thu, Nov 22, 2012 at 10:02 AM, Prasad, Ramit wrote: > Peter O'Doherty wrote: > > > > Hi list, > > Firstly, apologies for the low-level nature of this question - it's > > really quite basic but I don't seem to be able to solve it. > > > > I need to write a program that examines 3 variables x, y, z, and prints > > the largest odd number. I've tried all sorts of variations and this is > > the current version: > > > > x, y, z = 26, 15, 20 > > > > if x > y and x > z and x%2 != 0: > > print 'x is largest and odd' > > elif y > x and y > z and y%2 != 0: > > print 'y is largest and odd' > > elif z > x and z > y and z%2 != 0: > > print 'z is largest and odd' > > else: > > print 'no odd' > > > > > > A solution should be possible using only the simple operators and > > keywords above, no functions, lists or any other form of iteration. > > (It's from p. 16 of Introduction to Computation and Programming Using > > Python, and no, it's not "homework"!) > > > > The "smart" solution is eluding me so my inelegant solution would > figure out what is odd for each x,y, and z. Then compare only looking > at values that are odd. Your current if statement only works if > all values are odd, but not if the largest value is even and the > middle (or low) value is odd. The following code snippets should > give you an idea how to create the if statement so that it works > correctly > > useX = x % 2 # 1 is equivalent to True > if useX and ( ( useY and x > y ) or not useY ) # and for z: > print 'X-izard, use largest odd value attack!', x > > > ~Ramit > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Oops. I sent this to Ramit, not the list. Sorry Ramit Here is another idea: x, y, z = 26, 15, 20 largest = None if x %2: largest = x if y % 2: if y > largest: largest = y if z % 2: if z > largest: largest = z; if Largest: print "largest value is", largest else: print "no odd values" untested -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From pasokan at talentsprint.com Thu Nov 22 16:18:25 2012 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 22 Nov 2012 20:48:25 +0530 Subject: [Tutor] Beginner's question In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> Message-ID: How about this? # Assumption x, y, z are all > 0 x, y, z = a = x * (x % 2) b = y * (y % 2) c = z * (z % 2) big = a if big < b: big = b if big < c big = c if big == 0: print "No odd number" else: print big, "is biggest odd number" Asokan Pichai If a language is designed for non-programmers, soon only non-programs get written in it. --- Anonymouse -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Thu Nov 22 16:49:12 2012 From: d at davea.name (Dave Angel) Date: Thu, 22 Nov 2012 10:49:12 -0500 Subject: [Tutor] Beginner's question In-Reply-To: References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> Message-ID: <50AE4978.1080309@davea.name> On 11/22/2012 10:14 AM, Joel Goldstick wrote: >> > Peter O'Doherty wrote: >>> > > >>> < snip > >>> > > I need to write a program that examines 3 variables x, y, z, and prints >>> > > the largest odd number. I've tried all sorts of variations and this is >>> > > the current version: >>> > > > x, y, z = 26, 15, 20 > > largest = None > if x %2: > largest = x > if y % 2: > if y > largest: > largest = y > if z % 2: > if z > largest: > largest = z; > > if Largest: > print "largest value is", largest > else: > print "no odd values" > This one first gets into trouble if x is even and y is odd, because if tries to compare y with None, which is basically an undefined ordered comparison (and illegal in Python3, I believe). The flag value needs to be an int, or at least numeric. How about: x, y, z = 26, 15, 20 if x%2 == y%2 == z%2 == 0: print "No odd values" else: if x%2==0: x = y if x%2==0: x = y #now x is odd if y%2==0: y = x if z%2==0: z = x #at this point, they're all odd and we just want the largest one if x < y: x, y = y,x if x < z: x = z print "largest odd value is", x With the caveat that x, y, and z may get modified on their way through. I doubt if that really violates the problem statement, however. I didn't test this with all 120 cases, just with the data supplied. -- DaveA From oscar.j.benjamin at gmail.com Thu Nov 22 20:31:58 2012 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 22 Nov 2012 19:31:58 +0000 Subject: [Tutor] Beginner's question In-Reply-To: <50AE20A5.7070800@peterodoherty.net> References: <50AE20A5.7070800@peterodoherty.net> Message-ID: On 22 November 2012 12:55, Peter O'Doherty wrote: > Hi list, > Firstly, apologies for the low-level nature of this question - it's really > quite basic but I don't seem to be able to solve it. > > I need to write a program that examines 3 variables x, y, z, and prints the > largest odd number. I've tried all sorts of variations and this is the > current version: > > x, y, z = 26, 15, 20 > > if x > y and x > z and x%2 != 0: > print 'x is largest and odd' > elif y > x and y > z and y%2 != 0: > print 'y is largest and odd' > elif z > x and z > y and z%2 != 0: > print 'z is largest and odd' > else: > print 'no odd' > > > A solution should be possible using only the simple operators and keywords > above, no functions, lists or any other form of iteration. (It's from p. 16 > of Introduction to Computation and Programming Using Python, and no, it's > not "homework"!) x, y, z = 13, 14, 15 largest_odd = None if x % 2: largest_odd = x if y % 2 and y > largest_odd: largest_odd = y if z % 2 and z > largest_odd: largest_odd = z if largest_odd is None: print('No odd numbers!') else: print('Largest odd number is %i' % largest_odd) The code above is just an explicit expansion of what happens if you solve this problem the normal way (using iteration): # ValueError when there are no odd numbers largest_odd = max(v for v in (x, y, z) if v % 2) Oscar From eryksun at gmail.com Thu Nov 22 20:50:39 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 22 Nov 2012 14:50:39 -0500 Subject: [Tutor] Beginner's question In-Reply-To: <50AE4978.1080309@davea.name> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> Message-ID: On Thu, Nov 22, 2012 at 10:49 AM, Dave Angel wrote: > >> x, y, z = 26, 15, 20 >> >> largest = None >> if x %2: >> largest = x >> if y % 2: >> if y > largest: >> largest = y >> if z % 2: >> if z > largest: >> largest = z; >> >> if Largest: >> print "largest value is", largest >> else: >> print "no odd values" >> > > This one first gets into trouble if x is even and y is odd, because if > tries to compare y with None, which is basically an undefined ordered > comparison (and illegal in Python3, I believe). The flag value needs to > be an int, or at least numeric. Yes, comparing an int to None raises a TypeError in Python 3, but it is 'defined' in 2.x, for what it's worth. Since NoneType lacks tp_richcompare (__lt__, __gt__, etc) NoneType lacks tp_compare (__cmp__) int/long lack tp_richcompare for a swapped operation int/long tp_compare isn't _PyObject_SlotCompare None can't be coerced (__coerce__) to an int/long the comparison falls through to default_3way_compare, where it's hard coded: /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1; http://hg.python.org/cpython/file/70274d53c1dd/Objects/object.c#l750 If you want a warning for this, start the interpreter with the -3 flag. The first time you try to compare None to a number in your code (except for EQ/NE), you'll get a deprecation warning: >>> None < -1 __main__:1: DeprecationWarning: comparing unequal types not supported in 3.x True Also, "smaller than anything" only applies to the default case, after having exhausted all other avenues. You can make your own type that's 'smaller' than anything, including None: import functools @functools.total_ordering class LT(object): def __eq__(self, other): return isinstance(other, LT) def __lt__(self, other): if isinstance(other, LT): return False return True def max_odd(seq, reduce=functools.reduce): sentry = LT() test = lambda x, y: y if y % 2 and y > x else x result = reduce(test, seq, sentry) if result == sentry: raise ValueError("No odd numbers") return result You can unroll the reduction as a chain of statements as Joel did, if you have to. Just replace "largest = None" with "largest = sentry = LT()". From d at davea.name Thu Nov 22 22:43:12 2012 From: d at davea.name (Dave Angel) Date: Thu, 22 Nov 2012 16:43:12 -0500 Subject: [Tutor] Beginner's question In-Reply-To: References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> Message-ID: <50AE9C70.3000004@davea.name> On 11/22/2012 02:50 PM, eryksun wrote: > On Thu, Nov 22, 2012 at 10:49 AM, Dave Angel wrote: >> >>> >>> >> >> This one first gets into trouble if x is even and y is odd, because if >> tries to compare y with None, which is basically an undefined ordered >> comparison (and illegal in Python3, I believe). The flag value needs to >> be an int, or at least numeric. > > Yes, comparing an int to None raises a TypeError in Python 3, but it > is 'defined' in 2.x, for what it's worth. Since > > NoneType lacks tp_richcompare (__lt__, __gt__, etc) > NoneType lacks tp_compare (__cmp__) > int/long lack tp_richcompare for a swapped operation > int/long tp_compare isn't _PyObject_SlotCompare > None can't be coerced (__coerce__) to an int/long > > the comparison falls through to default_3way_compare, where it's hard coded: > > /* None is smaller than anything */ > if (v == Py_None) > return -1; > if (w == Py_None) > return 1; > > http://hg.python.org/cpython/file/70274d53c1dd/Objects/object.c#l750 > You're looking at a particular implementation of CPython code, while I'm looking at Python's docs. In tha language version 2.x, the result is repeatable, but undefined, deliberately. ++ http://docs.python.org/2/reference/expressions.html ++ Otherwise, objects of different types always compare unequal, and ++ are ordered consistently but arbitrarily. In other words 2 > None will give the same answer each time, for a single run of a script in CPython, but it is unspecified what that answer will be, and may vary by version as well as implementation. -- DaveA From dfjennings at gmail.com Thu Nov 22 23:47:10 2012 From: dfjennings at gmail.com (Don Jennings) Date: Thu, 22 Nov 2012 17:47:10 -0500 Subject: [Tutor] MIT python video [WAS: Re: Hi Don,] In-Reply-To: <3245CBCA99B596439C37EF53E1220BE418C712E5@ITSUSRAGMDGD04.jnj.com> References: <3245CBCA99B596439C37EF53E1220BE418C712E5@ITSUSRAGMDGD04.jnj.com> Message-ID: On Nov 22, 2012, at 8:11 AM, Waters, Mike [ITSCA Non-J&J] wrote: > Hi Don, first thanks for the support on Python, I find the information very helpful. You're welcome. You'll find it even more helpful if you send your questions to the whole python tutor list which I've cc'd :>) > I have been watching the MIT John Gutag and he will highlight a section of code and then go to the? Format ?tab and pick something about the 3 or 4 th line down to remove the data. I have not seen these videos, so I can only guess he's using some kind of IDE perhaps? IDLE maybe? > Why do I not have a Format button?(I am running 2.7 on Win) And since the image is not clear on the screen what is he doing? You'll be happy to find out that the slides are available in pdf format. Go to the main page for the course [1] and choose one of the units in the navigation sidebar on the left. Then you'll see the list of topics. After clicking on one of those, you should find the "Lecture slides" under the "Session Activities" section of the page. Take care, Don [1] http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/Syllabus/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Fri Nov 23 00:49:17 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Nov 2012 10:49:17 +1100 Subject: [Tutor] Beginner's question In-Reply-To: <50AE9C70.3000004@davea.name> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> <50AE9C70.3000004@davea.name> Message-ID: <50AEB9FD.4060203@pearwood.info> On 23/11/12 08:43, Dave Angel wrote: > In other words > 2> None > > will give the same answer each time, for a single run of a script in > CPython, but it is unspecified what that answer will be, and may vary by > version as well as implementation. Correct. The ordering of None has changed at least once in CPython: [steve at ando ~]$ python2.7 -c "print 2 > None" True [steve at ando ~]$ python1.5 -c "print 2 > None" 0 -- Steven From eryksun at gmail.com Fri Nov 23 00:52:15 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 22 Nov 2012 18:52:15 -0500 Subject: [Tutor] Beginner's question In-Reply-To: <50AE9C70.3000004@davea.name> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> <50AE9C70.3000004@davea.name> Message-ID: On Thu, Nov 22, 2012 at 4:43 PM, Dave Angel wrote: > > You're looking at a particular implementation of CPython code, while I'm > looking at Python's docs. In tha language version 2.x, the result is > repeatable, but undefined, deliberately. I wouldn't dispute that. I have no experience with Jython/IronPython to confirm what they do. Also, this ordering for None is unmentioned in PEP 207: http://www.python.org/dev/peps/pep-0207 Nor is it tested in test_richcmp.py. That said, in CPython the ordering hasn't changed since rich comparisons were added in 2.1a (circa 2001): http://hg.python.org/cpython/file/b60831eeab5a/Objects/object.c#l514 Without this exception, comparing to None would use the type name (currently "NoneType", but "None" in v2.1), which I realize is also unspecified in the docs. From eryksun at gmail.com Fri Nov 23 00:57:34 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 22 Nov 2012 18:57:34 -0500 Subject: [Tutor] Beginner's question In-Reply-To: <50AEB9FD.4060203@pearwood.info> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> <50AE9C70.3000004@davea.name> <50AEB9FD.4060203@pearwood.info> Message-ID: On Thu, Nov 22, 2012 at 6:49 PM, Steven D'Aprano wrote: > >> will give the same answer each time, for a single run of a script in >> CPython, but it is unspecified what that answer will be, and may vary by >> version as well as implementation. > > Correct. The ordering of None has changed at least once in CPython: > > > [steve at ando ~]$ python2.7 -c "print 2 > None" > True > [steve at ando ~]$ python1.5 -c "print 2 > None" > 0 LOL... version 1.5. Anyway, there will never be a version 2.8, so the question is really what Jython, IronPython, and other 2.x implementations do. From d at davea.name Fri Nov 23 01:10:13 2012 From: d at davea.name (Dave Angel) Date: Thu, 22 Nov 2012 19:10:13 -0500 Subject: [Tutor] Beginner's question In-Reply-To: References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> <50AE9C70.3000004@davea.name> <50AEB9FD.4060203@pearwood.info> Message-ID: <50AEBEE5.9040106@davea.name> On 11/22/2012 06:57 PM, eryksun wrote: > On Thu, Nov 22, 2012 at 6:49 PM, Steven D'Aprano wrote: >>> will give the same answer each time, for a single run of a script in >>> CPython, but it is unspecified what that answer will be, and may vary by >>> version as well as implementation. >> Correct. The ordering of None has changed at least once in CPython: >> >> >> [steve at ando ~]$ python2.7 -c "print 2 > None" >> True >> [steve at ando ~]$ python1.5 -c "print 2 > None" >> 0 > LOL... version 1.5. Anyway, there will never be a version 2.8, so the > question is really what Jython, IronPython, and other 2.x > implementations do. No, the question is what will Python3000 do. Oh, wait, it's already out, and it's called 3.x Since it's explicitly an error there, it seems good not to write new code using the misfeature. -- DaveA From eryksun at gmail.com Fri Nov 23 01:30:35 2012 From: eryksun at gmail.com (eryksun) Date: Thu, 22 Nov 2012 19:30:35 -0500 Subject: [Tutor] Beginner's question In-Reply-To: <50AEBEE5.9040106@davea.name> References: <50AE20A5.7070800@peterodoherty.net> <5B80DD153D7D744689F57F4FB69AF474167BEF71@SCACMX008.exchad.jpmchase.net> <50AE4978.1080309@davea.name> <50AE9C70.3000004@davea.name> <50AEB9FD.4060203@pearwood.info> <50AEBEE5.9040106@davea.name> Message-ID: On Thu, Nov 22, 2012 at 7:10 PM, Dave Angel wrote: > > No, the question is what will Python3000 do. Oh, wait, it's already > out, and it's called 3.x Since it's explicitly an error there, it seems > good not to write new code using the misfeature. I meant it along the lines of cross-compatibility in 2.x, for which there is a default order defined in the code, but not defined by the docs, as you pointed out to me. My question is whether the default behavior of CPython in this case has been accepted as an implicit spec. In this thread, both Joel and Oscar contributed code that depends on None being less than any number. I've seen it elsewhere, and I suspect it's common. From steve at pearwood.info Fri Nov 23 02:16:43 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 23 Nov 2012 12:16:43 +1100 Subject: [Tutor] Beginner's question In-Reply-To: <50AE3D09.3040103@peterodoherty.net> References: <50AE20A5.7070800@peterodoherty.net> <50AE3D09.3040103@peterodoherty.net> Message-ID: <50AECE7B.5080300@pearwood.info> On 23/11/12 01:56, Peter O'Doherty wrote: > This code appears to work although it's very cumbersome. Is >there a better way to do it? Of course it is cumbersome, that's because of the artificial constraints set on the problem. I quote from your description of the problem: "using only the simple operators and keywords above, no functions, lists or any other form of iteration." This constraint makes the problem cumbersome. Imagine if we needed to do the same thing for a thousand numbers, not just three! The solution you give isn't quite right -- it works for the example given, but not others. There are thirteen cases to consider: 1) none of the numbers are odd; 2) only x is odd; 3) only y is odd; 4) only z is odd; 5) only x is even, and y is largest; 6) only x is even, and z is largest; 7) only y is even, and x is largest; 8) only y is even, and z is largest; 9) only z is even, and x is largest; 10) only z is even, and y is largest; 11) all of the numbers are odd, and x is largest; 12) all of the numbers are odd, and y is largest; 13) all of the numbers are odd, and z is largest. not including cases where two or more numbers are odd and equal since that can be naturally handled. Whatever solution you come up with, it needs to work correctly with all thirteen cases. The code you gave fails on case #1, and possibly others. However, just because there are thirteen different cases to check, doesn't mean your code needs thirteen different branches! Think of the problem slightly differently: Suppose you only had *one* number to check. if x is odd: set the biggest odd number yet seen to x if we haven't seen a biggest odd number yet: print "no biggest odd number seen" otherwise: print the biggest odd number seen Easy, right? Now add a second number: if x is odd: set the biggest odd number yet seen to x if y is odd: if we haven't seen a biggest odd number yet: set the biggest odd number yet seen to y otherwise, we have seen a biggest odd number, so: if y is larger than the biggest odd number yet seen: set the biggest odd number yet seen to y if we haven't seen a biggest odd number yet: print "no biggest odd number seen" otherwise: print the biggest odd number seen Can you extend that to a third number, z? Can you convert that pseudo-code into Python code? Hint: Python doesn't make it easy to check whether a variable exists. The easy way is to set a placeholder value that cannot be mistaken for a legitimate value, and then check whether the variable equals the placeholder. "variable is None" or "variable is not None" are the standard ways to do this. Finally, here is how I would solve the problem for real: try: print max(filter(lambda n: n%2 != 0, (x, y, z))) except ValueError: print ('no largest odd number') You are not expected to understand this! Especially not the mysterious lambda. -- Steven From mail at peterodoherty.net Fri Nov 23 07:39:02 2012 From: mail at peterodoherty.net (Peter O'Doherty) Date: Fri, 23 Nov 2012 07:39:02 +0100 Subject: [Tutor] Beginner's question In-Reply-To: <50AE2520.5070001@peterodoherty.net> References: <50AE20A5.7070800@peterodoherty.net> <50AE2520.5070001@peterodoherty.net> Message-ID: <50AF1A06.7060203@peterodoherty.net> Many, many thanks to all those who replied to my question. I hope the next time I post, it will be with something more advanced. Judging by the volume of replies, is it fair to say that this problem was much too advanced for page 16 of an introductory text? Best wishes, Peter From __peter__ at web.de Fri Nov 23 10:25:52 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Nov 2012 10:25:52 +0100 Subject: [Tutor] Beginner's question References: <50AE20A5.7070800@peterodoherty.net> <50AE3D09.3040103@peterodoherty.net> <50AECE7B.5080300@pearwood.info> Message-ID: Steven D'Aprano wrote: > On 23/11/12 01:56, Peter O'Doherty wrote: > >> This code appears to work although it's very cumbersome. Is >>there a better way to do it? > > > Of course it is cumbersome, that's because of the artificial > constraints set on the problem. I quote from your description Indeed. > Finally, here is how I would solve the problem for real: > > > try: > print max(filter(lambda n: n%2 != 0, (x, y, z))) > except ValueError: > print ('no largest odd number') > > > You are not expected to understand this! Especially not the > mysterious lambda. For completeness here is the version you *are* supposed to understand, right now or "real soon": numbers = x, y, z odds = [n for n in numbers if n % 2] if odds: print("largest odd number:", max(odds)) else: print("no odd numbers") From dfjennings at gmail.com Fri Nov 23 16:02:08 2012 From: dfjennings at gmail.com (Don Jennings) Date: Fri, 23 Nov 2012 10:02:08 -0500 Subject: [Tutor] MIT python video [WAS: Re: Hi Don,] In-Reply-To: <593E2429-2E21-4D5A-AA10-FAB21E7DEC8E@me.com> References: <3245CBCA99B596439C37EF53E1220BE418C712E5@ITSUSRAGMDGD04.jnj.com> <593E2429-2E21-4D5A-AA10-FAB21E7DEC8E@me.com> Message-ID: On Nov 22, 2012, at 9:48 PM, Jan Karel Schreuder wrote: > > > On Nov 22, 2012, at 5:47 PM, Don Jennings wrote: > >> >> On Nov 22, 2012, at 8:11 AM, Waters, Mike [ITSCA Non-J&J] wrote: >> >>> Hi Don, first thanks for the support on Python, I find the information very helpful. >> >> You're welcome. You'll find it even more helpful if you send your questions to the whole python tutor list which I've cc'd :>) >> >>> I have been watching the MIT John Gutag and he will highlight a section of code and then go to the? Format ?tab and pick something about the 3 or 4 th line down to remove the data. >> >> I have not seen these videos, so I can only guess he's using some kind of IDE perhaps? IDLE maybe? >> >>> Why do I not have a Format button?(I am running 2.7 on Win) And since the image is not clear on the screen what is he doing? >> > > Gutag uses Idle Thanks! In case it helps future http://duckduckgo.com searchers, the name is actually "Guttag". Take care, Don -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Fri Nov 23 19:10:28 2012 From: swiftone at swiftone.org (Brett Ritter) Date: Fri, 23 Nov 2012 10:10:28 -0800 Subject: [Tutor] Beginner's question In-Reply-To: <50AF1A06.7060203@peterodoherty.net> References: <50AE20A5.7070800@peterodoherty.net> <50AE2520.5070001@peterodoherty.net> <50AF1A06.7060203@peterodoherty.net> Message-ID: On Thu, Nov 22, 2012 at 10:39 PM, Peter O'Doherty wrote: > Judging by the volume of replies, is it fair to say that this problem was > much too advanced for page 16 of an introductory text? That is a matter of taste. There are two things you need to learn: 1) the syntax of the language 2) how to approach programming problems #1 can be done gradually, #2 necessarily has a "hard" moment. For that, you need a problem that requires you think in programming terms: How can I break this down? What are the different conditions that could break my logic? How do I avoid missing situations? Once you cross that hump, it becomes "easy". Future problems will be hard again, but never to the same degree - once you've internalized the process, it's just a matter of refinement. Myself, I'd prefer to get that hard part over quickly. Up to page 16 obviously taught you enough basic syntax for your initial stab, so I think it was well timed. The important thing is for you to realize that you're learning a thought pattern, like algebra - once you "get it", the rest is merely learning applications and additional rules, but that initial insight requires some mental wrestling that can't really be reduced. If you're worried about the rest of the text (which I'm unfamiliar with) being more hard than enjoyable, I'd recommend continuing to play with this problem. Create variants (lowest POSITIVE even number), learn the typical situations that make it complicated. When someone can give you a problem in that vein and you can write a solution without referring to your previous attempts (or anyone elses), you've crossed the line and are forever changed. From that point forward the best the book (or any programming text) can do is challenge you, it can no longer be "hard". (Disclaimer: certain _concepts_ can once again be hard, such as pointers (not in python), lambdas, closures, etc. These should still be easier than this initial learning step) The bad part is that once you get it, you'll look back and wonder how you considered it hard. The good part is that if you are a programmer at heart, you'll find you love challenges. I think that's part of why you've gotten so many replies - this is an easy problem to understand, quick to provide a solution (right or wrong) for, and the constraints placed on it (just to keep you from getting lost in unfamiliar syntax) make it a mental challenge for us because our first approach is disallowed. Don't be disheartened at the difficulty, and don't fear it being this hard all along. -- Brett Ritter / SwiftOne swiftone at swiftone.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From kbailey at howlermonkey.net Sat Nov 24 04:01:47 2012 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Fri, 23 Nov 2012 22:01:47 -0500 Subject: [Tutor] Beginner's question In-Reply-To: References: <50AE20A5.7070800@peterodoherty.net> <50AE2520.5070001@peterodoherty.net> <50AF1A06.7060203@peterodoherty.net> Message-ID: <50B0389B.4040501@howlermonkey.net> On 11/23/2012 1:10 PM, Brett Ritter wrote: > On Thu, Nov 22, 2012 at 10:39 PM, Peter O'Doherty > > wrote: > > Judging by the volume of replies, is it fair to say that this > problem was much too advanced for page 16 of an introductory text? > > > That is a matter of taste. There are two things you need to learn: > 1) the syntax of the language > 2) how to approach programming problems > > #1 can be done gradually, #2 necessarily has a "hard" moment. For > that, you need a problem that requires you think in programming terms: > How can I break this down? What are the different conditions that > could break my logic? How do I avoid missing situations? > > Once you cross that hump, it becomes "easy". Future problems will be > hard again, but never to the same degree - once you've internalized > the process, it's just a matter of refinement. > > Myself, I'd prefer to get that hard part over quickly. Up to page 16 > obviously taught you enough basic syntax for your initial stab, so I > think it was well timed. The important thing is for you to realize > that you're learning a thought pattern, like algebra - once you "get > it", the rest is merely learning applications and additional rules, > but that initial insight requires some mental wrestling that can't > really be reduced. If you're worried about the rest of the text > (which I'm unfamiliar with) being more hard than enjoyable, I'd > recommend continuing to play with this problem. Create variants > (lowest POSITIVE even number), learn the typical situations that make > it complicated. When someone can give you a problem in that vein and > you can write a solution without referring to your previous attempts > (or anyone elses), you've crossed the line and are forever changed. > From that point forward the best the book (or any programming text) > can do is challenge you, it can no longer be "hard". (Disclaimer: > certain _concepts_ can once again be hard, such as pointers (not in > python), lambdas, closures, etc. These should still be easier than > this initial learning step) > > The bad part is that once you get it, you'll look back and wonder how > you considered it hard. The good part is that if you are a programmer > at heart, you'll find you love challenges. I think that's part of why > you've gotten so many replies - this is an easy problem to understand, > quick to provide a solution (right or wrong) for, and the constraints > placed on it (just to keep you from getting lost in unfamiliar syntax) > make it a mental challenge for us because our first approach is > disallowed. > > Don't be disheartened at the difficulty, and don't fear it being this > hard all along. > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org This being said, prehaps an early chapter if not the first should be how to think like a programmer. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- -Shaboom. Kirk Bailey CEO, Freehold Marketing LLC http://www.OneBuckHosting.com/ Fnord! -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdragon1984 at gmail.com Sun Nov 25 04:16:55 2012 From: sdragon1984 at gmail.com (Nathan) Date: Sat, 24 Nov 2012 22:16:55 -0500 Subject: [Tutor] Dynamic TKinter widgets? Message-ID: I'm working on a simple Tarot reading program in Python 2.7, and I'm having a bit of trouble with some GUI abstract. (Sorry, no code in here.) As of right now, all of the logic is working, and I can generate Tarot spreads that tell me, in text, the role of each card "position", and what card is in that position. For example, if I were to use a simple three-card past/present/future spread, the output would be something like: Past: Prince of Swords Present: The Hermit Future: Ten of Disks What I'm trying to do now is add support for the card images. the problem is, the program supports multiple types of spreads (two, so far, are selectable), and they use different numbers of cards. It looks like I need a variable number of widgets to display something like this. I'm not entirely sure how I would handle something like that. Right now, though, I do have two ideas that I would like to run by you guys. The first is to use one text widget-- as opposed to the one label widget I'm currently using-- and embed the images where the card names would be. I would have to try out some demos first, though, to see if I can otherwise use text widgets just as label widgets. The other idea, which seems much more cumbersome, is to create a dummy frame widget, then a frame widget designed specifically for each type of spread. The user selects the spread they want to use (Celtic Cross), and the associated frame gets placed on the GUI. What do you guys think? Is there a better way to deal (ha!) with this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdragon1984 at gmail.com Sun Nov 25 04:37:52 2012 From: sdragon1984 at gmail.com (Nathan) Date: Sat, 24 Nov 2012 22:37:52 -0500 Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: <201211242133.26264.cfuller084@thinkingplanet.net> References: <201211242133.26264.cfuller084@thinkingplanet.net> Message-ID: I did consider using a canvas widget, but it looks a bit intimidating right now. I'm sure I'll get to it eventually. I don't think I've heard of Pmw. I take it it's a module that has a "Notebook" widget class? On Nov 24, 2012 10:33 PM, "Chris Fuller" wrote: > On Saturday 24 November 2012, Nathan wrote: > > I'm working on a simple Tarot reading program in Python 2.7, and I'm > having > > a bit of trouble with some GUI abstract. (Sorry, no code in here.) > > > > As of right now, all of the logic is working, and I can generate Tarot > > spreads that tell me, in text, the role of each card "position", and what > > card is in that position. For example, if I were to use a simple > three-card > > past/present/future spread, the output would be something like: > > > > Past: Prince of Swords > > Present: The Hermit > > Future: Ten of Disks > > > > What I'm trying to do now is add support for the card images. the problem > > is, the program supports multiple types of spreads (two, so far, are > > selectable), and they use different numbers of cards. It looks like I > need > > a variable number of widgets to display something like this. I'm not > > entirely sure how I would handle something like that. > > > > Right now, though, I do have two ideas that I would like to run by you > > guys. > > > > The first is to use one text widget-- as opposed to the one label widget > > I'm currently using-- and embed the images where the card names would > be. I > > would have to try out some demos first, though, to see if I can otherwise > > use text widgets just as label widgets. > > > > The other idea, which seems much more cumbersome, is to create a dummy > > frame widget, then a frame widget designed specifically for each type of > > spread. The user selects the spread they want to use (Celtic Cross), and > > the associated frame gets placed on the GUI. > > > > What do you guys think? Is there a better way to deal (ha!) with this? > > I think the usual procedure with something like this is a single Canvas > widget. > > You could also use a Notebook with tabs disabled from Pmw or the like to > implement multiple alternate Frames. As you say, more cumbersome. > > Cheers > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Sun Nov 25 04:33:26 2012 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 24 Nov 2012 21:33:26 -0600 Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: References: Message-ID: <201211242133.26264.cfuller084@thinkingplanet.net> On Saturday 24 November 2012, Nathan wrote: > I'm working on a simple Tarot reading program in Python 2.7, and I'm having > a bit of trouble with some GUI abstract. (Sorry, no code in here.) > > As of right now, all of the logic is working, and I can generate Tarot > spreads that tell me, in text, the role of each card "position", and what > card is in that position. For example, if I were to use a simple three-card > past/present/future spread, the output would be something like: > > Past: Prince of Swords > Present: The Hermit > Future: Ten of Disks > > What I'm trying to do now is add support for the card images. the problem > is, the program supports multiple types of spreads (two, so far, are > selectable), and they use different numbers of cards. It looks like I need > a variable number of widgets to display something like this. I'm not > entirely sure how I would handle something like that. > > Right now, though, I do have two ideas that I would like to run by you > guys. > > The first is to use one text widget-- as opposed to the one label widget > I'm currently using-- and embed the images where the card names would be. I > would have to try out some demos first, though, to see if I can otherwise > use text widgets just as label widgets. > > The other idea, which seems much more cumbersome, is to create a dummy > frame widget, then a frame widget designed specifically for each type of > spread. The user selects the spread they want to use (Celtic Cross), and > the associated frame gets placed on the GUI. > > What do you guys think? Is there a better way to deal (ha!) with this? I think the usual procedure with something like this is a single Canvas widget. You could also use a Notebook with tabs disabled from Pmw or the like to implement multiple alternate Frames. As you say, more cumbersome. Cheers From cfuller084 at thinkingplanet.net Sun Nov 25 04:55:29 2012 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Sat, 24 Nov 2012 21:55:29 -0600 Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: References: <201211242133.26264.cfuller084@thinkingplanet.net> Message-ID: <201211242155.29689.cfuller084@thinkingplanet.net> On Saturday 24 November 2012, Nathan wrote: > I did consider using a canvas widget, but it looks a bit intimidating right > now. I'm sure I'll get to it eventually. > > I don't think I've heard of Pmw. I take it it's a module that has a > "Notebook" widget class? > On Nov 24, 2012 10:33 PM, "Chris Fuller" > > wrote: > > On Saturday 24 November 2012, Nathan wrote: > > > I'm working on a simple Tarot reading program in Python 2.7, and I'm > > > > having > > > > > a bit of trouble with some GUI abstract. (Sorry, no code in here.) > > > > > > As of right now, all of the logic is working, and I can generate Tarot > > > spreads that tell me, in text, the role of each card "position", and > > > what card is in that position. For example, if I were to use a simple > > > > three-card > > > > > past/present/future spread, the output would be something like: > > > > > > Past: Prince of Swords > > > Present: The Hermit > > > Future: Ten of Disks > > > > > > What I'm trying to do now is add support for the card images. the > > > problem is, the program supports multiple types of spreads (two, so > > > far, are selectable), and they use different numbers of cards. It > > > looks like I > > > > need > > > > > a variable number of widgets to display something like this. I'm not > > > entirely sure how I would handle something like that. > > > > > > Right now, though, I do have two ideas that I would like to run by you > > > guys. > > > > > > The first is to use one text widget-- as opposed to the one label > > > widget I'm currently using-- and embed the images where the card names > > > would > > > > be. I > > > > > would have to try out some demos first, though, to see if I can > > > otherwise use text widgets just as label widgets. > > > > > > The other idea, which seems much more cumbersome, is to create a dummy > > > frame widget, then a frame widget designed specifically for each type > > > of spread. The user selects the spread they want to use (Celtic > > > Cross), and the associated frame gets placed on the GUI. > > > > > > What do you guys think? Is there a better way to deal (ha!) with this? > > > > I think the usual procedure with something like this is a single Canvas > > widget. > > > > You could also use a Notebook with tabs disabled from Pmw or the like to > > implement multiple alternate Frames. As you say, more cumbersome. > > > > Cheers Python Megawidgets, http://pmw.sourceforge.net/ I'm pretty sure Tix has something similar, and that's in the Standard Library now, but Pmw is what I'm familiar with. Cheers From sbjaved at gmail.com Sun Nov 25 09:50:16 2012 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 25 Nov 2012 13:50:16 +0500 Subject: [Tutor] stop a loop after precise amount of time Message-ID: import time s = time.time() + 30 running = True while running: if time.time() == s: print 'yes' running = False This stops the loop after 30s but the program uses about 12% cpu. What would be a more efficient way to do this? (p.s. i'm on python 2.7.3) Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Nov 25 10:24:15 2012 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 Nov 2012 09:24:15 +0000 Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: References: Message-ID: On 25/11/12 03:16, Nathan wrote: > What I'm trying to do now is add support for the card images. the > problem is, the program supports multiple types of spreads (two, so far, > are selectable), and they use different numbers of cards. It looks like > I need a variable number of widgets to display something like this. I'm > not entirely sure how I would handle something like that. Tkinter is dynamic by definition. So you just need a loop to add your images in some kind of collection widget. A Canvas or a Frame would seem obvious choices... Just choose your preferred layout manager - simple pack() would work or you could use grid() for more sophisticated shapes. > Right now, though, I do have two ideas that I would like to run by you > guys. > > The first is to use one text widget-- as opposed to the one label widget > I'm currently using-- and embed the images where the card names would > be. I would have to try out some demos first, though, to see if I can > otherwise use text widgets just as label widgets. You can certainly embed images in Text widgets, I'm not sure about Labels, but I think you can. You can also use Buttons. > The other idea, which seems much more cumbersome, is to create a dummy > frame widget, then a frame widget designed specifically for each type of > spread. The user selects the spread they want to use (Celtic Cross), and > the associated frame gets placed on the GUI. That doesn't sound cumbersome to me, it sounds like standard Tkinter practice. Frames are the base object of nearly everything in Tkinter. A Celtic cross pattern could just be an algorithm for positioning things on a grid... So it may simply be a case of having different generator functions for the card locations (a list of tuples?) and selecting a function rather than a Frame. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Nov 25 10:57:34 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 25 Nov 2012 20:57:34 +1100 Subject: [Tutor] stop a loop after precise amount of time In-Reply-To: References: Message-ID: <50B1EB8E.3000603@pearwood.info> On 25/11/12 19:50, Saad Javed wrote: > import time > > s = time.time() + 30 > running = True > while running: > if time.time() == s: > print 'yes' > running = False > > This stops the loop after 30s but the program uses about 12% cpu. What > would be a more efficient way to do this? (p.s. i'm on python 2.7.3) import time time.sleep(30) print "Done sleeping" By the way, if you decide to use a while loop, don't test for time == s exactly. If the timer misses your target by even a billionth of a second, the loop will never end. Better is: stop = time.time() + 30 while time.time() < stop: pass print "Done" but don't do this either, use time.sleep. -- Steven From sbjaved at gmail.com Sun Nov 25 12:01:15 2012 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 25 Nov 2012 16:01:15 +0500 Subject: [Tutor] stop a loop after precise amount of time In-Reply-To: References: Message-ID: time.sleep(30) will pause the program for 30s. I want to the run the program for 30s. Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Sun Nov 25 12:06:54 2012 From: scarolan at gmail.com (Sean Carolan) Date: Sun, 25 Nov 2012 05:06:54 -0600 Subject: [Tutor] Listen for input while performing other tasks Message-ID: I'm working on a python script that runs on a Raspberry Pi. The script detects when hardware buttons are pressed, and then runs functions based on that input. I want to be able to always listen for a button press, no matter what the script is doing at the current moment. When a button press is detected, the script should stop whatever it is doing, and move to the next "mode" or function. So far I've only been able to come up with kludgy implementations with lots of short time.sleep() calls alternating with checks to see whether the buttons were pressed or not. There has to be a cleaner way to do this. Do you have any ideas how to make this work? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbjaved at gmail.com Sun Nov 25 12:17:47 2012 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 25 Nov 2012 16:17:47 +0500 Subject: [Tutor] stop a loop after precise amount of time In-Reply-To: References: Message-ID: import time running = True while running: print 'yes' time.sleep(10) This will print 'yes' after every 10s. I want to print 'yes' for 10s, then quit. Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Nov 25 12:36:39 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 25 Nov 2012 22:36:39 +1100 Subject: [Tutor] stop a loop after precise amount of time In-Reply-To: References: Message-ID: <50B202C7.5000406@pearwood.info> On 25/11/12 22:01, Saad Javed wrote: > time.sleep(30) will pause the program for 30s. I want to the run the > program for 30s. Your first email did not make that clear. Please take more care to explain your question. stop = time.time() + 30 while time.time() < stop: do_something_useful() print "Done" This will not interrupt do_something_useful, it only checks the time at the start of each loop. That's simple and easy and very often is close enough. But if you want to interrupt do_something_useful when 30s is up, that becomes much, much, much harder. See here for an explanation of why it is hard: http://eli.thegreenplace.net/2011/08/22/how-not-to-set-a-timeout-on-a-computation-in-python/ and here for one possible solution: http://pguides.net/python-tutorial/python-timeout-a-function/ -- Steven From __peter__ at web.de Sun Nov 25 12:45:37 2012 From: __peter__ at web.de (Peter Otten) Date: Sun, 25 Nov 2012 12:45:37 +0100 Subject: [Tutor] stop a loop after precise amount of time References: Message-ID: Saad Javed wrote: > import time > > running = True > while running: > print 'yes' > time.sleep(10) > > This will print 'yes' after every 10s. I want to print 'yes' for 10s, then > quit. Then combine the two techniques, the busy waiting loop with sleeping for a shorter amount of time: import time stop_time = time.time() + 10 while time.time() < stop_time: print "yes" time.sleep(.1) print "that's all folks" From steve at pearwood.info Sun Nov 25 13:03:08 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 25 Nov 2012 23:03:08 +1100 Subject: [Tutor] Listen for input while performing other tasks In-Reply-To: References: Message-ID: <50B208FC.8000706@pearwood.info> On 25/11/12 22:06, Sean Carolan wrote: > I'm working on a python script that runs on a Raspberry Pi. The script > detects when hardware buttons are pressed, and then runs functions based on > that input. > > I want to be able to always listen for a button press, no matter what the > script is doing at the current moment. When a button press is detected, > the script should stop whatever it is doing, and move to the next "mode" or > function. > > So far I've only been able to come up with kludgy implementations with lots > of short time.sleep() calls alternating with checks to see whether the > buttons were pressed or not. > > There has to be a cleaner way to do this. Not really. Running code in parallel (the bit of your script doing the work, and the bit of the script listening for a button press) is inherently icky. Even when it is easy, it is only easy because of an incredible amount of work happening in the background hiding the complexity. > Do you have any ideas how to make this work? (1) Use some sort of framework (e.g. a GUI application framework) with a proper event loop. This is likely the only good solution. Tkinter may do do the job. So might pyev: http://code.google.com/p/pyev/ assuming you can get libev running on a Raspberry Pi. (2) Write your own event loop, which will probably need to be in C and will probably be horrible to write and horrible to use. Wait, it may not be that horrible, because you're only interested in reading from the keyboard, which you may be able to do using non-blocking reads. Let me think about this one... (4) Possibly using threads or processes. (5) Since you're probably using Linux on your Raspberry Pi, you can use the signal module to listen for specific signals rather than any arbitrary key press. That might be close enough to solve your problem. Explaining exactly what you are hoping to do might simplify the issue somewhat. -- Steven From steve at pearwood.info Sun Nov 25 13:27:13 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 25 Nov 2012 23:27:13 +1100 Subject: [Tutor] Listen for input while performing other tasks In-Reply-To: References: Message-ID: <50B20EA1.7060004@pearwood.info> On 25/11/12 22:06, Sean Carolan wrote: > I'm working on a python script that runs on a Raspberry Pi. The script > detects when hardware buttons are pressed, and then runs functions based on > that input. Oh I'm sorry, I completely misread what you wrote there. I didn't realise you were talking about hardware buttons, rather than waiting for a key press. Total brain-fart there on my part, sorry about that. [...] > So far I've only been able to come up with kludgy implementations with lots > of short time.sleep() calls alternating with checks to see whether the > buttons were pressed or not. If you show us how you check whether the button is pressed, we may be able to show you how to run that asynchronously. -- Steven From scarolan at gmail.com Sun Nov 25 13:32:44 2012 From: scarolan at gmail.com (Sean Carolan) Date: Sun, 25 Nov 2012 06:32:44 -0600 Subject: [Tutor] Listen for input while performing other tasks In-Reply-To: <50B20EA1.7060004@pearwood.info> References: <50B20EA1.7060004@pearwood.info> Message-ID: > If you show us how you check whether the button is pressed, we may be able to > show you how to run that asynchronously. Apologies for the previous email; I think I sent it in HTML format. Gmail changed their user interface again... This is how I'm checking for a button press: modes = (weather, alarmclock, moodlight) currmode = 0 mode = 10 ## mode button is on pin #10 def checkMode(): '''Returns the current mode and whether a mode change was detected.''' global currmode modechange = False GPIO.setup(mode, GPIO.IN) if GPIO.input(mode) == False: print "Mode button pressed." if currmode < len(modes) - 1: currmode += 1 else: currmode = 0 modechange = True #print modes[currmode] return (modes[currmode], modechange) It's pretty simple, really. If GPIO.input(mode) returns False, then the button is pressed. My function above returns the current mode from my modes tuple, and whether a change was detected. From francois.dion at gmail.com Sun Nov 25 14:29:51 2012 From: francois.dion at gmail.com (Francois Dion) Date: Sun, 25 Nov 2012 08:29:51 -0500 Subject: [Tutor] Listen for input while performing other tasks In-Reply-To: References: <50B20EA1.7060004@pearwood.info> Message-ID: On Sun, Nov 25, 2012 at 7:32 AM, Sean Carolan wrote: > This is how I'm checking for a button press: This should really be done with interrupts, but unfortunately there is no support in the RPi.GPIO module for that, even if you have a patched kernel. I've done a workshop earlier this month that was on buttons with RPi.GPIO, might be of interest: http://raspberry-python.blogspot.com/2012/11/pyhack-workshop-01.html http://raspberry-python.blogspot.com/2012/11/piquizmachine.html (next workshop is on the 8th, but that'll be on the raspberry pi and motors) Fundamentally, the loop is: while gpio.input(PIN): pass dostuff() The moment the loop ends, the button was pressed. On the next line you would do something, and then go back to polling. If you do have to do something at the same time, you'll have to look into threads. Or you could launch an external script as a background process. Now, on to your code: > modes = (weather, alarmclock, moodlight) > currmode = 0 > mode = 10 ## mode button is on pin #10 mode and modes are constants. In python, it is a convention to use caps. MODES= and MODE= This helps readability of the code. Are weather, alarmclock Also, I typically import RPi.GPIO as gpio (lowercase). So you would type gpio.input(MODE). It makes more sense. > def checkMode(): pass the current mode: def checkmode( current): > global currmode That way you dont have to do the above > modechange = False > GPIO.setup(mode, GPIO.IN) Do that outside of the function. gpio.setup() should be done once at the beginning. It then has plenty of time to stabilise and you are not wasting time in the function. Also, dont forget to do a gpio.cleanup() when leaving (and possibly in a try: except: finally: block if it is likely the program ends abruptly). > if GPIO.input(mode) == False: > print "Mode button pressed." > if currmode < len(modes) - 1: > currmode += 1 > else: > currmode = 0 > modechange = True > #print modes[currmode] > return (modes[currmode], modechange) > > It's pretty simple, really. If GPIO.input(mode) returns False, then > the button is pressed. My function above returns the current mode > from my modes tuple, and whether a change was detected. The rest of your code is to support your requirement of returning a mode and boolean value. It could be a bit tighter, but the main issue is how you are separating the scope. The loop should be in the function, and no sleep (or less than 50ms if you insist), else you might miss the press. I'm not sure if you were asking for pointers or a complete solution, so I'll leave it at this for now. Francois -- pyptug.blogspot.com - raspberry-python.blogspot.com From scarolan at gmail.com Sun Nov 25 15:05:14 2012 From: scarolan at gmail.com (Sean Carolan) Date: Sun, 25 Nov 2012 08:05:14 -0600 Subject: [Tutor] Listen for input while performing other tasks In-Reply-To: References: <50B20EA1.7060004@pearwood.info> Message-ID: On Sun, Nov 25, 2012 at 7:29 AM, Francois Dion wrote: > This should really be done with interrupts, but unfortunately there is > no support in the RPi.GPIO module for that, even if you have a patched > kernel. Thank you for all this great information. I ended up going with a simple solution; I created a separate "listener" script that just waits for a button press. When the mode button is pressed, it uses os.system() to kill the other script and then starts it up again in the next mode. This seems to work well for my purposes. From alan.gauld at btinternet.com Mon Nov 26 00:49:09 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 25 Nov 2012 23:49:09 +0000 (GMT) Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: References: Message-ID: <1353887349.66662.YahooMailNeo@web87901.mail.ir2.yahoo.com> CC'ing the list... ? I know you can use images instead of text with Labels, like you can with Buttons.? >The advantage of a Text widget, in this case, is that you can use both in the same widget.? >That way, I don't need to worry about how widgets are displayed, shuffled around, and? >undisplayed during runtime. One widget should handle everything. > >Don't get hung up on the number of widgets. In the scheme of things widgets are not? expensive. Create them as you need them, delete them when you are done. Layout? managers are there to manage the layout for you. if you can define the layout in terms? of a grid then you can fill the grid with blanks to hold the shape and add/remove? widgets as you like. If you use pack you can either force the containing frame to a fixed size or allow it? to grow/shrink with the widgets. Either approach can work. This is standard? That's interesting to know. The biggest issue I'm having here is scalability.? >Each new spread is going to need a new frame widget, which in turn will need? >(number of cards in spread)*2 more widgets.? > >But that's how many? If its getting up beyond a couple of thousand then you might? have a problem. If its less than a hundred its not an issue. In between you might want? to be a bit clever. As noted above, the Text widget solution only needs one. > >Actually it probably needs more. Each image is a widget too, so you just organise? the widgets inside a Text instead of inside a Frame or Canvas. All these things are? just containers for more widgets. Frames are designed to hold widgets, end of story.? Text is?designed to *display* images and text - usually within a Frame. Canvas is? designed to *display* images and graphics shapes. If you want your images joined? or surrounded by lines/circles etc then go with Canvas. If you need to include? explanatory text around the images use a Text. If you want to create a reusable? widget that you can use in multiple screens or hot swap with other variants of? the same go with a Frame and build a display widget hierarchy.?If you just want to? display a bunch?of images it doesn't matter much which one you pick. I repeat, don't sweat over the widget count, that's not usually an issue. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdragon1984 at gmail.com Mon Nov 26 02:10:53 2012 From: sdragon1984 at gmail.com (Nathan) Date: Sun, 25 Nov 2012 20:10:53 -0500 Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: <1353887349.66662.YahooMailNeo@web87901.mail.ir2.yahoo.com> References: <1353887349.66662.YahooMailNeo@web87901.mail.ir2.yahoo.com> Message-ID: On Nov 25, 2012 6:49 PM, "ALAN GAULD" wrote: > > CC'ing the list... > Oops, my bad. I forget to hit Reply All. >> >> I know you can use images instead of text with Labels, like you can with Buttons. >> The advantage of a Text widget, in this case, is that you can use both in the same widget. >> That way, I don't need to worry about how widgets are displayed, shuffled around, and >> undisplayed during runtime. One widget should handle everything. >> > Don't get hung up on the number of widgets. In the scheme of things widgets are not > expensive. Create them as you need them, delete them when you are done. Layout > managers are there to manage the layout for you. if you can define the layout in terms > of a grid then you can fill the grid with blanks to hold the shape and add/remove > widgets as you like. > > If you use pack you can either force the containing frame to a fixed size or allow it > to grow/shrink with the widgets. Either approach can work. >> >> This is standard? That's interesting to know. The biggest issue I'm having here is scalability. >> Each new spread is going to need a new frame widget, which in turn will need >> (number of cards in spread)*2 more widgets. >> > But that's how many? If its getting up beyond a couple of thousand then you might > have a problem. If its less than a hundred its not an issue. In between you might want > to be a bit clever. Well, that depends entirely on how many spreads I'll eventually have, and the average number of cards per spread. Celtic Cross, for example, is a ten card spread, so it needs 21 widgets by itself. A hundred widgets is reached with just 10 spreads averaging 4.5 cards each. I expect, ultimately, to have more than that. >> >> As noted above, the Text widget solution only needs one. >> > Actually it probably needs more. Each image is a widget too, so you just organise > the widgets inside a Text instead of inside a Frame or Canvas. Is that how it works on the source level, or "under the hood"? The code makes it look like I'm only writing one widget, with multiple text and image elements within it, but perhaps I'm misunderstanding something. The approach I'm taking now is a Label widget, containing a single string constructed with elements from lists. I'm hoping that I can take the same approach using a single Text widget, and just convert every other string element from a filename to an image. >All these things are > just containers for more widgets. Frames are designed to hold widgets, end of story. > Text is designed to *display* images and text - usually within a Frame. Canvas is > designed to *display* images and graphics shapes. If you want your images joined > or surrounded by lines/circles etc then go with Canvas. If you need to include > explanatory text around the images use a Text. If you want to create a reusable > widget that you can use in multiple screens or hot swap with other variants of > the same go with a Frame and build a display widget hierarchy. If you just want to > display a bunch of images it doesn't matter much which one you pick. > Then it seems Text it is. Perhaps later in development, Frames and/or Canvases might be appropriate for more complex designs. > I repeat, don't sweat over the widget count, that's not usually an issue. > > Alan G. > Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Mon Nov 26 22:06:19 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 26 Nov 2012 13:06:19 -0800 (PST) Subject: [Tutor] doctest question Message-ID: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> Hi, I am using doctest and I am struggling with newlines characters (see below). One is the newline escape (backslash) for a long dictionary definition. The other is an embedded \n in the output. I used the +NORMALIZE_WHITESPACE directive. I also tried using a triple-quoted raw docstring. Any ideas? While we're at it: is this a good book? http://www.packtpub.com/python-testing-beginners-guide/book It should be complete, not too shallow, nor so detailed that is becomes too impractical. Thanks! import doctest import copy def _setMultRespDefsEx(multRespDefs): ??????? """>>> multRespDefs = {'mesetx': {'countedValue': '1', 'firstVarIsLabel': True, \ ??? ??? ??? ?? 'label': '', 'setType': 'E','varNames':? ['mevar1', 'mevar2', \ ??? ??? ??? ?? 'var3']}, 'mesety': {'countedValue': 'Yes', 'firstVarIsLabel': \ ??? ??? ??? ?? False, 'label': 'Enhanced set with user specified label', \ ??? ??? ??? ?? 'setType': 'E', 'varNames': ['mevar4', 'mevar5', 'mevar6']}} ??????? >>> _setMultRespDefsEx(multRespDefs) ??????? $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 ??????? $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6 ??????? # doctest: +NORMALIZE_WHITESPACE""" ??????? mrDefs = [] ??????? for setName, rest in multRespDefs.iteritems(): ??????????? if rest["setType"] != "E": ??????????????? return {} ??????????? rest["setName"] = setName ??????????? v = int(rest["firstVarIsLabel"]) ??????????? rest["firstVarIsLabel"] = v if v == 1 else "" ??????????? rest["valueLen"] = len(rest["countedValue"]) ??????????? rest["lblLen"] = len(rest["label"]) ??????????? rest["label"] = rest["label"] ??????????? rest["varNames"] = " ".join(rest["varNames"]) ??????????? mrDef =? "$%(setName)s=%(setType)s 1%(firstVarIsLabel)s %(valueLen)s " ??????????? mrDef += "%(countedValue)s %(lblLen)s %(label)s %(varNames)s" ??????????? mrDefs.append((mrDef % rest).replace("? ", " ")) ??????? return "\n".join(mrDefs) if __name__ == "__main__": ??? x = {"setType": "E", "label": "Enhanced set with user specified label", ???????? "varNames": ["mevar4", "mevar5", "mevar6"], "countedValue": ???????? "Yes", "firstVarIsLabel": False} ??? d = {'testme': copy.deepcopy(x), 'testmeMore': copy.deepcopy(x)} ??? print _setMultRespDefsEx(d) # prints desired result ??? doctest.testmod() # fails because of newline! See below ********************************************************************** File "__main__", line 3, in __main__._setMultRespDefsEx Failed example: ??? _setMultRespDefsEx(multRespDefs) Expected: ??? $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 ??? $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6 ??? # doctest: +NORMALIZE_WHITESPACE Got: ??? mesetx {'countedValue': '1', 'firstVarIsLabel': True, 'setType': 'E', 'varNames': ['mevar1', 'mevar2', 'var3'], 'label': ''} ??? mesety {'countedValue': 'Yes', 'firstVarIsLabel': False, 'setType': 'E', 'varNames': ['mevar4', 'mevar5', 'mevar6'], 'label': 'Enhanced set with user specified label'} ??? '$mesetx=E 11 1 1 0 mevar1 mevar2 var3\n$mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6' ********************************************************************** 1 items had failures: ?? 1 of?? 2 in __main__._setMultRespDefsEx ***Test Failed*** 1 failures. ********************************************************************** 1st error with r-escaped docstring ********************************************************************** File "__main__", line 5, in __main__._setMultRespDefsEx Failed example: ??? multRespDefs = {'mesetx': {'countedValue': '1', 'firstVarIsLabel': True, \ Exception raised: ??? Traceback (most recent call last): ????? File "C:\Python26\lib\doctest.py", line 1241, in __run ??????? compileflags, 1) in test.globs ????? File "", line 1 ???????? multRespDefs = {'mesetx': {'countedValue': '1', 'firstVarIsLabel': True, \ ????????????????????????????????????????????????????????????????????????????????? ??? ^ ???? SyntaxError: unexpected EOF while parsing ***************************************************** From steve at pearwood.info Mon Nov 26 23:02:45 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 27 Nov 2012 09:02:45 +1100 Subject: [Tutor] doctest question In-Reply-To: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <50B3E705.7090609@pearwood.info> On 27/11/12 08:06, Albert-Jan Roskam wrote: > Hi, > > I am using doctest and I am struggling with newlines characters > (see below). One is the newline escape (backslash) for a long >dictionary definition. The other is an embedded \n in the output. > I used the +NORMALIZE_WHITESPACE directive. I also tried using a > triple-quoted raw docstring. Any ideas? Yes, quite a few. Your following example is hard to understand and, as they say in English, "as clear as mud". It would help a lot if you laid out the example dictionary so that it was easier to read, and if you followed the standard convention to end the docstring with a single """ so that it separates the end of the docstring from the start of the code. Function name "_setMultRespDefsEx" is not self-explanatory, or even *hint* at what the function is supposed to do. It appears to take a dictionary of stuff, and formats it as a string. It would be nice[1] if your docstring explained what sort of stuff. The example given should be simple, not complex. If you must give a complex example, always give a simple example first. Examples should be written for clarity, not as code golf. There is no prize for stuffing everything into one or two lines. Doctext directives are not global to the docstring, they must appear on the same line as the doctest itself. Take advantage of Python's implicit line continuation to avoid problems with backslash line continuations. Doctesting anything to do with dictionaries is tricky, because you cannot rely on the order of a dict. There are a couple of different ways to solve that: * the lazy solution: always use doctests on dicts with a single item; * change the function to always process the dict in a known order; * change the doctest to post-process the function result, e.g. pull the string apart into separate lines, sort the lines, put it back together. Here's my attempt: import doctest import copy def _setMultRespDefsEx(multRespDefs): """Format a dictionary of stuff as a string. Expects that dict contains: {breakfast: {spam: foo, ham: bar} blah blah blah ...} # or whatever >>> xdict = {'countedValue': '1', 'firstVarIsLabel': True, 'label': '', ... 'setType': 'E','varNames': ['mevar1', 'mevar2', 'mevar3']} >>> ydict = {'countedValue': 'Yes', 'firstVarIsLabel': False, ... 'label': 'Enhanced set with user specified label', ... 'setType': 'E', 'varNames': ['mevar4', 'mevar5', 'mevar6']} >>> adict = {'mesetx': xdict, 'mesety': ydict} >>> print(_setMultRespDefsEx(adict)) $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 mevar6 KNOWN BUGS: 1) Sometimes this function returns a dict instead of a string. 2) The formatted string output is ambiguous. """ mrDefs = [] # "That's Mister Defs to you" :-) for setName, rest in sorted(multRespDefs.iteritems()): if rest["setType"] != "E": return {} rest["setName"] = setName v = int(rest["firstVarIsLabel"]) rest["firstVarIsLabel"] = v if v == 1 else "" rest["valueLen"] = len(rest["countedValue"]) rest["lblLen"] = len(rest["label"]) rest["label"] = rest["label"] rest["varNames"] = " ".join(rest["varNames"]) mrDef = "$%(setName)s=%(setType)s 1%(firstVarIsLabel)s %(valueLen)s " mrDef += "%(countedValue)s %(lblLen)s %(label)s %(varNames)s" mrDefs.append((mrDef % rest).replace(" ", " ")) return "\n".join(mrDefs) And running the doctest: py> doctest.testmod() TestResults(failed=0, attempted=4) [1] By "nice" I mean *essential*. -- Steven From steve at pearwood.info Mon Nov 26 23:34:04 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 27 Nov 2012 09:34:04 +1100 Subject: [Tutor] doctest question In-Reply-To: <50B3E705.7090609@pearwood.info> References: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> <50B3E705.7090609@pearwood.info> Message-ID: <50B3EE5C.2090906@pearwood.info> On 27/11/12 09:02, Steven D'Aprano wrote: > Here's my attempt: > def _setMultRespDefsEx(multRespDefs): > """Format a dictionary of stuff as a string. Expects that dict contains: [...] > KNOWN BUGS: > > 1) Sometimes this function returns a dict instead of a string. > 2) The formatted string output is ambiguous. > > """ Oops, I forgot one: 3) This modifies the input argument. Never call this function except on a temporary deep copy of your dict. -- Steven From fomcl at yahoo.com Tue Nov 27 10:50:24 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 27 Nov 2012 01:50:24 -0800 (PST) Subject: [Tutor] doctest question In-Reply-To: <50B3E705.7090609@pearwood.info> References: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> <50B3E705.7090609@pearwood.info> Message-ID: <1354009824.6881.YahooMailNeo@web163805.mail.gq1.yahoo.com> ? > On 27/11/12 08:06, Albert-Jan Roskam wrote: >> Hi, >> >> I am using doctest and I am struggling with newlines characters >> (see below). One is the newline escape (backslash) for a long >> dictionary definition. The other is an embedded \n in the output. >> I used the +NORMALIZE_WHITESPACE directive. I also tried using a >> ? triple-quoted raw docstring. Any ideas? > > Yes, quite a few. > > Your following example is hard to understand and, as they say in > English, "as clear as mud". It would help a lot if you laid out the > example dictionary so that it was easier to read, and if you followed > the standard convention to end the docstring with a single """ so > that it separates the end of the docstring from the start of the code. ? Ok, good idea. After all, "Readability counts" ? ? > Function name "_setMultRespDefsEx" is not self-explanatory, or even > *hint* at what the function is supposed to do. It appears to take a > dictionary of stuff, and formats it as a string. It would be nice[1] > if your docstring explained what sort of stuff. But in my defense (a little bit, at least), this is a helper function for another function that *does* have a good explanation/docstring. I should mention that in this function's docstring though. You're right that I could, at the very least, start by saying: """ Helper function to set extended multiple response definitions (see function 'blaah' for further info) ? """ ? ? > The example given should be simple, not complex. If you must give a > complex example, always give a simple example first. > > Examples should be written for clarity, not as code golf. There is no > prize for stuffing everything into one or two lines. > > Doctext directives are not global to the docstring, they must appear > on the same line as the doctest itself. AHA! I missed that from the online documentation. Thank you. ? > Take advantage of Python's implicit line continuation to avoid > problems with backslash line continuations. > > Doctesting anything to do with dictionaries is tricky, because you > cannot rely on the order of a dict. There are a couple of different > ways to solve that: ? Huh? Although I am iterating over a dictionary (which is unordered), the return value will, given a certain input,?always be the same. Why is the 'unorderedness'?relevant here? ? ? > * the lazy solution: always use doctests on dicts with a single item; > > * change the function to always process the dict in a known order; > > * change the doctest to post-process the function result, e.g. pull > ? the string apart into separate lines, sort the lines, put it > ? back together. > > > Here's my attempt: > > > import doctest > import copy > > def _setMultRespDefsEx(multRespDefs): > ? ? """Format a dictionary of stuff as a string. Expects that > dict contains: > > ? ? {breakfast: {spam: foo, ham: bar} blah blah blah ...}? # or whatever > > ? ? >>> xdict = {'countedValue': '1', > 'firstVarIsLabel': True, 'label': '', > ? ? ...? ? ? ? ? 'setType': 'E','varNames':? > ['mevar1', 'mevar2', 'mevar3']} > ? ? >>> ydict = {'countedValue': 'Yes', > 'firstVarIsLabel': False, > ? ? ...? ? ? ? ? 'label': 'Enhanced set with user specified > label', > ? ? ...? ? ? ? ? 'setType': 'E', 'varNames': > ['mevar4', 'mevar5', 'mevar6']} > ? ? >>> adict = {'mesetx': xdict, 'mesety': ydict} > ? ? >>> print(_setMultRespDefsEx(adict)) > ? ? $mesetx=E 11 1 1 0 mevar1 mevar2 mevar3 > ? ? $mesety=E 1 3 Yes 38 Enhanced set with user specified label mevar4 mevar5 > mevar6 > > ? ? KNOWN BUGS: > > ? ? ? ? 1) Sometimes this function returns a dict instead of a string. > ? ? ? ? 2) The formatted string output is ambiguous. > > ? ? """ > ? ? mrDefs = []? # "That's Mister Defs to you" :-) ? ;-))) ? > ? ? for setName, rest in sorted(multRespDefs.iteritems()): > ? ? ? ? if rest["setType"] != "E": > ? ? ? ? ? ? return {} > ? ? ? ? rest["setName"] = setName > ? ? ? ? v = int(rest["firstVarIsLabel"]) > ? ? ? ? rest["firstVarIsLabel"] = v if v == 1 else "" > ? ? ? ? rest["valueLen"] = len(rest["countedValue"]) > ? ? ? ? rest["lblLen"] = len(rest["label"]) > ? ? ? ? rest["label"] = rest["label"] > ? ? ? ? rest["varNames"] = " > ".join(rest["varNames"]) > ? ? ? ? mrDef =? "$%(setName)s=%(setType)s 1%(firstVarIsLabel)s > %(valueLen)s " > ? ? ? ? mrDef += "%(countedValue)s %(lblLen)s %(label)s %(varNames)s" > ? ? ? ? mrDefs.append((mrDef % rest).replace("? ", " ")) > ? ? return "\n".join(mrDefs) > > > > And running the doctest: > > py> doctest.testmod() > TestResults(failed=0, attempted=4) > > > > > > [1] By "nice" I mean *essential*. > > > -- Steven > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From d at davea.name Tue Nov 27 13:09:54 2012 From: d at davea.name (Dave Angel) Date: Tue, 27 Nov 2012 07:09:54 -0500 Subject: [Tutor] doctest question In-Reply-To: <1354009824.6881.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> <50B3E705.7090609@pearwood.info> <1354009824.6881.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <50B4AD92.8070508@davea.name> On 11/27/2012 04:50 AM, Albert-Jan Roskam wrote: > >> On 27/11/12 08:06, Albert-Jan Roskam wrote: >>> (Steven D'Aprano wrote, even though the indentation is wrong) >>> >>> >>> >>> Doctesting anything to do with dictionaries is tricky, because you >>> cannot rely on the order of a dict. There are a couple of different >>> ways to solve that: > > Huh? Although I am iterating over a dictionary (which is unordered), > the return value will, given a certain input, always be the same. Why > is the 'unorderedness' relevant here? > It's only promised to be the same for a single run of the program. http://permalink.gmane.org/gmane.comp.python.devel/131826 In particular, """ Hash randomization causes the iteration order of dicts and sets to be unpredictable and differ across Python runs. Python has never guaranteed iteration order of keys in a dict or set, and applications are advised to never rely on it. Historically, dict iteration order has not changed very often across releases and has always remained consistent between successive executions of Python.""" Starting with the releases described in that document, hash randomization was introduced, but disabled by default. But a user might enable it (with the -R cmd switch, or an environment variable). And in the latest version (3.3, i believe it's enabled by default, as a protection against a security threat. Even if you somehow can assure that your code will never run on those versions, it has never been assured that the hash ordering remains stable between even minor versions of the releases. > (Steven again:) >> * the lazy solution: always use doctests on dicts with a single item; >> >> * change the function to always process the dict in a known order; >> >> * change the doctest to post-process the function result, e.g. pull >> the string apart into separate lines, sort the lines, put it >> back together. >> >> >> As Steven points out, it's dangerous to doctest with a dictionary without some form of enforced ordering. -- DaveA From steve at pearwood.info Tue Nov 27 15:01:21 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 28 Nov 2012 01:01:21 +1100 Subject: [Tutor] doctest question In-Reply-To: <1354009824.6881.YahooMailNeo@web163805.mail.gq1.yahoo.com> References: <1353963979.27596.YahooMailNeo@web163805.mail.gq1.yahoo.com> <50B3E705.7090609@pearwood.info> <1354009824.6881.YahooMailNeo@web163805.mail.gq1.yahoo.com> Message-ID: <50B4C7B1.8090001@pearwood.info> On 27/11/12 20:50, Albert-Jan Roskam wrote: >> Function name "_setMultRespDefsEx" is not self-explanatory, or even >> *hint* at what the function is supposed to do. It appears to take a >> dictionary of stuff, and formats it as a string. It would be nice[1] >> if your docstring explained what sort of stuff. > > But in my defense (a little bit, at least), this is a helper > function for another function that *does* have a good explanation/docstring. > I should mention that in this function's docstring though. Yes! You're not just writing documentation for others. You're also writing documentation for yourself, in six months time, or even six weeks time, when the function is no longer fresh in your mind and you only have the vaguest memory of what it is supposed to do. [...] >> Doctesting anything to do with dictionaries is tricky, because you >> cannot rely on the order of a dict. There are a couple of different >> ways to solve that: > > Huh? Although I am iterating over a dictionary (which is unordered), > the return value will, given a certain input, always be the same. Why > is the 'unorderedness' relevant here? Because if you don't sort the dictionary items, the doctest fails. I know this, because the first time I ran it, it failed for exactly this reason. Feel free to take the call to sorted() out. When you do, your input dict looks like this: {'mesetx': ..., 'mesety': ...} # X first, Y second and your doctest, *as you wrote it*, has the same order: $mesetx= ... $mesety= ... BUT the actual output of the function may be in the opposite order, Y first and X second. Or at least, that's the order *I* get, running CPython 2.7.2 under Centos Linux built with gcc 4.1.2. What *you* get, running some other version of Python, built with a different compiler, under a different operating system, may be different. With only two items in the dict, you have a 50% chance of the doctest matching the actual run of the dict. The only promise that Python makes about the order of iterating over a dict is that if you iterate over the same dict twice, without making any changes, in the same Python run, you will get the same output. That is all. You might get a different order if you do any of these things: - modify the dict between runs, even if you reverse the changes; - change the way you assemble the dict in the first place; - use a different version of Python; - or a different implementation; - or theoretically even the same version but on a different OS; - or even if you merely exit Python and run the script again. [steve at ando ~]$ python3.3 -c "print({'a': None, 'b': None})" {'b': None, 'a': None} [steve at ando ~]$ python3.3 -c "print({'a': None, 'b': None})" {'a': None, 'b': None} -- Steven From D.Wilder at F5.com Tue Nov 27 17:49:47 2012 From: D.Wilder at F5.com (Dave Wilder) Date: Tue, 27 Nov 2012 16:49:47 +0000 Subject: [Tutor] manipulating a string in python Message-ID: Hello, I believe there is a simple answer to this, but I am confused on what direction I should go that would perform what I wish to do most efficiently. ** My Environment *** [root at f5ite ~/tests]$ python Python 2.7 (r27:82500, Jul 6 2010, 02:54:50) [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 Type "help", "copyright", "credits" or "license" for more information. [root at f5ite ~/tests]$ uname -a Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 BST 2012 i686 i686 i386 GNU/Linux [root at f5ite ~/tests]$ more /etc/redhat-release CentOS release 5.8 (Final) [root at f5ite ~/tests]$ I need to strip down a string to make a list of "auto" and anything starting w/ "10" and nothing else. Below is the string I am currently working with. >> results 'tmsh list net interface 1.1 media-capa \rbilities\nnet interface 1.1 {\n media-capabilities {\n none\n auto\n 10T-FD\n 10T-HD\n 100TX-FD\n 100TX-HD\n 1000T-FD\n 1000T-HD\n }\n}\n' >> I want to chop it up, so I have a list of all media speeds (auto or "10X" that I can then loop through, so would like to end up with something like below: >> results 'none', 'auto', '10T-FD'...'1000T-HD' I could do this using a series of "split" commands. However, is there a better way? For example, can I just eliminate "media-capabilities", "{" and "}" right off the bat and then do a split on "\n"? Should I use "re" matching for this? I could also just a single split('\n') and then inside the loop ignore everything that is not "auto" or starts with "10", but that seems inefficient. Any advice on the best way to do this? Thanks, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From stuart at sjsears.com Tue Nov 27 18:14:38 2012 From: stuart at sjsears.com (Stuart Sears) Date: Tue, 27 Nov 2012 17:14:38 +0000 Subject: [Tutor] manipulating a string in python In-Reply-To: References: Message-ID: <50B4F4FE.5070009@sjsears.com> On 27/11/12 16:49, Dave Wilder wrote: > Hello, > > I believe there is a simple answer to this, but I am confused on what > direction I should go that would perform what I wish to do most > efficiently. > > ** My Environment *** > > [root at f5ite ~/tests]$ python > > Python 2.7 (r27:82500, Jul 6 2010, 02:54:50) > > [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > [root at f5ite ~/tests]$ uname ?a > > Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 > BST 2012 i686 i686 i386 GNU/Linux > > [root at f5ite ~/tests]$ more /etc/redhat-release > > CentOS release 5.8 (Final) > > [root at f5ite ~/tests]$ > > I need to strip down a string to make a list of ?auto? and anything > starting w/ ?10? and nothing else. well, if you know the pattern, you could use regex for that. Or, if it's really simple, a single split and lots of .startswith or fnmatch calls could also work. > > Below is the string I am currently working with. > >>> results > > 'tmsh list net interface 1.1 media-capa \rbilities\nnet interface 1.1 > {\n media-capabilities {\n none\n auto\n 10T-FD\n > > 10T-HD\n 100TX-FD\n 100TX-HD\n 1000T-FD\n > 1000T-HD\n }\n}\n' > >>> > > I want to chop it up, so I have a list of all media speeds (auto or > ?10X? that I can then loop through, so would like to end up with > something like below: >>> results > > ?none?, ?auto?, ?10T-FD???1000T-HD? > > I could do this using a series of ?split? commands. However, is there a > better way? For example, can I just eliminate ?media-capabilities?, ?{? > and ?}? right off the bat > > and then do a split on ?\n?? Should I use ?re? matching for this? I'd say so. Assuming that is essentially 'auto' and 'starts with 10..T' import re media_re = re.compile(r'(auto|10+T-[HF]D)') instr = """tmsh list net interface 1.1 media-capa \rbilities\nnet interface 1.1 {\n media-capabilities {\n none\n auto\n 10T-FD\n 10T-HD\n 100TX-FD\n 100TX-HD\n 1000T-FD\n 1000T-HD\n }\n}\n""" print [ x.strip() for x in instr.split() if media_re.match(x) ] gives: ['auto', '10T-FD', '10T-HD', '1000T-FD', '1000T-HD'] if you want to include 'none' as well, you'd add it to the regex > I could also just a single split(?\n?) and then inside the loop ignore > everything that is not ?auto? or starts with ?10?, but that seems > inefficient. > > Any advice on the best way to do this? I'd use regex for it, but there are numerous other ways to achieve this. -- Stuart Sears RHCA etc. "It's today!" said Piglet. "My favourite day," said Pooh. From d at davea.name Tue Nov 27 18:28:42 2012 From: d at davea.name (Dave Angel) Date: Tue, 27 Nov 2012 12:28:42 -0500 Subject: [Tutor] manipulating a string in python In-Reply-To: References: Message-ID: <50B4F84A.1000508@davea.name> On 11/27/2012 11:49 AM, Dave Wilder wrote: Could you please use text mode in your messages? Your email editor produces double-spacing when it converts the html stuff you wrote into the text this forum supports. > > > I believe there is a simple answer to this, but I am confused on what direction I should go that would perform what I wish to do most efficiently. > > > > ** My Environment *** > > [root at f5ite ~/tests]$ python > > Python 2.7 (r27:82500, Jul 6 2010, 02:54:50) > > [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > > > [root at f5ite ~/tests]$ uname -a > > Linux VM-QA-ITE-03 2.6.32-220.17.1.el6.i686 #1 SMP Tue May 15 22:09:39 BST 2012 i686 i686 i386 GNU/Linux > > > > [root at f5ite ~/tests]$ more /etc/redhat-release > > CentOS release 5.8 (Final) > > [root at f5ite ~/tests]$ > > Thanks for being so thorough about your environment. > > > > > I need to strip down a string to make a list of "auto" and anything starting w/ "10" and nothing else. > > > > Below is the string I am currently working with. > >>> results > 'tmsh list net interface 1.1 media-capa \rbilities\nnet interface 1.1 {\n media-capabilities {\n none\n auto\n 10T-FD\n > > 10T-HD\n 100TX-FD\n 100TX-HD\n 1000T-FD\n 1000T-HD\n }\n}\n' What is this string supposed to represent? Is it equivalent to a text file, so it should be interpreted as lines? That would at least give a meaning to "starting w/ "10". Assuming that, are leading blanks significant? If so, i don't see any lines beginning with "10". > I want to chop it up, so I have a list of all media speeds (auto or > "10X" that I can then loop through, so would like to end up with > something like below: >>> results > 'none', 'auto', '10T-FD'...'1000T-HD' > Why is 'none' in the expected results? It is not 'auto' and it doesn't begin with '10'. > > I could do this using a series of "split" commands. However, is there a better way? For example, can I just eliminate "media-capabilities", "{" and "}" right off the bat What are special about "media-capabilities", "{", and "}" ?? Why aren't you "eliminating" "tmsh" for example? > > and then do a split on "\n"? Should I use "re" matching for this? > > > > I could also just a single split('\n') and then inside the loop ignore everything that is not "auto" or starts with "10", but that seems inefficient. > > > > Any advice on the best way to do this? > > Once you have an unambiguous spec, the code should be pretty straightforward (depends on that spec, of course). Only then should you worry about inefficient. Chances are that the code which generates this string or reads it from a file, or whatever, is taking more time than the logic you'll need here. So, for example, it might be quicker to substitute readlines() for read(), if you're just getting it from a file. Another point: your 'results' display isn't a valid repr() output for any Python built-in type. Do i presume you want a list of strings, and just omitted the square brackets? And do i presume you don't want any placeholders in that list for lines not matching the spec? -- DaveA From fomcl at yahoo.com Tue Nov 27 21:38:46 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 27 Nov 2012 12:38:46 -0800 (PST) Subject: [Tutor] manipulating a string in python In-Reply-To: <50B4F4FE.5070009@sjsears.com> References: <50B4F4FE.5070009@sjsears.com> Message-ID: <1354048726.45370.YahooMailNeo@web163803.mail.gq1.yahoo.com> ' > >import re >media_re = re.compile(r'(auto|10+T-[HF]D)') > >instr = """tmsh list net interface 1.1 media-capa \rbilities\nnet >interface 1.1 >{\n? ? media-capabilities {\n? ? ? ? none\n? ? ? ? auto\n? ? ? ? 10T-FD\n >10T-HD\n? ? ? ? 100TX-FD\n? ? ? ? 100TX-HD\n? ? ? ? 1000T-FD\n >1000T-HD\n? ? }\n}\n""" > >print [ x.strip() for x in instr.split() if media_re.match(x) ] > > >gives: >['auto', '10T-FD', '10T-HD', '1000T-FD', '1000T-HD'] slightly more readable: print re.findall(r'(auto|10+T-[HF]D)', instr) gives: ['auto', '10T-FD', '10T-HD', '1000T-FD', '1000T-HD'] Not relevant here, but really neat (I recently discovered this by accident): if you have groups in your regex, re.findall turns them into a list of tuples. > From sampanriver at hotmail.com Wed Nov 28 02:01:12 2012 From: sampanriver at hotmail.com (JiangShan) Date: Wed, 28 Nov 2012 01:01:12 +0000 Subject: [Tutor] Question about the raw string In-Reply-To: References: Message-ID: Hi everyone, I am studying the python 3 and I am confused about the raw string. Why does the python interpreter do not escape the single backslash before the quotes even I add a "r" before the string. The following is an example: >>> print(r"\") SyntaxError: EOL while scanning string literal >>> print(r"\\") \\ >>> Jiang Shan -------------- next part -------------- An HTML attachment was scrubbed... URL: From crawlzone at gmail.com Wed Nov 28 02:13:52 2012 From: crawlzone at gmail.com (Ray Jones) Date: Tue, 27 Nov 2012 18:13:52 -0700 Subject: [Tutor] LCM revisited + OOP Message-ID: <50B56550.4060806@gmail.com> Part I I am a good way through MIT's Introduction to Computer Science and Programming as offered through edX. I'm not certain I'm going to pass the course this first time through, the major hangup being the understanding of OOP. Part II When the LCM thread came through, I wrote some quick code do the computation. I began by creating a function that generates a list of primes and reversing the list high to low. Then I created a recursive function to find the prime factors for each of the numbers and manipulated the results to the LCM. What do these two things have to do with each other? I can see some of the vast power of OOP. Unfortunately I can't see when or why I would create objects in my everyday programming. So I went back to look at my LCM code to see if there a way to create better code by using OOP rather than the functions I used. I can't see a better way. I know I can use OOP - I just don't see how setting it up with a couple of classes would make it simpler or better than the non-OOP way. I'm not including code because I'm more interested in understanding the whys and wherefores of using OOP vs. not using it than in receiving help with my specific code. (And I'm not a particularly fine coder to begin with... ;) ). From steve at pearwood.info Wed Nov 28 03:15:57 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 28 Nov 2012 13:15:57 +1100 Subject: [Tutor] Question about the raw string In-Reply-To: References: Message-ID: <20121128021557.GB21941@ando> On Wed, Nov 28, 2012 at 01:01:12AM +0000, JiangShan wrote: > Hi everyone, > > I am studying the python 3 and I am confused about the raw > string. Why does the python interpreter do not escape the > single backslash before the quotes even I add a "r" before the > string. The following is an example: > > >>> print(r"\") > > SyntaxError: EOL while scanning string literal > >>> print(r"\\") > \\ > >>> A very good question! Note that this is not just in Python 3, the same thing applies to all versions of Python, and even other implementations like IronPython: steve at runes:~$ ipy IronPython 2.6 Beta 2 DEBUG (2.6.0.20) on .NET 2.0.50727.1433 Type "help", "copyright", "credits" or "license" for more information. >>> s = r"\" File "", line 1 s = r"\" ^ SyntaxError: EOL while scanning single-quoted string Unfortunately, there is no good answer except "that's the way it is, because that's the way the string parser is designed to work". It is a documented limitation of raw strings: http://docs.python.org/2/reference/lexical_analysis.html#string-literals and it has been reported as a bug but closed as "Invalid": http://bugs.python.org/issue1271 -- Steven From steve at pearwood.info Wed Nov 28 03:27:57 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 28 Nov 2012 13:27:57 +1100 Subject: [Tutor] LCM revisited + OOP In-Reply-To: <50B56550.4060806@gmail.com> References: <50B56550.4060806@gmail.com> Message-ID: <20121128022757.GC21941@ando> On Tue, Nov 27, 2012 at 06:13:52PM -0700, Ray Jones wrote: > Part I > I am a good way through MIT's Introduction to Computer Science and > Programming as offered through edX. I'm not certain I'm going to pass > the course this first time through, the major hangup being the > understanding of OOP. We should come back to that. > Part II > When the LCM thread came through, I wrote some quick code do the > computation. I began by creating a function that generates a list of > primes and reversing the list high to low. Then I created a recursive > function to find the prime factors for each of the numbers and > manipulated the results to the LCM. Seems like a complicated way to generate the least common multiple. > What do these two things have to do with each other? I can see some of > the vast power of OOP. Unfortunately I can't see when or why I would > create objects in my everyday programming. So I went back to look at my > LCM code to see if there a way to create better code by using OOP rather > than the functions I used. I can't see a better way. I know I can use > OOP - I just don't see how setting it up with a couple of classes would > make it simpler or better than the non-OOP way. For something as simple as Least Common Multiple? Using a function is much more sensible than writing a class. OOP is for when you have a single data type that needs *state* and *behaviour*. A LCM function only has behaviour, and so a function is best. If you have code that never needs to store its current state, then a simple function is probably best. If you have code that does store the current state, then OOP is probably best. Do you understand what I mean by "current state"? -- Steven From crawlzone at gmail.com Wed Nov 28 03:40:57 2012 From: crawlzone at gmail.com (Ray Jones) Date: Tue, 27 Nov 2012 19:40:57 -0700 Subject: [Tutor] LCM revisited + OOP In-Reply-To: <20121128022757.GC21941@ando> References: <50B56550.4060806@gmail.com> <20121128022757.GC21941@ando> Message-ID: <50B579B9.5070206@gmail.com> On 11/27/2012 07:27 PM, Steven D'Aprano wrote: > For something as simple as Least Common Multiple? Using a function is > much more sensible than writing a class. > > OOP is for when you have a single data type that needs *state* and > *behaviour*. A LCM function only has behaviour, and so a function is > best. > > If you have code that never needs to store its current state, then a > simple function is probably best. If you have code that does store the > current state, then OOP is probably best. Do you understand what I mean > by "current state"? > I see. Yes, current state should refer to an object's location, heading, speed (if in motion), state of at-rest, etc.? That explains much. Without a state, LCM is not a good candidate as a Class object...unlike, say, a circuit??? From wrw at mac.com Wed Nov 28 02:52:34 2012 From: wrw at mac.com (wrw at mac.com) Date: Tue, 27 Nov 2012 20:52:34 -0500 Subject: [Tutor] LCM revisited + OOP In-Reply-To: <50B56550.4060806@gmail.com> References: <50B56550.4060806@gmail.com> Message-ID: <05E3E48D-4718-4251-A77A-9264BDB9E2F5@mac.com> On Nov 27, 2012, at 8:13 PM, Ray Jones wrote: > > Part I > I am a good way through MIT's Introduction to Computer Science and > Programming as offered through edX. I'm not certain I'm going to pass > the course this first time through, the major hangup being the > understanding of OOP. > > Part II > When the LCM thread came through, I wrote some quick code do the > computation. I began by creating a function that generates a list of > primes and reversing the list high to low. Then I created a recursive > function to find the prime factors for each of the numbers and > manipulated the results to the LCM. > > What do these two things have to do with each other? I can see some of > the vast power of OOP. Unfortunately I can't see when or why I would > create objects in my everyday programming. So I went back to look at my > LCM code to see if there a way to create better code by using OOP rather > than the functions I used. I can't see a better way. I know I can use > OOP - I just don't see how setting it up with a couple of classes would > make it simpler or better than the non-OOP way. > > I'm not including code because I'm more interested in understanding the > whys and wherefores of using OOP vs. not using it than in receiving help > with my specific code. (And I'm not a particularly fine coder to begin > with... ;) ). > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Ray, I'll be VERY interested to see how others answer this question, because I'm still working through it myself. I started programming back in the days of FORTRAN IV, writing data analysis programs in support of my own work. I've moved forward since and have spent the last two years learning Python. All my initial development in Python was very much procedural and I've been quite happy to leverage its power. More recently, as I decided to start developing simple GUI front ends for some of my stuff, I took another long hard look at the sections in my various books on OOP, and have finally (I hope) started to see daylight. To be overly simplistic, OOP really shows its worth when one is creating classes that _do_ represent objects or abstractions of objects (and of course, that's why GUI widgets lend themselves to nicely to OOP). To give a slightly more concrete example, I develop a lot of network utilities, and it suddenly became obvious that a "network" class would be a very useful thing. That class allows me to define a network object in terms of a remote end-point, and then perform all sorts of actions (tests) on the "network" between here and there. Behind the scenes, that class can share data among its internal modules and functions, but each instance of the class is completely unique and the fact that the collection of "hops" that make up that particular "network" is also unique can be safely hidden (or exposed) as needed. So, to summarize - for a lot of purely procedural programming - there may well NOT be any advantage to OOP, but when you start developing code that needs to mimic/represent or model complicated "objects" then OOP starts to shine. Done right it simplifies the interface to the object, simplifies future debugging when objects are combined, and provides structure that helps you get the "logic" right. Good luck that class, Bill From sdragon1984 at gmail.com Wed Nov 28 22:53:04 2012 From: sdragon1984 at gmail.com (Nathan) Date: Wed, 28 Nov 2012 16:53:04 -0500 Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: References: <1353887349.66662.YahooMailNeo@web87901.mail.ir2.yahoo.com> Message-ID: Okay, now I see what I was doing wrong. For some dumb reason, I had forgotten that you can create a widget without assigning a variable. That helps runtime widget creation a LOT. The Frame idea I had was actually writing out one Frame per type of spread; I would have had, for example, celtic_cross_frame, past_present_future_frame, etc. Selecting a different spread would hotswap one spread Frame out for a new one and configure the widgets already hardcoded in the Frame. Then I remembered that all I need to do to create a widget is simply call it and add it to the layout, so I just created a single Frame and a loop that adds a variable number of widgets. Now I just destroy that Frame (and thus, the widgets it holds), recreate it, and repopulate it. Which, re-reading this discussion, is probably what you meant by standard practice. Thanks for your help! On Nov 25, 2012 8:10 PM, "Nathan" wrote: > > On Nov 25, 2012 6:49 PM, "ALAN GAULD" wrote: > > > > CC'ing the list... > > > > Oops, my bad. I forget to hit Reply All. > > >> > >> I know you can use images instead of text with Labels, like you can > with Buttons. > >> The advantage of a Text widget, in this case, is that you can use both > in the same widget. > >> That way, I don't need to worry about how widgets are displayed, > shuffled around, and > >> undisplayed during runtime. One widget should handle everything. > >> > > Don't get hung up on the number of widgets. In the scheme of things > widgets are not > > expensive. Create them as you need them, delete them when you are done. > Layout > > managers are there to manage the layout for you. if you can define the > layout in terms > > of a grid then you can fill the grid with blanks to hold the shape and > add/remove > > widgets as you like. > > > > If you use pack you can either force the containing frame to a fixed > size or allow it > > to grow/shrink with the widgets. Either approach can work. > >> > >> This is standard? That's interesting to know. The biggest issue I'm > having here is scalability. > >> Each new spread is going to need a new frame widget, which in turn will > need > >> (number of cards in spread)*2 more widgets. > >> > > But that's how many? If its getting up beyond a couple of thousand then > you might > > have a problem. If its less than a hundred its not an issue. In between > you might want > > to be a bit clever. > > Well, that depends entirely on how many spreads I'll eventually have, and > the average number of cards per spread. Celtic Cross, for example, is a ten > card spread, so it needs 21 widgets by itself. A hundred widgets is reached > with just 10 spreads averaging 4.5 cards each. I expect, ultimately, to > have more than that. > > >> > >> As noted above, the Text widget solution only needs one. > >> > > Actually it probably needs more. Each image is a widget too, so you just > organise > > the widgets inside a Text instead of inside a Frame or Canvas. > > Is that how it works on the source level, or "under the hood"? The code > makes it look like I'm only writing one widget, with multiple text and > image elements within it, but perhaps I'm misunderstanding something. > > The approach I'm taking now is a Label widget, containing a single string > constructed with elements from lists. I'm hoping that I can take the same > approach using a single Text widget, and just convert every other string > element from a filename to an image. > > >All these things are > > just containers for more widgets. Frames are designed to hold widgets, > end of story. > > Text is designed to *display* images and text - usually within a Frame. > Canvas is > > designed to *display* images and graphics shapes. If you want your > images joined > > or surrounded by lines/circles etc then go with Canvas. If you need to > include > > explanatory text around the images use a Text. If you want to create a > reusable > > widget that you can use in multiple screens or hot swap with other > variants of > > the same go with a Frame and build a display widget hierarchy. If you > just want to > > display a bunch of images it doesn't matter much which one you pick. > > > > Then it seems Text it is. Perhaps later in development, Frames and/or > Canvases might be appropriate for more complex designs. > > > I repeat, don't sweat over the widget count, that's not usually an issue. > > > > Alan G. > > > > Thanks! > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Nov 28 23:17:51 2012 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 28 Nov 2012 22:17:51 +0000 (GMT) Subject: [Tutor] Dynamic TKinter widgets? In-Reply-To: References: <1353887349.66662.YahooMailNeo@web87901.mail.ir2.yahoo.com> Message-ID: <1354141071.70882.YahooMailNeo@web87904.mail.ir2.yahoo.com> Then I remembered that all I need to do to create a widget is simply call it and add it to the layout, so I just created a single Frame and a loop that adds a variable number of widgets. Now I just destroy that Frame (and thus, the widgets it holds), recreate it, and repopulate it. >Which, re-reading this discussion, is probably what you meant by standard practice. > >Exactly so, you create the widgets you need, then throw them away when done.? You store them in a container for the duration. So long as their associated methods? are connected to your core data then you can use them and dispose of them. >>> Don't get hung up on the number of widgets. In the scheme of things widgets are not? >>> expensive. Create them as you need them, delete them when you are done. Layout? >>> managers are there to manage the layout for you.? >> >> >>> Alan G. >> >> >> -------------- next part -------------- An HTML attachment was scrubbed... URL: From oakvillene at oxfordlearning.com Thu Nov 29 08:03:07 2012 From: oakvillene at oxfordlearning.com (Oxford Learning Centre) Date: Thu, 29 Nov 2012 02:03:07 -0500 Subject: [Tutor] Need a Python tutor Message-ID: <4BF7DF47-0975-4C0E-8E1A-F5C4D4C50E71@oxfordlearning.com> Hi there My son is in first year Engineering & he needs help with reviewing for his final next week on computer programming using Python language. Please if u have or know any one who can help him that will be a great help. He is in school in Hamilton Ontario , but you can reach me either by phone 9052571207 or by e-mail. Thanks Saly Beshara Centre Director Oxford Learning Centre Oakville N/E 380 Dundas St. East Unit D-8 905-257-1207 www.oxfordlearning.com Sent from my iPad From tara.nicholson at live.co.uk Tue Nov 20 15:39:06 2012 From: tara.nicholson at live.co.uk (Tara Nicholson) Date: Tue, 20 Nov 2012 14:39:06 +0000 Subject: [Tutor] (no subject) Message-ID: Hi, im trying to write a script which randomly generates 10,000 points(x,y) in the unit square(so range between 0 and 1 for both x and y).so far I have written the code below in red, however it only produces one random point. How do I get it to repeat this so it produces 10,000 different random points?Thankyouuu, Tara. import mathimport randomrandom.seed() x=random.uniform(0,1)y=random.uniform(0,1) for i in range(0,1): for j in range(0,1): print (x,y) -------------- next part -------------- An HTML attachment was scrubbed... URL: From unaiza.ahsan at gmail.com Tue Nov 20 15:06:04 2012 From: unaiza.ahsan at gmail.com (Unaiza Ahsan) Date: Tue, 20 Nov 2012 09:06:04 -0500 Subject: [Tutor] New to Python - simple question Message-ID: I'm on Chapter 1 of Solem's book. The following function definition needs to be added to imtools.py: [I did paste this I think in my first email]. import os from numpy import * def histeq(im,nbr_bins=256): """ Histogram equalization of a grayscale image. """ # get image histogram imhist,bins = histogram(im.flatten(),nbr_bins,normed=True) cdf = imhist.cumsum() # cumulative distribution function cdf = 255 * cdf / cdf[-1] # normalize # use linear interpolation of cdf to find new pixel values im2 = interp(im.flatten(),bins[:-1],cdf) return im2.reshape(im.shape), cdf Now this file is saved as imtools.py in my main C:\Python27 folder. In IDLE, I'm supposed to write: from PIL import Image from numpy import * im = array(Image.open(?AquaTermi_lowcontrast.jpg?).convert(?L?)) im2,cdf = imtools.histeq(im) That's it. That's the code I'm using. But it's giving me that error that "histogram" is not found. Er, I just checked the numpy version I have downloaded. It indeed doesn't have any histogram (although its documentation says it should :s). Sorry. I had checked the documentation first (and thought that this version contains histogram). I think the function histogram is not defined in numpy at all. It's in something called "mahotas" (No idea what that is). Thanks all for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vaddesreenivasulu at gmail.com Fri Nov 23 10:12:25 2012 From: vaddesreenivasulu at gmail.com (Sreenivasulu) Date: Fri, 23 Nov 2012 14:42:25 +0530 Subject: [Tutor] pyXML i Python2.6 In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474167BB1D3@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF474167BB1D3@SCACMX008.exchad.jpmchase.net> Message-ID: Hi Ramith, Thank you for your reply . I have made some modifications in pyXMl and it is working fine . I have file named as Test.py and below is the code in the file from SOAPpy import WSDL SecurityServerUrlTemplate = "http:// %s/SpinSecurity/SpinInfoExchange.asmx?WSDL" secser1="Coputername" url = SecurityServerUrlTemplate % secser1 server = WSDL.Proxy(url) print "hello" when am running python2.6 Test.py , am getting below error : xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 5 But when am running with sudo python2.6 Test.py . it was running without error . Do you have any idea on this issue. Regards, Sreenu. On Tue, Nov 20, 2012 at 11:59 PM, Prasad, Ramit wrote: > Sreenivasulu wrote: > > > > Hi, > > > > Am unable to install pyXML in Ubuntu usig python2.6 > > > > Could you please help me > > > > Regards, > > Sreenu > > Since you do not provide a link I am guessing you are referring > to the very outdated package. You use the ElementTree class or the > reputed third party module lxml. The ElementTree class is in the > Python 2.6 standard library at xml.etree.ElementTree.ElementTree. > > > You can try modifying the pyXML source (seems like a small change), > but I do not recommend this approach. > http://stackoverflow.com/questions/4953600/pyxml-on-ubuntu > > > ~Ramit > > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zaatlob at hotmail.com Fri Nov 30 10:21:21 2012 From: zaatlob at hotmail.com (leon zaat) Date: Fri, 30 Nov 2012 09:21:21 +0000 Subject: [Tutor] FW: (no subject) In-Reply-To: References: Message-ID: From: tara.nicholson at live.co.uk To: tutor at python.org Date: Tue, 20 Nov 2012 14:39:06 +0000 Subject: [Tutor] (no subject) Hi, im trying to write a script which randomly generates 10,000 points(x,y) in the unit square(so range between 0 and 1 for both x and y).so far I have written the code below in red, however it only produces one random point. How do I get it to repeat this so it produces 10,000 different random points?Thankyouuu, Tara. import mathimport randomrandom.seed() x=random.uniform(0,1)y=random.uniform(0,1) for i in range(0,1): for j in range(0,1): print (x,y) _______________________________________________ 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: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ATT00001 URL: From fomcl at yahoo.com Fri Nov 30 10:38:22 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 30 Nov 2012 01:38:22 -0800 (PST) Subject: [Tutor] Pypi entry points Message-ID: <1354268302.58416.YahooMailNeo@web163802.mail.gq1.yahoo.com> Hi, I am reading The Hitchhiker's Guide to Packaging 1.0 documentation, specifically http://guide.python-distribute.org/creation.html. I am struggling to understand the section about Entry Points. This appears to be a way to include extra functionality in a program, without the need to actually include it in the tar.gz file. Or, as the website says: "[A] pretty easy and simple way to allow other packages to register something that you want to know. Extra plugins, extra render methods, extra functionality you want to register in your web application, etcetera." I find the code examples hard to understand. I'd expect that it'd be steps like "in the middle of the setup, download and unzip file xxxx.zip from website http://blaaah.eu. How does this work? ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From steve at pearwood.info Fri Nov 30 11:03:10 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 30 Nov 2012 21:03:10 +1100 Subject: [Tutor] FW: (no subject) In-Reply-To: References: Message-ID: <50B8845E.8020909@pearwood.info> Hello Tara, or is it Leon? On 30/11/12 20:21, leon zaat wrote: > Hi, im trying to write a script which randomly generates 10,000 points(x,y) >in the unit square(so range between 0 and 1 for both x and y).so far I have > written the code below in red, What red? I see no red. Please do not rely on colour in email, for at least two reasons: 1) For colour to be visible in your email, you must have so-called "Rich Text" (actually HTML mail) turned on. Many people have HTML mail turned off, because it is a security and privacy threat, or simply do not appreciate having somebody else's choice of colour and font being forced on them. 2) About 8% of men and 0.5% of women have red-green colour-blindness, with other forms of colour-blindness being less common. All up, about 1 in 10 men and 1 in 100 women cannot easily or at all distinguish colours. Others may be partially or completely blind. Using a screen reader, they can still "read" the words you send, but will have no idea at all about colours. >however it only produces one random point. How do I get it to repeat this so it > produces 10,000 different random points? import math import random random.seed() x=random.uniform(0,1) y=random.uniform(0,1) This generates one random point, because it gets executed once. After generating that single random point, you then loop 1x1 times: for i in range(0,1): # this line loops once for j in range(0,1): # and this also loops once print (x,y) so it only 1x1 = 1 time. The solution is simple: if you want to generate 10,000 points, you must put the code that chooses a random point inside something that will loop 10,000 times. Here's an example that will loop 20 times: for i in range(20): # Pick an x and y ar random x = random.uniform(0,1) y = random.uniform(0,1) print (x, y) All you have to do now is extend that to loop 10000 times instead of 20. -- Steven From steve at pearwood.info Fri Nov 30 11:28:21 2012 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 30 Nov 2012 21:28:21 +1100 Subject: [Tutor] Need a Python tutor In-Reply-To: <4BF7DF47-0975-4C0E-8E1A-F5C4D4C50E71@oxfordlearning.com> References: <4BF7DF47-0975-4C0E-8E1A-F5C4D4C50E71@oxfordlearning.com> Message-ID: <50B88A45.2060308@pearwood.info> Hi Saly, My comments below. On 29/11/12 18:03, Oxford Learning Centre wrote: > Hi there > My son is in first year Engineering& he needs help with reviewing >for his final next week on computer programming using Python >language. Please if u have or know any one who can help him that >will be a great help. He is in school in Hamilton Ontario , but >you can reach me either by phone 9052571207 or by e-mail. Are you looking for a paid tutor who can come out and work with your son in person? I'm not sure if anyone here is from Canada, let alone Hamilton, but you may be lucky. If not, with your permission I can pass your details on if I can find anyone in the area. Otherwise, we're more than happy to help your son via email, on this mailing list. Regards, -- Steven From fomcl at yahoo.com Fri Nov 30 12:15:34 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 30 Nov 2012 03:15:34 -0800 (PST) Subject: [Tutor] FW: (no subject) In-Reply-To: <50B8845E.8020909@pearwood.info> References: <50B8845E.8020909@pearwood.info> Message-ID: <1354274134.90885.YahooMailNeo@web163803.mail.gq1.yahoo.com> >> Hi, im trying to write a script which randomly generates 10,000 points(x,y) >> in the unit square(so range between 0 and 1 for both x and y).so far I have >> written the code below in red, > >What red? I see no red. > >Please do not rely on colour in email, for at least two reasons: > >1) For colour to be visible in your email, you must have so-called "Rich Text" >???(actually HTML mail) turned on. Many people have HTML mail turned off, >???because it is a security and privacy threat, or simply do not appreciate >???having somebody else's choice of colour and font being forced on them. > >2) About 8% of men and 0.5% of women have red-green colour-blindness, with other >???forms of colour-blindness being less common. All up, about 1 in 10 men and 1 >???in 100 women cannot easily or at all distinguish colours. Others may be >???partially or completely blind. Using a screen reader, they can still "read" >???the words you send, but will have no idea at all about colours. > Aside from colour-blindness, using (saturated) red and blue is an ergnomical no-no as the human eye is relatively insensitive to those colors: http://www.lawrence-najjar.com/papers/Using_color_effectively.html http://hyperphysics.phy-astr.gsu.edu/hbase/vision/colcon.html From fomcl at yahoo.com Fri Nov 30 17:43:08 2012 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 30 Nov 2012 08:43:08 -0800 (PST) Subject: [Tutor] how to struct.pack a unicode string? Message-ID: <1354293788.96740.YahooMailNeo@web163803.mail.gq1.yahoo.com> Hi, How can I pack a unicode string using the struct module? If I simply use packed = struct.pack(fmt, hello) in the code below (and 'hello' is a unicode string), I get this: "error: argument for 's' must be a string". I keep reading that I have to encode it to a utf-8 bytestring, but this does not work (it yields mojibake and tofu output for some of the languages). It's annoying if one needs to know the encoding in which each individual language should be represented. I was hoping "unicode-internal" was the way to do it, but this does not reproduce the original string when I unpack it.. :-( # Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)] on win32 import sys import struct greetings = \ ??????? [['Arabic', [1575, 1604, 1587, 1604, 1575, 1605, 32, 1593, 1604, 1610, 1603, ???????????????????? 1605], 'cp1256'], # 'cp864' 'iso8859_6' ???????? ['Assamese', [2472, 2478, 2488, 2509, 2453, 2494, 2544], 'utf-8'], ???????? ['Bengali', [2438, 2488, 2488, 2494, 2482, 2494, 2478, 2497, 32, 2438, ????????????????????? 2482, 2494, 2439, 2453, 2497, 2478], 'utf-8'], ???????? ['Georgian', [4306, 4304, 4315, 4304, 4320, 4335, 4317, 4305, 4304], 'utf-8'], ???????? ['Kazakh', [1057, 1241, 1083, 1077, 1084, 1077, 1090, 1089, 1110, 1079, 32, ???????????????????? 1073, 1077], 'utf-8'], ???????? ['Russian', [1047, 1076, 1088,1072, 1074, 1089, 1090, 1074, 1091, 1081, ????????????????????? 1090, 1077], 'utf-8'], ???????? ['Spanish', [161, 72, 111, 108, 97, 33], 'cp1252'], ???????? ['Swiss German', [71, 114, 252, 101, 122, 105], 'cp1252'], ???????? ['Thai', [3626, 3623, 3633, 3626, 3604, 3637], 'cp874'], ???????? ['Walloon', [66, 111, 110, 100, 106, 111, 251], 'cp1252']]???? for greet in greetings: ??? language, chars, encoding = greet ??? hello = "".join([unichr(i) for i in chars]) ??? #print language, hello, encoding? # prints everything as it should look ??? endianness = "<" if sys.byteorder == "little" else ">" ??? fmt = endianness + str(len(hello)) + "s" ??? #https://code.activestate.com/lists/python-list/301601/ ??? #http://bytes.com/topic/python/answers/546519-unicode-strings-struct-files ??? #packed = struct.pack(fmt, hello.encode('utf_32_le')) ??? #packed = struct.pack(fmt, hello.encode(encoding)) ??? #packed = struct.pack(fmt, hello.encode('utf_8')) ??? packed = struct.pack(fmt, hello.encode("unicode-internal")) ??? print struct.unpack(fmt, packed)[0].decode("unicode-internal")? # UnicodeDecodeError: 'unicode_internal' codec can't decode byte 0x00 in position 12: truncated input Thank you in advance! ? Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From __peter__ at web.de Fri Nov 30 19:26:36 2012 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 Nov 2012 19:26:36 +0100 Subject: [Tutor] how to struct.pack a unicode string? References: <1354293788.96740.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: Albert-Jan Roskam wrote: > How can I pack a unicode string using the struct module? If I simply use > packed = struct.pack(fmt, hello) in the code below (and 'hello' is a > unicode string), I get this: "error: argument for 's' must be a string". I > keep reading that I have to encode it to a utf-8 bytestring, but this does > not work (it yields mojibake and tofu output for some of the languages). You keep reading it because it is the right approach. You will not get mojibake if you decode the "packed" data before using it. Your code basically becomes for greet in greetings: language, chars, encoding = greet hello = "".join([unichr(i) for i in chars]) packed = hello.encode("utf-8") unpacked = packed.decode("utf-8") print unpacked I don't know why you mess with byte order, perhaps you can tell a bit about your actual use-case.